3 # CGI wrapper to qchess
14 path = "../qchess-cgi-data/"
16 def open_fifo(name, mode, timeout=None):
18 return open(name, mode)
21 class Worker(threading.Thread):
23 threading.Thread.__init__(self)
30 self.result = open(name, mode)
40 while time.time() - start < timeout:
41 if w.is_alive() == False:
43 if w.exception != None:
50 #sys.stderr.write("FIFO_TIMEOUT!\n")
51 # Recursive to deal with possible race condition
54 f = open_fifo(name, "w", 1)
56 f = open_fifo(name, "r", 1)
60 #sys.stderr.write("Opened other end!\n")
67 raise Exception("FIFO_TIMEOUT")
70 if w.exception != None:
76 if os.path.exists(path+client+".in") and os.path.exists(path+client+".out"):
78 fifo_out = open_fifo(path+client+".in", "w", 5)
83 fifo_out.write("quit\n")
87 fifo_in = open_fifo(path+client+".out", "r", 5)
92 s = fifo_in.readline().strip(" \r\n")
95 s = fifo_in.readline().strip(" \r\n")
98 log = open(path+client, "a")
99 log.write(" -> %s\n" % str(datetime.datetime.now()))
108 print "Content-Type: text/plain\r\n\r\n"
111 form = cgi.FieldStorage()
112 client = cgi.escape(os.environ["REMOTE_ADDR"])
114 #client = "127.0.0.1"
140 if os.path.exists(path+client+".in") and os.path.exists(path+client+".out"):
141 if request == "quit":
146 print "Game in progress expects x and y."
148 elif request == "start":
150 args = [path+"qchess.py", "--no-graphics"]
151 if mode == None or mode == "bishop":
152 args += ["@fifo:../qchess-cgi-data/"+client, "@internal:AgentBishop"]
154 args += ["@fifo:../qchess-cgi-data/"+client, "@internal:AgentRandom"]
155 elif mode == "eigengame":
156 args += ["--server=progcomp.ucc.asn.au", "@fifo:../qchess-cgi-data/"+client]
157 subprocess.Popen(args)
160 log = open(path+client, "a")
161 log.write("%s" % str(datetime.datetime.now()))
165 print "No game in progress."
169 if not (os.path.exists(path+client+".in") and os.path.exists(path+client+".out")):
170 print "No game in progress."
174 fifo_out = open_fifo(path+client+".in", "w")
178 fifo_out.write("%d %d\n" % (x, y))
183 #sys.stderr.write("\ncgi read from fifo here\n")
185 fifo_in = open_fifo(path+client+".out", "r")
189 #sys.stderr.write("Opened fine\n")
190 s = fifo_in.readline().strip(" \r\n")
192 while s != "SELECT?" and s != "MOVE?" and not s.split(" ")[0] in ["white","black"]:
196 s = fifo_in.readline().strip(" \r\n")
199 if s.split(" ")[0] in ["white", "black"]:
200 #sys.stderr.write("cgi quit!\n")
203 #sys.stderr.write("Done\n")
207 if __name__ == "__main__":
209 sys.exit(main(sys.argv))
212 sys.stderr.write(str(e) + "\n")