生命游戏 game of life

生命游戏为1970年英国数学家J. H. Conway所提出,某一细胞的邻居包括上、下、左、右、左上、左下、右上与之相邻的细胞,游戏规则如下:
1.孤单死亡:如果细胞的邻居小于一个,则该细胞在下一次状态将死亡
2.拥挤死亡:如果细胞的邻居在四个以上,则该细胞在下一次状态将死亡
3.稳定:如果细胞的邻居为2或3个,则下一次状态为稳定存活
4.复活:如果某位置无细胞存活,而该位置的邻居为3个,则该位置将复活一个细胞
有题目的意思可以看出,当邻居个数为0、1、4、5、6、7、时,该细胞的下次状态为死亡
                      邻居个数为2时,该细胞的下次状态为稳定存活
                      邻居个数为3时,该细胞的下次状态为复活

class LifeGame
  def initialize(max_row,max_column)
    @map=[]
    @newmap=[]
    for i in 0...max_row
      @map<<[false]*max_column
      @newmap<<[false]*max_column
    end
  end

  def _cell(x,y)
    @map[x][y]=true
  end

  def _next
    for row in 0...(@map.size)
      for col in 0...(@map[0].length)
        n=_neighbors(row,col)
        if [0,1,4,5,6,7,8].include? n
          @newmap[row][col]=false
        elsif n==2
          @newmap[row][col]=@map[row][col]
        else n==3
          @newmap[row][col]=true
        end
#        case n
#        when n.in[0,1,4,5,6,7,8]
#          @newmap[row][col]=false
#        when n==2
#          @newmap[row][col]=@map[row][col]
#        when n==3
#          @newmap[row][col]=true
#        end
      end
      for i in [email protected]
        for j in 0..@map[0].length-1
          @map[i][j]=@newmap[i][j]
        end
      end
    end
  end

  def _print
    print("\nGame of life cell status")
    for row in [email protected]
      print("\n")
      for col in 0...@map[0].size
        if @map[row][col]
          print("#")
        else
          print("-")
        end
      end
    end
  end

  def _neighbors(row,col)
    count = 0
    for r in Range.new(row-1, row+1)
      for c in Range.new(col-1, col+1)
        rc = r < 0 or r >= @map.size
        cc = c < 0 or c >= @map[0].size
        if  rc or cc
          next
        end
        if @map[r][c]
          count += 1
        end
      end
    end
    if @map[row][col] == true
      count -= 1
    end
    return count
  end
end


game = LifeGame.new(10, 25)
print("Game of life Program")
print("Enter x, y where x, y is living cell")
print("0 <= x < 10, 0 <= y < 25")
print("Terminate with x, y = -1, -1")
while(true)
    strs = gets.chomp.split(",")
    row = strs[0].to_i
    col = strs[1].to_i
    if row >= 0 and row < 10 and col >= 0 and row < 25
        game._cell(row, col)
    else row == -1 or col == -1
        break
    end
end

while(true)
    game._print
    game._next
    print("\nContinue next Generation ?")
    if gets.chomp!.upcase== "N"
      break
    end
end



你可能感兴趣的:(游戏,C++,c,C#,Ruby)