diff options
author | tomsmeding <hallo@tomsmeding.nl> | 2015-10-18 21:20:18 +0200 |
---|---|---|
committer | tomsmeding <hallo@tomsmeding.nl> | 2015-10-18 21:20:18 +0200 |
commit | b5077ff9a36c89c84c04f33dce3a2a0ff45e9184 (patch) | |
tree | 9cdbecbd6a188ca8de874d01a6cdc04adb1582f2 /interactor.js |
Initial
Diffstat (limited to 'interactor.js')
-rwxr-xr-x | interactor.js | 96 |
1 files changed, 96 insertions, 0 deletions
diff --git a/interactor.js b/interactor.js new file mode 100755 index 0000000..2d38cbb --- /dev/null +++ b/interactor.js @@ -0,0 +1,96 @@ +#!/usr/bin/env node + +var aicmd; + +if(process.argv.length!=3){ + console.log("Give AI command to run as command line argument."); + process.exit(1); +} +aicmd=process.argv[2]; +console.log("Using AI command '"+aicmd+"'"); + + +var app=require("express")(), + http=require("http").Server(app), + io=require("socket.io")(http), + fs=require("fs"), + spawn=require("child_process").spawn; + +eval(String(fs.readFileSync("common.js"))); + + +var HTTPPORT=8080; + +var uniqid=(function(){ + var id=0; + return function(){return id++;}; +})(); + +app.get("/",function(req,res){ + res.sendFile(__dirname+"/index.html"); +}); + +["index.html","common.js"].forEach(function(fname){ + app.get("/"+fname,function(req,res){ + res.sendFile(__dirname+"/"+fname); + }); +}); + +io.on("connection",function(conn){ + var id=uniqid(); + console.log("New IO connection id "+id); + + var bd=emptyboard(); + var aiplayer=0; + + conn.on("disconnect",function(){ + console.log("Disconnect id "+id); + }); + conn.on("usermove",function(idx){ + idx=+idx; + if(idx<0||idx>=W*H){ + conn.emit("alert","You sent an invalid move, index "+idx); + conn.emit("getusermove"); + return; + } + var x=idx%W,y=~~(idx/W); + bd[y][x].c=1-aiplayer; + bd[y][x].n++; + bd=stabilise(bd); + proc.stdin.write(x+" "+y+"\n"); + }); + + + var proc=spawn("sh",["-c",aicmd],{ + stdio:["pipe","pipe","inherit"] + }); + var buffer=""; + proc.stdout.on("data",function(data){ + var idx,line,mv; + buffer+=data; + while((idx=buffer.indexOf("\n"))!=-1){ + line=buffer.slice(0,idx); + buffer=buffer.slice(idx+1); + mv=line.split(" ").map(function(s){return parseInt(s,10);}); + if(mv.length!=2||isNaN(mv[0])||isNaN(mv[1])){ + console.log("Invalid move written by AI: '"+line+"'"); + conn.emit("alert","Invalid move written by AI: '"+line+"'"); + mv[0]=0; + mv[1]=0; + } + bd[mv[1]][mv[0]].c=aiplayer; + bd[mv[1]][mv[0]].n++; + bd=stabilise(bd); + conn.emit("applymove",{index:W*mv[1]+mv[0],player:aiplayer}); + conn.emit("setonturn",1-aiplayer); + conn.emit("getusermove"); + } + }); + proc.stdin.write("A\n-1 -1\n"); + conn.emit("emptyboard"); + conn.emit("setonturn",0); +}); + +http.listen(HTTPPORT,function(){ + console.log("Listening on http://localhost:"+HTTPPORT); +}); |