Skip to content

Instantly share code, notes, and snippets.

@firstspring1845
Last active August 29, 2015 14:03
Show Gist options
  • Save firstspring1845/aa1adfcc3e19cff19f64 to your computer and use it in GitHub Desktop.
Save firstspring1845/aa1adfcc3e19cff19f64 to your computer and use it in GitHub Desktop.
適当ライフゲーム
class Field
def initialize(x,y)
@x = x
@y = y
@m = x.times.map{[false]*y}
end
def get_size
[@x,@y]
end
def set_cell(x,y,v)
if x < 0 or y < 0 or x >= @x or y >= @y
raise IndexError.new(':(')
end
@m[y][x] = v
end
def get_cell(x,y,default=nil)
if x < 0 or y < 0 or x >= @x or y >= @y
if default != nil
return default
end
raise IndexError.new(':(')
end
@m[y][x]
end
def to_show
@m.map{|l|l.map{|c|c ? 1 : 0}.join}.join("\n")
end
#|x,y,value|
def each(&proc)
@x.times.to_a.product(@y.times.to_a).each{|p|
proc.call(p[0],p[1],get_cell(p[0],p[1]))
}
end
end
require './field.rb'
def put_help
puts 'This is life game:)'
puts 'Commands:s'
puts 's:Show field'
puts 'p:Play 1 step'
puts 'q:Quit'
end
def play
f = Marshal.load(Marshal.dump($f))
f.each{|x,y,value|
adj = [-1,0,1].product([-1,0,1]).select{|a|a != [0,0]}
lives = adj.inject(0){|sum,p|sum + (f.get_cell(x+p[0],y+p[1],false) ? 1 : 0)}
case [value,lives]
when ->l{!l[0] and l[1] == 3} #birth
$f.set_cell(x,y,true)
when ->l{l[0] and [2,3].include?(l[1])} #live
$f.set_cell(x,y,true)
when ->l{l[0] and l[1] >= 1} #depopulation
$f.set_cell(x,y,false)
when ->l{l[0] and l[1] <= 4} #overpopulation
$f.set_cell(x,y,false)
end
}
end
puts 'Please input field size(ex. : 50 50[Enter])'
s = gets.split.map{|s|s.to_i}
$f = Field.new(s[0],s[1])
$f.instance_eval{
set_cell(1,0,true)
set_cell(2,1,true)
set_cell(0,2,true)
set_cell(1,2,true)
set_cell(2,2,true)
}
k = ''
while not k.include?('q')
k = gets.chomp
case k
when ''
put_help
when 's'
puts $f.to_show
when 'p'
play
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment