summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--interactor/common.js19
-rw-r--r--interactor/index.html4
-rwxr-xr-xinteractor/interactor.js30
3 files changed, 51 insertions, 2 deletions
diff --git a/interactor/common.js b/interactor/common.js
index 65313ce..af7c462 100644
--- a/interactor/common.js
+++ b/interactor/common.js
@@ -16,6 +16,24 @@ function bdcopy(bd){
});
}
+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;
+}
+
+function countballs(bd){
+ var count=0;
+ var x,y;
+ for(y=0;y<H;y++)for(x=0;x<W;x++)count+=bd[y][x].n;
+ return count;
+}
+
function stabilise(bd){
var newbd;
var changes;
@@ -38,6 +56,7 @@ function stabilise(bd){
}
}
bd=newbd;
+ if(checkwin(bd)!=-1)break;
} while(changes);
return bd;
}
diff --git a/interactor/index.html b/interactor/index.html
index c861c82..21892c7 100644
--- a/interactor/index.html
+++ b/interactor/index.html
@@ -112,6 +112,7 @@ function stabiliseanims(bd){
}
bd=newbd;
anims.push([stage,bdcopy(bd)]);
+ if(checkwin(bd)!=-1)break;
} while(stage.length);
return anims;
}
@@ -203,6 +204,9 @@ socket.on("setonturn",function(player){
socket.on("getusermove",function(){
getusermove();
});
+socket.on("win",function(player){
+ setstatustext("<b>Player "+(player+1)+" won</b>");
+});
</script>
</head>
<body onload="init()">
diff --git a/interactor/interactor.js b/interactor/interactor.js
index 2d38cbb..843bf2c 100755
--- a/interactor/interactor.js
+++ b/interactor/interactor.js
@@ -36,6 +36,16 @@ app.get("/",function(req,res){
});
});
+function stopproc(proc){
+ proc.stdin.write("Quit\n");
+ var timeout=setTimeout(function(){
+ proc.kill();
+ },500);
+ proc.on("exit",function(){
+ clearTimeout(timeout);
+ });
+}
+
io.on("connection",function(conn){
var id=uniqid();
console.log("New IO connection id "+id);
@@ -57,16 +67,24 @@ io.on("connection",function(conn){
bd[y][x].c=1-aiplayer;
bd[y][x].n++;
bd=stabilise(bd);
+ if(countballs(bd)>2){
+ var win=checkwin(bd);
+ if(win!=-1){
+ conn.emit("win",1-aiplayer);
+ stopproc(proc);
+ return;
+ }
+ }
proc.stdin.write(x+" "+y+"\n");
});
var proc=spawn("sh",["-c",aicmd],{
- stdio:["pipe","pipe","inherit"]
+ stdio:["pipe","pipe",process.stderr]
});
var buffer="";
proc.stdout.on("data",function(data){
- var idx,line,mv;
+ var idx,line,mv,win;
buffer+=data;
while((idx=buffer.indexOf("\n"))!=-1){
line=buffer.slice(0,idx);
@@ -82,6 +100,14 @@ io.on("connection",function(conn){
bd[mv[1]][mv[0]].n++;
bd=stabilise(bd);
conn.emit("applymove",{index:W*mv[1]+mv[0],player:aiplayer});
+ if(countballs(bd)>2){
+ win=checkwin(bd);
+ if(win!=-1){
+ conn.emit("win",aiplayer);
+ stopproc(proc);
+ return;
+ }
+ }
conn.emit("setonturn",1-aiplayer);
conn.emit("getusermove");
}