News:

SMF - Just Installed!

Main Menu

Conway's Game of Life in SketchUp

Started by Medeek, December 31, 2018, 02:42:23 AM

Previous topic - Next topic

0 Members and 1 Guest are viewing this topic.

Medeek

Conway's Game of Life or Saturday Night Fever, I'm not sure which:



If the grid is much bigger than 20x20 it really slows down, at least on my computer.

Something like this probably needs to run at a lower level than the Ruby API.

My code is below:



    ### Conway Gameboard ####

    model = Sketchup.active_model
    entities = model.active_entities
    @view = model.active_view
    @faces = []

    @cycles = 0
    ysize = 18
    xsize = 18
    blk = 12

    model.start_operation('Generate Game Board', true, false, true)

    for j in 0..(ysize-1)

       for i in 0..(xsize-1)
          i2 = i + 1
          j2 = j + 1
          pt1 = [(i*blk),(j*blk),0]
          pt2 = [(i2*blk),(j*blk),0]
          pt3 = [(i2*blk),(j2*blk),0]
          pt4 = [(i*blk),(j2*blk),0]
          face1 = entities.add_face(pt1, pt2, pt3, pt4)
         
          face1.reverse! if (rand(4)<2)

          @faces << face1
       end
    end

    model.commit_operation


    def calc_conway

       @update_array = []

       for facei in @faces
       
          adj_live_count = 0
         
          if facei.normal.samedirection? Z_AXIS
             facei_status = true
          else
             facei_status = false
          end
       
          adj_faces_list = @faces.find_all { |e| !facei.bounds.intersect(e.bounds).empty? }
          adj_faces_list.delete(facei)
         
          for face_adj in adj_faces_list
             if face_adj.normal.samedirection? Z_AXIS
                adj_live_count += 1
             end   
          end
       
          if facei_status
             # Cell is Live
             if adj_live_count < 2
                @update_array << true
             elsif adj_live_count < 4
                @update_array << false
             else
                @update_array << true
             end
          else
             # Cell is Dead
             if adj_live_count == 3
                @update_array << true
             else
                @update_array << false
             end
          end
       end

       counter = 0
       for facei in @faces
          if @update_array[counter]
             facei.reverse!
          end
          counter += 1
       end

       @view.refresh
       @cycles += 1

       if @cycles > 200
          UI.stop_timer(@conwaytimer)
       end
    end


    model.start_operation('Run Game of Life', true, false, true)

    @conwaytimer = UI.start_timer(0.02, true) { calc_conway }

    model.commit_operation
Nathaniel P. Wilkerson, P.E.