diff options
author | tomsmeding <hallo@tomsmeding.nl> | 2015-12-05 20:40:32 +0100 |
---|---|---|
committer | tomsmeding <hallo@tomsmeding.nl> | 2015-12-05 20:40:32 +0100 |
commit | 1954ed67ef61c509560418a9d2da58083b822996 (patch) | |
tree | 870237504df86fcdd6cfaab2948e73e7211cf95d /common.js |
Initial enzo
Diffstat (limited to 'common.js')
-rw-r--r-- | common.js | 82 |
1 files changed, 82 insertions, 0 deletions
diff --git a/common.js b/common.js new file mode 100644 index 0000000..e77db07 --- /dev/null +++ b/common.js @@ -0,0 +1,82 @@ +var W=8,H=9; + +if(typeof module=="undefined")module=false; //hack to support client-side importing + +if(module)module.exports["emptyboard"]=emptyboard; +function emptyboard(){ + return new Array(H).fill(0).map(function(){ + return new Array(W).fill(0).map(function(){ + return {n:0,c:0}; + }); + }); +} + +if(module)module.exports["bdcopy"]=bdcopy; +function bdcopy(bd){ + return bd.map(function(r){ + return r.map(function(c){ + return {n:c.n,c:c.c}; + }); + }); +} + +if(module)module.exports["checkwin"]=checkwin; +function checkwin(bd){ + var wincolour=-1,i; + for(i=0;i<W*H;i++){ + if(bd[~~(i/W)][i%W].n){ + if(wincolour==-1)wincolour=bd[~~(i/W)][i%W].c + else if(bd[~~(i/W)][i%W].c!=wincolour)return -1; + } + } + return wincolour; +} + +if(module)module.exports["countballs"]=countballs; +function countballs(bd,p){ + var count=0; + var x,y; + if(p==undefined){ + for(y=0;y<H;y++)for(x=0;x<W;x++)count+=bd[y][x].n; + } else { + for(y=0;y<H;y++)for(x=0;x<W;x++)count+=bd[y][x].n*(bd[y][x].c==p); + } + return count; +} + +if(module)module.exports["stabilise"]=stabilise; +function stabilise(bd){ + var newbd; + var changes; + var x,y,nnei,quo; + do { + changes=false; + newbd=bdcopy(bd); + for(y=0;y<H;y++){ + for(x=0;x<W;x++){ + nnei=(y>0)+(x>0)+(y<H-1)+(x<W-1); + if(bd[y][x].n>=nnei){ + quo=~~(bd[y][x].n/nnei); + newbd[y][x].n-=quo*nnei; + if(y>0) {newbd[y-1][x].n+=quo;newbd[y-1][x].c=bd[y][x].c;} + if(x>0) {newbd[y][x-1].n+=quo;newbd[y][x-1].c=bd[y][x].c;} + if(y<H-1){newbd[y+1][x].n+=quo;newbd[y+1][x].c=bd[y][x].c;} + if(x<W-1){newbd[y][x+1].n+=quo;newbd[y][x+1].c=bd[y][x].c;} + changes=true; + } + } + } + bd=newbd; + if(checkwin(bd)!=-1)break; + } while(changes); + return bd; +} + + + +if(module)module.exports["validatenick"]=validatenick; +function validatenick(nick){ + return /^[a-zA-Z0-9_-]{3,}$/.test(nick); +} + +Array.prototype.fill=Array.prototype.fill||function(t){if(null==this)throw new TypeError("this is null or not defined");for(var r=Object(this),n=r.length>>>0,i=arguments[1],a=i>>0,e=0>a?Math.max(n+a,0):Math.min(a,n),o=arguments[2],h=void 0===o?n:o>>0,l=0>h?Math.max(n+h,0):Math.min(h,n);l>e;)r[e]=t,e++;return r}; |