1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
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);
});
|