Vianoce v ITnetwork sú tu! Dobí si teraz kredity a získaj až 80 % extra kreditov na e-learningové kurzy ZADARMO. Zisti viac.
Hľadáme nové posily do ITnetwork tímu. Pozri sa na voľné pozície a pridaj sa k najagilnejšej firme na trhu - Viac informácií.

Kolónie baktériu (Conwayova hra života)

Ukážkový program Kolónie baktérií (Conwayova hra života) vrátane zdrojového kódu v jazyku Ruby.

require 'rexml/document'

class Colony

  # outputs colony
  def output(target)
    @height.times do |h|
      @width.times do |w|
        if (@cells[w][h])
          target.print "*"
        else
          target.print "."
        end
      end
      target.puts
    end
  end

  # performs one lifecycle
  def live
    # awful duplication of an array
    @old_cells = []
    (@width).times do |w|
      @row = []
      (@height).times do |h|
        @row << @cells[w][h]
      end
      @old_cells << @row
    end
    # and then the God comes
    @height.times do |h|
      @width.times do |w|
        # will it survive?
        @cells[w][h] = false
        if @old_cells[w][h]  # ziva bunka
          @cells[w][h] = true if (get_neighbours(w, h) == 2) || (get_neighbours(w, h) == 3)
        end
        if not @old_cells[w][h]  # mrtva bunka
          @cells[w][h] = true if (get_neighbours(w, h) == 3)
        end
      end
    end
  end

  # loads cells
  def load(fname)
    # does input file exists?
    if not File.exists?(fname)
      puts "Input file does not exists"
      exit
    end
    File.open(fname) do |f|
      doc = REXML::Document.new(f)
      @width = doc.root.elements["dimensions"].attributes["x"].to_i
      if (doc.root.elements["dimensions"].attributes.has_key?("y"))
        @height = doc.root.elements["dimensions"].attributes["y"].to_i
      else
        @height = @width
      end
      # creating matrix - also awful
      @cells = []
      (@width).times do |w|
        @row = []
        (@height).times { @row << false }
        @cells << @row
      end
      # filling matrix
      doc.root.elements["cells"].elements.each do |element|
        x = element.attributes["x"].to_i - 1
        y = element.attributes["y"].to_i - 1
        @cells[x][y] = true
      end
    end
  end

  private

  #  returns number of neighbouring cells
  def get_neighbours(x, y)
    count = 0
    # classic rectangle
    3.times do |h|
      3.times do |w|
        posx = x + w - 1
        posy = y + h - 1
        # placement correction
        posx = @width - 1 if (posx < 0)
        posx = 0 if (posx > @width - 1)
        posy = @height - 1 if (posy < 0)
        posy = 0 if (posy > @height - 1)
        if (@old_cells[posx][posy])
          count += 1
        end
      end
    end
    count -= 1 if (@old_cells[x][y]) # if center cell is alive I have to remove it
    return count
  end

end


# ------------ main program -----------


if (ARGV[0].length == 0)
  puts "Not enought arguments"
  exit
end

colony = Colony.new

colony.load(ARGV[0])

puts "Welcome to Conway's game of life"
puts "--------------------------------"
colony.output(STDOUT)
# commnads processing loop
command = ""
while (command != "x") do
  print "Enter command: "
  command = STDIN.gets.strip
  count = 1                                            # n with param.
  if command =˜ /ˆn\s+\d+/
    count = command.split(" ").last.to_i
    command = "n"
  end
  if (command =˜ /ˆn$/) || (command == "")             #n processing
    count.times { colony.live }
    colony.output(STDOUT)
  elsif command =˜ /ˆs\s+\w+\.[A-Za-z]{3}$/            # s
    begin
      fname = command.split(" ").last
      begin
        File.open(fname,"w") { |f| colony.output(f) }
        puts "Successfuly saved"
      rescue
        puts "Cannot save file"
      end
    end
  elsif (command =˜ /ˆ(h|\?)$/)                        # h
    puts "Help"
    puts "----"
    puts "n - perform lifecycle"
    puts "n y - perform next y lifecycles"
    puts "s filename.ext - saves colony into file"
    puts "h or ? -this help"
    puts "x - terminate"
  else
    puts "Unknows command or parametter, type 'h' to access help" if (command != "x")
  end

end

puts "Terminated."


 

Stiahnuť

Stiahnutím nasledujúceho súboru súhlasíš s licenčnými podmienkami

Stiahnuté 458x (1.96 kB)
Aplikácia je vrátane zdrojových kódov v jazyku Ruby

 

Všetky články v sekcii
Ruby
Program pre vás napísal David Hartinger
Avatar
Užívateľské hodnotenie:
Ešte nikto nehodnotil, buď prvý!
David je zakladatelem ITnetwork a programování se profesionálně věnuje 15 let. Má rád Nirvanu, nemovitosti a svobodu podnikání.
Unicorn university David sa informačné technológie naučil na Unicorn University - prestížnej súkromnej vysokej škole IT a ekonómie.
Aktivity