Skip to content

Instantly share code, notes, and snippets.

@bearice
Created January 30, 2014 14:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bearice/8709389 to your computer and use it in GitHub Desktop.
Save bearice/8709389 to your computer and use it in GitHub Desktop.
_ = require 'underscore'
class Board
constructor: (@width=10,@height=10,@mine_count=10) ->
@cells = []
for i in [0..@width*@height-1]
@cells.push {x: i % @width, y: Math.floor(i / @width), c:'x', g:'x', b:false, v:false}
tmp = _.sample(@cells, @mine_count)
_.each tmp,(c) ->
c.b = true
_.each @cells, (c) =>
c.c = _.chain(@neighborOf c.x,c.y).filter((c) -> c.b).size().value()
@groups = []
_.chain(@cells)
.filter((c)-> (c.c is 0) and (not c.b))
.each (c)=>
p = @getCellAt c.x-1,c.y
u = @getCellAt c.x,c.y-1
if u && u.c == 0
c.g = u.g
else if p && p.c == 0
c.g = p.g
else
c.g = @groups.length
@groups.push {id: c.g, members:[]}
@groups[c.g].members.push c
if p && p.c == 0 and u && u.c == 0 && p.g != u.g
pg = @groups[p.g]
ug = @groups[u.g]
if pg != ug
_.each pg.members, (c) =>
c.g = ug.id
ug.members = pg.members.concat ug.members
@groups[p.g] = ug
getCellAt: (x,y) ->
return undefined unless 0 <= x < @width and 0 <= y < @height
@cells[y*@width+x]
neighborOf: (x,y) ->
_.compact [
@getCellAt(x-1,y-1),
@getCellAt(x-1,y),
@getCellAt(x-1,y+1),
@getCellAt(x,y-1),
@getCellAt(x,y+1),
@getCellAt(x+1,y-1),
@getCellAt(x+1,y),
@getCellAt(x+1,y+1),
]
toString: ->
buf = (c.b&&'x'||c.c for c in @cells).join('')
buf2 = (c.g for c in @cells).join('')
lines = []
lines.push buf.substr(i*@width, @width) + " " + buf2.substr(i*@width, @width) for i in [0..@height]
str = lines.join '\n'
#str += JSON.stringify _.uniq(@groups),false,' '
b = new Board 10,10,5
console.info b.toString()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment