[Toss-devel-svn] SF.net SVN: toss:[1438] trunk/Toss
Status: Beta
Brought to you by:
lukaszkaiser
|
From: <luk...@us...> - 2011-05-13 22:22:09
|
Revision: 1438
http://toss.svn.sourceforge.net/toss/?rev=1438&view=rev
Author: lukaszkaiser
Date: 2011-05-13 22:22:02 +0000 (Fri, 13 May 2011)
Log Message:
-----------
WebClient handling fully in TossServer, removing python files.
Modified Paths:
--------------
trunk/Toss/Server/DB.ml
trunk/Toss/Server/DB.mli
trunk/Toss/Server/ReqHandler.ml
trunk/Toss/Server/ReqHandler.mli
trunk/Toss/Server/ReqHandlerTest.ml
trunk/Toss/Server/Server.ml
trunk/Toss/WebClient/.cvsignore
Removed Paths:
-------------
trunk/Toss/WebClient/Handler.py
trunk/Toss/WebClient/MakeDB.py
trunk/Toss/WebClient/README
trunk/Toss/WebClient/Wrapper.py
Property Changed:
----------------
trunk/Toss/WebClient/
Modified: trunk/Toss/Server/DB.ml
===================================================================
--- trunk/Toss/Server/DB.ml 2011-05-13 12:42:31 UTC (rev 1437)
+++ trunk/Toss/Server/DB.ml 2011-05-13 22:22:02 UTC (rev 1438)
@@ -2,15 +2,94 @@
http://hg.ocaml.info/release/ocaml-sqlite3/file/0e2f7d2cbd12/sqlite3.mli
*)
+let debug_level = ref 0
+
+
+let tID = ref "toss_id_05174_"
+
+let dbFILE = ref ((Unix.getenv "HOME") ^ "/.tossdb.sqlite")
+
+let tGAMES = ref ["Breakthrough"; "Checkers"; "Chess"; "Connect4";
+ "Entanglement"; "Gomoku"; "Pawn-Whopping"; "Tic-Tac-Toe"]
+
+let def_gdir = if Sys.file_exists "/usr/share/toss" then
+ "/usr/share/toss/games" else "./examples"
+
+
+(* ------- Toss DB Creation ------- *)
+
+let create_db dbfname games_path games =
+ let db = Sqlite3.db_open dbfname in
+ let exec s = ignore (Sqlite3.exec_not_null_no_headers db (fun _ -> ()) s) in
+ exec ("create table users(id string primary key," ^
+ " name string, surname string, email string, passwd string)");
+ exec ("create table cur_states(playid int primary key," ^
+ " game string, player1 string, player2 string," ^
+ " move int, toss string, loc string, info string, svg string)");
+ exec ("create table old_states(playid int," ^
+ " game string, player1 string, player2 string," ^
+ " move int, toss string, loc string, info string, svg string)");
+ exec ("create table games(game string primary key, toss string)");
+ exec ("create table lock(tid int primary key, locked bool)");
+ exec ("create table friends(id string, fid string)");
+ exec ("insert into lock(tid, locked) values ('" ^ !tID ^ "', 'false')");
+ exec ("insert into users(id, name, surname, email, passwd) values " ^
+ "('computer', 'Computer', 'tPlay', 'co...@tp...', 'xxx')");
+ let insert_game g =
+ let f = open_in (games_path ^ "/" ^ g ^ ".toss") in
+ let toss = Aux.input_file f in
+ close_in f;
+ exec ("insert into games(game, toss) values ('" ^ g ^ "','" ^ toss ^ "')");
+ print_endline ("Added " ^ g) in
+ List.iter insert_game games;
+ ignore (Sqlite3.db_close db);
+ Unix.chmod dbfname 0o777
+
+
+let reload_games dbfname games_path games =
+ let db = Sqlite3.db_open dbfname in
+ let exec s = ignore (Sqlite3.exec_not_null_no_headers db (fun _ -> ()) s) in
+ exec "delete from games";
+ print_endline "Deleted old games";
+ let reload_game g =
+ let f = open_in (games_path ^ "/" ^ g ^ ".toss") in
+ let toss = Aux.input_file f in
+ close_in f;
+ exec ("insert into games(game, toss) values ('" ^ g ^ "','" ^ toss ^ "')");
+ print_endline ("Reloading games: added " ^ g) in
+ List.iter reload_game games;
+ ignore (Sqlite3.db_close db)
+
+
+let renew_db ~games_dir =
+ let nolastslash s =
+ let l = String.length s in
+ if s.[l-1] = '/' then String.sub s 0 (l-1) else s in
+ let gdir = nolastslash games_dir in
+ if Sys.file_exists !dbFILE then (
+ print_endline ("Reloading games into Toss DB (" ^ !dbFILE ^ ")");
+ reload_games !dbFILE gdir !tGAMES;
+ print_endline "Games reloaded";
+ ) else (
+ print_endline ("Creating empty Toss DB (" ^ !dbFILE ^ ")");
+ create_db !dbFILE gdir !tGAMES;
+ print_endline "Created tossdb.sqlite";
+ )
+
+
+
+(* ---------- DB functions wrapper ------------- *)
+
exception DBError of string
let print_row r = Array.iter (fun s -> print_string (s ^ " | ")) r
let print_rows rs = List.iter (fun r -> print_row r; print_endline "") rs
-let apply_cmd dbfile select cmd =
+let rec apply_cmd ?(retried=0) dbfile select cmd =
let (rows, wh_s) = (ref [], if select = "" then "" else " where " ^ select) in
let select_s = cmd ^ wh_s in
+ if not (Sys.file_exists !dbFILE) then create_db !dbFILE def_gdir !tGAMES;
let db = Sqlite3.db_open dbfile in
let add_row r = rows := r :: !rows in
let res = Sqlite3.exec_not_null_no_headers db add_row select_s in
@@ -18,6 +97,11 @@
ignore (Sqlite3.db_close db);
match res with
| Sqlite3.Rc.OK -> (List.rev !rows, nbr_changed)
+ | Sqlite3.Rc.BUSY | Sqlite3.Rc.LOCKED when retried < 20 ->
+ if !debug_level > 0 then
+ Printf.printf "DB busy or locked, retrying %i\n%!" retried;
+ ignore (Unix.select [] [] [] 0.1);
+ apply_cmd ~retried:(retried+1) dbfile select cmd
| x -> raise (DBError (Sqlite3.Rc.to_string x))
let get_table dbfile ?(select="") tbl =
@@ -34,4 +118,4 @@
let update_table dbfile ?(select="") set_s tbl =
snd (apply_cmd dbfile select ("update " ^ tbl ^ " set " ^ set_s))
-
+
Modified: trunk/Toss/Server/DB.mli
===================================================================
--- trunk/Toss/Server/DB.mli 2011-05-13 12:42:31 UTC (rev 1437)
+++ trunk/Toss/Server/DB.mli 2011-05-13 22:22:02 UTC (rev 1438)
@@ -1,5 +1,11 @@
exception DBError of string
+val debug_level : int ref
+
+val tID : string ref
+val dbFILE : string ref
+val tGAMES : string list ref
+
val print_row : string array -> unit
val print_rows : string array list -> unit
@@ -11,3 +17,5 @@
val insert_table : string -> string -> string -> string list -> unit
val update_table : string -> ?select : string -> string -> string -> int
+
+val renew_db : games_dir : string -> unit
Modified: trunk/Toss/Server/ReqHandler.ml
===================================================================
--- trunk/Toss/Server/ReqHandler.ml 2011-05-13 12:42:31 UTC (rev 1437)
+++ trunk/Toss/Server/ReqHandler.ml 2011-05-13 22:22:02 UTC (rev 1438)
@@ -3,7 +3,10 @@
let debug_level = ref 0
let set_debug_level i = (debug_level := i;)
+let html_dir_path = ref (if Sys.file_exists "/usr/share/toss" then
+ "/usr/share/toss/html" else "WebClient/")
+
(* ---------- Basic request type and internal handler ---------- *)
type req_state =
@@ -382,7 +385,7 @@
);
let fname_in0 = String.sub cmd 5 ((String.index_from cmd 5 ' ') - 5) in
let fname_in = if fname_in0 = "" then "index.html" else fname_in0 in
- let fname = "WebClient/" ^ fname_in in
+ let fname = !html_dir_path ^ fname_in in
if !debug_level > 1 then Printf.printf "SERVING FILE: %s;\n%!" fname;
if Sys.file_exists fname then (
let f = open_in fname in
@@ -402,10 +405,7 @@
"<body><p>Not found: " ^ fname_in ^ "</p></body>\n</html>")
let handle_http_post cmd head msg ck =
- let tUID = "toss_id_05174_" in
- let dbFILE = "/var/www/WebClient/tossdb.sqlite" in
- let tGAMES = ["Breakthrough"; "Checkers"; "Chess"; "Connect4";
- "Entanglement"; "Gomoku"; "Pawn-Whopping"; "Tic-Tac-Toe"] in
+ let (tID, dbFILE) = (!DB.tID, !DB.dbFILE) in
let get_args s = Array.map (strip_all ["'"]) (split ", " s) in
let dbtable select tbl = DB.get_table dbFILE ~select tbl in
let passwd_from_db uid =
@@ -421,7 +421,7 @@
| x when x > 1 -> failwith ("get_user_name: multiple entries for " ^ uid)
| _ -> let r = List.hd res in (r.(1), r.(2), r.(3)) in
let verif_uid () =
- let (ukey, pkey)= (tUID ^ "username", tUID ^ "passphrase") in
+ let (ukey, pkey)= (tID ^ "username", tID ^ "passphrase") in
if not (List.mem_assoc ukey ck) then "" else
if not (List.mem_assoc pkey ck) then "" else
let (uid, pwd1) = (List.assoc ukey ck, List.assoc pkey ck) in
@@ -436,7 +436,7 @@
let user_plays uid =
let (name, _, _) = get_user_name_surname_mail uid in
let app_plays plays g = plays ^ "$" ^ (list_plays g uid) in
- let plays = List.fold_left app_plays "" tGAMES in
+ let plays = List.fold_left app_plays "" !DB.tGAMES in
uid ^ "$" ^ name ^ plays in
let get_free_id () = (DB.count_table dbFILE "cur_states") + 1 in
let db_cur_insert game p1 p2 pid move toss loc info svg_str =
@@ -444,12 +444,12 @@
"playid, game, player1, player2, move, toss, loc, info, svg"
[pid; game; p1; p2; move; toss; loc; info; svg_str] in
let rec get_global_lock () =
- let select = "locked='false' and tid='" ^ tUID ^ "'" in
+ let select = "locked='false' and tid='" ^ tID ^ "'" in
let i = DB.update_table dbFILE ~select "locked='true'" "lock" in
if !debug_level > 1 then print_endline ("Glob lock " ^ (string_of_int i));
if i = 1 then () else get_global_lock () in
let release_global_lock () =
- let select = "locked='true' and tid='" ^ tUID ^ "'" in
+ let select = "locked='true' and tid='" ^ tID ^ "'" in
if !debug_level > 1 then print_endline "Glob lock release";
ignore (DB.update_table dbFILE ~select "locked='false'" "lock") in
let new_play game pl1 pl2 =
@@ -520,7 +520,7 @@
| Some p when p <> pwd -> ("wrong password", [])
| Some _ ->
let exp = if chk then Some (float (3600 * 1000)) else None in
- ("OK", [(tUID^"username", uid, exp); (tUID^"passphrase", pwd, exp)]) in
+ ("OK", [(tID^"username", uid, exp); (tID^"passphrase", pwd, exp)]) in
let list_friends all uid =
if all then List.map (fun a -> a.(0)) (dbtable "" "users") else
let friends = dbtable ("id='" ^ uid ^ "'") "friends" in
@@ -545,8 +545,6 @@
upd ("surname='" ^ udata.(1) ^ "'");
upd ("email='" ^ udata.(2) ^ "'");
"OK" in
- if !debug_level > 1 then
- Printf.printf "POST\n%s\n%s\nCONTENT\n%s\nEND CONTENT\n" cmd head msg;
let (tcmd, data) = split_two "#" msg in
let resp, new_cookies = match tcmd with
| "USERNAME" ->
@@ -569,7 +567,7 @@
) else "Login: internal error", []
| "LOGOUT" ->
let c =
- [(tUID ^ "username", "a", None); (tUID ^ "passphrase", "a", None)] in
+ [(tID ^ "username", "a", None); (tID ^ "passphrase", "a", None)] in
("User logged out: " ^ (verif_uid ()), c)
| "ADDOPP" ->
add_opponent (verif_uid ()) data, []
@@ -613,15 +611,14 @@
let handle_http_msg rstate cmd head msg ck =
if String.sub cmd 0 5 = "GET /" then
- rstate, handle_http_get cmd head msg ck
+ Aux.Right (rstate, fun () -> handle_http_get cmd head msg ck)
else if String.length cmd > 13 && String.sub cmd 0 13 = "POST /Handler" then
- rstate, handle_http_post cmd head msg ck
- else try
- req_handle rstate
- (Aux.Right (GDLParser.parse_request KIFLexer.lex
- (Lexing.from_string msg)))
+ Aux.Right (rstate, fun () -> handle_http_post cmd head msg ck)
+ else try Aux.Left (req_handle rstate
+ (Aux.Right (GDLParser.parse_request KIFLexer.lex
+ (Lexing.from_string msg))))
with Parsing.Parse_error | Lexer.Parsing_error _ ->
- rstate, handle_http_post cmd head msg ck
+ Aux.Right (rstate, fun () -> handle_http_post cmd head msg ck)
@@ -664,7 +661,7 @@
let full_req_handle rstate in_ch out_ch =
try
let time_started = Unix.gettimeofday () in
- let report (new_rstate, resp) =
+ let report (new_rstate, resp) continue =
if !debug_level > 0 then (
Printf.printf "Resp-time: %F\n%!" (Unix.gettimeofday() -. time_started);
if !debug_level > 1 || String.length resp < 500 then
@@ -672,31 +669,37 @@
);
output_string out_ch (resp ^ "\n");
flush out_ch;
- new_rstate in
+ (new_rstate, continue) in
match read_in_line in_ch with
| (line, Some (Aux.Right (f, x))) when line = "COMP" ->
let res = f x in
Marshal.to_channel out_ch res [Marshal.Closures];
flush out_ch;
- rstate
+ (rstate, true)
| (line, Some (Aux.Left (cmd, head, msg, ck))) when line = "HTTP" ->
- report (handle_http_msg rstate cmd head msg ck)
+ (match handle_http_msg rstate cmd head msg ck with
+ | Aux.Left ((state, resp)) -> report (state, resp) true
+ | Aux.Right (state, future) ->
+ match Unix.fork () with
+ | 0 (* child *) -> report (state, future ()) false
+ | _ (* parent *) -> state, true
+ )
| (_, Some _) -> failwith "Internal ReqHandler Error (full_req_handle)!"
| (line, None) ->
report (req_handle rstate
(Aux.Left (ArenaParser.parse_request Lexer.lex
- (Lexing.from_string line))))
+ (Lexing.from_string line)))) true
with
| Parsing.Parse_error ->
Printf.printf "Toss Server: parse error\n%!";
output_string out_ch ("ERR could not parse\n");
flush out_ch;
- rstate
+ rstate, true
| Lexer.Parsing_error msg ->
Printf.printf "Toss Server: parse error: %s\n%!" msg;
output_string out_ch ("ERR could not parse\n");
flush out_ch;
- rstate
+ rstate, true
| End_of_file ->
output_string out_ch ("ERR processing completed -- EOF\n");
flush out_ch;
@@ -707,4 +710,4 @@
Printf.printf "Exception backtrace: %s\n%!"
(Printexc.get_backtrace ());
output_string out_ch ("ERR internal error -- see server stdout\n");
- rstate
+ rstate, true
Modified: trunk/Toss/Server/ReqHandler.mli
===================================================================
--- trunk/Toss/Server/ReqHandler.mli 2011-05-13 12:42:31 UTC (rev 1437)
+++ trunk/Toss/Server/ReqHandler.mli 2011-05-13 22:22:02 UTC (rev 1438)
@@ -6,8 +6,10 @@
val set_debug_level : int -> unit
-(** {2 Request Handlinf Functions} *)
+(** {2 Request Handling Functions} *)
+val html_dir_path : string ref
+
type req_state =
Formula.real_expr array array option (** heuristic option *)
* bool (** game modified *)
@@ -17,4 +19,8 @@
val init_state : req_state
-val full_req_handle : req_state -> in_channel -> out_channel -> req_state
+val req_handle : req_state -> (Arena.request, GDL.request) Aux.choice ->
+ req_state * string
+
+val full_req_handle : req_state -> in_channel -> out_channel ->
+ req_state * bool
Modified: trunk/Toss/Server/ReqHandlerTest.ml
===================================================================
--- trunk/Toss/Server/ReqHandlerTest.ml 2011-05-13 12:42:31 UTC (rev 1437)
+++ trunk/Toss/Server/ReqHandlerTest.ml 2011-05-13 22:22:02 UTC (rev 1438)
@@ -9,7 +9,7 @@
let out_ch = open_out "./Server/ServerTest.temp" in
let state = ref ReqHandler.init_state in
(try while true do
- state := ReqHandler.full_req_handle !state in_ch out_ch done
+ state := fst (ReqHandler.full_req_handle !state in_ch out_ch) done
with End_of_file -> ());
close_in in_ch; close_out out_ch;
let result =
@@ -33,7 +33,7 @@
let out_ch = open_out "./Server/ServerGDLTest.temp" in
let state = ref ReqHandler.init_state in
(try while true do
- state := ReqHandler.full_req_handle !state in_ch out_ch done
+ state := fst (ReqHandler.full_req_handle !state in_ch out_ch) done
with End_of_file -> ());
close_in in_ch; close_out out_ch;
let result =
Modified: trunk/Toss/Server/Server.ml
===================================================================
--- trunk/Toss/Server/Server.ml 2011-05-13 12:42:31 UTC (rev 1437)
+++ trunk/Toss/Server/Server.ml 2011-05-13 22:22:02 UTC (rev 1438)
@@ -4,6 +4,7 @@
let set_debug_level i =
debug_level := i;
+ DB.debug_level := i;
ReqHandler.set_debug_level i;
if i > 5 then Solver.set_debug_level 1 else Solver.set_debug_level 0;
if i > 0 then
@@ -25,20 +26,31 @@
let start_server f port addr_s =
(* Unix.establish_server f (Unix.ADDR_INET (get_inet_addr (addr_s), port))
- BUT we do not want a separate process for [f] as we use global state! *)
+ BUT we do not want a separate process for each [f], we use global state.*)
let sock = Unix.socket Unix.PF_INET Unix.SOCK_STREAM 0 in
Unix.setsockopt_optint sock Unix.SO_LINGER (Some 2);
Unix.setsockopt sock Unix.SO_REUSEADDR true;
Unix.bind sock (Unix.ADDR_INET (Aux.get_inet_addr (addr_s), port));
Unix.listen sock 99; (* maximally 99 pending requests *)
- while true do
+ let continue = ref true in
+ while !continue do
let (cl_sock, _) = Unix.accept sock in
- f (Unix.in_channel_of_descr cl_sock) (Unix.out_channel_of_descr cl_sock);
+ continue := f (Unix.in_channel_of_descr cl_sock)
+ (Unix.out_channel_of_descr cl_sock);
Unix.close cl_sock;
+ if !continue then (* collect zombies *)
+ try
+ ignore (Unix.waitpid [Unix.WNOHANG] (-1));
+ ignore (Unix.waitpid [Unix.WNOHANG] (-1));
+ with
+ Unix.Unix_error (e,_,_) -> if !debug_level > 1 then
+ Printf.printf "UNIX WAITPID: %s\n%!" (Unix.error_message e);
done
let req_handle in_ch out_ch =
- full_state := ReqHandler.full_req_handle !full_state in_ch out_ch
+ let (state, cont) = ReqHandler.full_req_handle !full_state in_ch out_ch in
+ full_state := state;
+ cont
let set_state_from_file fn =
let f = open_in fn in
@@ -123,13 +135,24 @@
Printf.printf "Aggregate payoffs %f, %f\n" !aggr_payoff_w !aggr_payoff_b;
) done
+let precache_game g =
+ let handle state s =
+ let (new_st, res) = ReqHandler.req_handle state
+ (Aux.Left (ArenaParser.parse_request Lexer.lex (Lexing.from_string s))) in
+ new_st in
+ print_endline ("Precaching " ^ g);
+ let toss = DB.get_table !DB.dbFILE ~select:("game='" ^ g ^ "'") "games" in
+ let init_g = handle (ReqHandler.init_state)
+ ("SET STATE #db#" ^ (List.hd toss).(1)) in
+ ignore (handle init_g "EVAL LOC MOVES 4.0 0 TIMEOUT 30 3 alpha_beta_ord")
+
(* ----------------------- START SERVER WHEN CALLED ------------------------- *)
let main () =
Aux.set_optimized_gc ();
- let (server, port) = (ref "localhost", ref 8110) in
- let (test_s, test_full) = (ref "# # / $", ref false) in
+ let (server, port, gmdir) = (ref "localhost", ref 8110, ref "") in
+ let (test_s, test_full, precache) = (ref "# # / $", ref false, ref false) in
let (experiment, e_len, e_d1, e_d2) = (ref false, ref 1, ref 2, ref 2) in
let set_parallel_port p =
let (_, s) = !GameTree.parallel_toss in
@@ -146,6 +169,12 @@
("-nm", Arg.Unit (fun () -> Heuristic.use_monotonic := false),
" monotonicity off");
("-p", Arg.Int (fun i -> (port := i)), " port number (default: 8110)");
+ ("-html", Arg.String (fun s -> ReqHandler.html_dir_path := s),
+ "set path to directory with html files for the web-based client");
+ ("-db", Arg.String (fun s -> (DB.dbFILE := s)), "use specified DB file");
+ ("-redodb", Arg.String (fun s -> gmdir := s),
+ "recreate DB files with games from given directory, e.g. 'examples'");
+ ("-tID", Arg.String (fun s -> DB.tID := s), "use specified tID");
("-heur-white-1", Arg.String (fun s -> heur_val_white1 := s),
"white (=first) player heuristic for use by the first player in tests");
("-heur-black-1", Arg.String (fun s -> heur_val_black1 := s),
@@ -159,6 +188,7 @@
("-test", Arg.String (fun s -> test_s := s), "unit tests for given path");
("-fulltest", Arg.String (fun s -> test_s := s; test_full := true),
"full unit tests for given path, might take longer");
+ ("-precache", Arg.Unit (fun () -> precache := true), "do game pre-caching");
("-experiment",
Arg.Tuple [Arg.Int (fun i -> experiment := true; e_len := i);
Arg.Int (fun d1 -> e_d1 := d1); Arg.Int (fun d2 -> e_d2 := d2)],
@@ -168,6 +198,10 @@
"Use a parallel running Toss client (port [p] server [s]) for computation")
] in
Arg.parse opts (fun _ -> ()) "Try -help for help or one of the following.";
+ if !precache then (
+ List.iter precache_game !DB.tGAMES;
+ print_endline "- precaching finished";
+ );
if !test_s <> "# # / $" then (
let (name, full) = (!test_s, !test_full) in
let len = String.length name in
@@ -184,10 +218,12 @@
let verbose = !debug_level > 0 in
set_debug_level 0;
ignore (OUnit.run_test_tt ~verbose (Tests.tests ~full ~dirs ~files ()))
- ) else if !experiment then
+ ) else if !experiment then (
run_test !e_len !e_d1 !e_d2
- else try
- start_server req_handle !port !server
+ ) else if !gmdir <> "" then (
+ DB.renew_db ~games_dir:!gmdir
+ ) else try
+ start_server req_handle !port !server
with Aux.Host_not_found ->
print_endline "The host you specified was not found."
Property changes on: trunk/Toss/WebClient
___________________________________________________________________
Modified: svn:ignore
- # We are still using .cvsignore files as we find them easier to manage
# than svn properties. Therefore if you change .cvsignore do the following.
# svn propset svn:ignore -F .cvsignore .
TossServer
tossdb.sqlite
*.ttf
*.eot
*.svg
*.woff
*~
+ # We are still using .cvsignore files as we find them easier to manage
# than svn properties. Therefore if you change .cvsignore do the following.
# svn propset svn:ignore -F .cvsignore .
*.ttf
*.eot
*.svg
*.woff
*~
Modified: trunk/Toss/WebClient/.cvsignore
===================================================================
--- trunk/Toss/WebClient/.cvsignore 2011-05-13 12:42:31 UTC (rev 1437)
+++ trunk/Toss/WebClient/.cvsignore 2011-05-13 22:22:02 UTC (rev 1438)
@@ -2,8 +2,6 @@
# than svn properties. Therefore if you change .cvsignore do the following.
# svn propset svn:ignore -F .cvsignore .
-TossServer
-tossdb.sqlite
*.ttf
*.eot
*.svg
Deleted: trunk/Toss/WebClient/Handler.py
===================================================================
--- trunk/Toss/WebClient/Handler.py 2011-05-13 12:42:31 UTC (rev 1437)
+++ trunk/Toss/WebClient/Handler.py 2011-05-13 22:22:02 UTC (rev 1438)
@@ -1,340 +0,0 @@
-import subprocess
-import socket
-import time
-from mod_python import apache, Cookie
-from pysqlite2 import dbapi2 as sqlite3
-from Wrapper import *
-import MakeDB
-
-
-def tmp_log (str):
- file = open ("/tmp/th.log", 'a')
- file.write (str)
- file.close()
-
-def get_all_from_db (db, tbl, select_s):
- res = []
- for r in db.execute("select * from " + tbl + " where " + select_s):
- res.append(r)
- return (res)
-
-def open_toss_server (port):
- args = [MakeDB.SERVER_FILE,
- "-s", "localhost", "-p", str(port)]
- server_proc = subprocess.Popen(args)
- time.sleep (0.1)
- return (port)
-
-def get_global_lock (db):
- cur = db.cursor ()
- cur.execute ("update lock set locked='true' " +
- " where locked='false' and tid='" + str(MakeDB.TUID) + "'")
- db.commit ()
- if cur.rowcount == 1:
- return
- time.sleep (0.1)
- get_global_lock (db)
-
-def release_global_lock (db):
- db.execute ("update lock set locked='false' " +
- " where locked='true' and tid='" + str(MakeDB.TUID) + "'")
- db.commit ()
-
-def get_toss_port (db):
- get_global_lock (db)
- free_ports = get_all_from_db (db, "ports", "locked='false'")
- if len(free_ports) == 0:
- fid = 0
- for f in db.execute ("select count(*) from ports"):
- fid = int(f[0])
- port = 8110+fid+1
- db.execute ("insert into ports(port, locked) values (?, ?)",
- (port, 'true'))
- release_global_lock (db)
- open_toss_server (port)
- return (port)
- (port, _) = free_ports[0]
- db.execute ("update ports set locked='true' where port=" + str(port))
- release_global_lock (db)
- return (port)
-
-def release_toss_port (db, port):
- db.execute ("update ports set locked='false' where port=" + str(port))
- db.commit ()
-
-def cp (f1, f2):
- subprocess.call(["cp", f1, f2])
-
-def list_plays (db, game, player_id):
- or_s = "(player1='" + player_id + "' or player2='" + player_id + "')"
- plays = get_all_from_db (db, "cur_states", "game='"+ game + "' and " + or_s)
- def play_name (p):
- (pid, g, p1, p2, move, _, _, _, _) = p
- return ("/plays/" + str(g) + "_" + str(p1) + "_" + str(p2) + "_" +
- str(pid) + "_" + str(move))
- return (str([play_name (p) for p in plays]))
-
-def list_friends (db, uid):
- if (uid == "**"):
- users = get_all_from_db (db, "users", "0=0")
- return ([str(u) for (u, _, _, _, _) in users])
- friends = get_all_from_db (db, "friends", "id='"+ uid + "'")
- return (str([str(f) for (_, f) in friends]))
-
-def db_cur_insert (db, game, p1, p2, pid, move, toss, loc, info, svg_str):
- db.execute ("insert into cur_states(playid, game, player1, player2, move, toss, loc, info, svg) values (?, ?, ?, ?, ?, ?, ?, ?, ?)",
- (pid, game, p1, p2, move, toss, str(loc), info, svg_str))
- db.commit ()
-
-def db_old_insert (db, game, p1, p2, pid, move, toss, loc, info, svg_str):
- db.execute ("insert into old_states(playid, game, player1, player2, move, toss, loc, info, svg) values (?, ?, ?, ?, ?, ?, ?, ?, ?)",
- (pid, game, p1, p2, move, toss, str(loc), info, svg_str))
- db.commit ()
-
-def get_game_info (client):
- dim_s = str(client.model.get_dim())
- model_s = str(client.model.get_elems_with_pos())
- rels_s = str(client.model.get_rels_simple())
- moves = client.cur_moves()
- moves_s = str(moves)
- if (len(moves) == 0): moves_s = client.get_payoffs()
- return (dim_s + "$" + model_s + "$" + rels_s + "$" + moves_s)
-
-def get_free_id (db):
- fid = 0
- for f in db.execute ("select count(*) from cur_states"):
- fid = int(f[0])
- return (fid + 1)
-
-def new_play (db, client, game, p1, p2):
- res = get_all_from_db (db, "games", "game='" + game + "'")
- (_, toss) = res[0]
- client.open_from_str (toss)
- info = get_game_info (client)
- model = client.get_model ()
- loc = client.get_cur_loc ()
- move_pl = int(client.get_loc_player (loc)) - 1
- get_global_lock (db)
- pid = get_free_id (db)
- db_cur_insert (db, game, p1, p2, pid, move_pl, model, loc, info, "")
- release_global_lock (db)
- return (str(pid) + "$" + info + "$" + str(move_pl))
-
-def game_select_s (g, p1, p2, pid, m):
- return("game='" + g + "' and player1='" + p1 + "' and player2='" + p2 +
- "' and playid=" + pid + " and move=" + m)
-
-def open_db (db, game, p1, p2, pid, move):
- select_s = game_select_s (game, p1, p2, pid, move)
- res = get_all_from_db (db, "cur_states", select_s)
- (_, _, _, _, move, _, _, info, _) = res[0]
- return (info + "$" + str(move))
-
-def db_escape (s):
- return (s.replace("'", "''"))
-
-def move_play (db, client, move_tup, g, p1, p2, pid, m):
- sel_s = game_select_s (g, p1, p2, pid, m)
- old_res = get_all_from_db (db, "cur_states", sel_s)
- (_, _, _, _, _, old_toss, old_loc, old_info, old_svg) = old_res[0]
- res = get_all_from_db (db, "games", "game='" + g + "'")
- (_, game_toss) = res[0]
- client.open_from_str (game_toss + "\n MODEL " + old_toss)
- client.set_cur_loc (old_loc)
- (move1, move2, move3) = move_tup
- new_pl = int(client.make_move (move1, move2, move3)) - 1
- new_toss = db_escape (client.get_model ())
- new_info = get_game_info (client)
- new_info_db = db_escape (new_info)
- db.execute ("update cur_states set toss='" + new_toss + "' where " + sel_s)
- db.execute ("update cur_states set info='"+ new_info_db +"' where "+ sel_s)
- db.execute ("update cur_states set loc='"+ str(move3) +"' where "+ sel_s)
- db.execute ("update cur_states set move=" + str(new_pl) +" where "+ sel_s)
- db_old_insert (db, g, p1, p2, pid, m, old_toss, old_loc, old_info, old_svg)
- return (new_info + "$" + str(new_pl))
-
-def upd_svg (db, g, p1, p2, pid, m, svg_s):
- select_s = game_select_s (g, p1, p2, pid, m)
- db.execute ("update cur_states set svg='" + svg_s + "' where " + select_s)
- db.commit ()
-
-def passwd_from_db (db, uid):
- res = get_all_from_db (db, "users", "id='" + uid + "'")
- if len(res) > 1: raise Exception ("db", "multiple entries for " + uid)
- if len(res) == 0: return (None)
- (uid, _, _, _, passwd) = res[0]
- return (str(passwd))
-
-def confirm_username (db, req):
- cookies = Cookie.get_cookies(req)
- if not (cookies.has_key(MakeDB.TUID + 'username')): return ""
- if not (cookies.has_key(MakeDB.TUID + 'passphrase')): return ""
- uid = cookies[MakeDB.TUID + 'username'].value
- pwd1 = cookies[MakeDB.TUID + 'passphrase'].value
- pwd2 = passwd_from_db (db, uid)
- if (pwd1 != pwd2): return ""
- return (uid)
-
-def login_user (db, req, uid, chk, pwd):
- db_pwd = passwd_from_db (db, uid)
- if not db_pwd: return ("no such user registered")
- if (pwd != db_pwd): return ("wrong password")
- t = time.time() + 3600000;
- if chk == "false":
- cookie1 = Cookie.Cookie(MakeDB.TUID + 'username', uid)
- cookie2 = Cookie.Cookie(MakeDB.TUID + 'passphrase', pwd)
- else:
- cookie1 = Cookie.Cookie(MakeDB.TUID + 'username', uid, expires=t)
- cookie2 = Cookie.Cookie(MakeDB.TUID + 'passphrase', pwd, expires=t)
- Cookie.add_cookie(req, cookie1)
- Cookie.add_cookie(req, cookie2)
- return ("OK")
-
-def register_user (db, ui):
- if len(ui) != 5: return (False)
- (uid, name, surname, email, pwd) = (ui[0], ui[1], ui[2], ui[3], ui[4])
- if passwd_from_db (db, uid): return (False)
- db.execute ("insert into users(id, name, surname, email, passwd) " +
- "values (?, ?, ?, ?, ?)", (uid, name, surname, email, pwd))
- db.execute ("insert into friends(id, fid) values (?, ?)", (uid, "computer"))
- db.commit ()
- return (True)
-
-def add_opponent (db, uid, oppid):
- if uid == "": return ("You must login first to add opponents.")
- if get_user_name (db, oppid) == "":
- return ("No such opponent found among tPlay users.")
- db.execute ("insert into friends(id, fid) values (?, ?)", (uid, oppid))
- db.commit ()
- return ("OK")
-
-def get_user_name (db, uname):
- res = get_all_from_db (db, "users", "id='" + uname + "'")
- if len(res) > 1: raise Exception ("db", "many entries for " + uname)
- if len(res) == 0: return ("")
- (_, name, _, _, _) = res[0]
- return (name)
-
-def get_user_surname (db, uname):
- res = get_all_from_db (db, "users", "id='" + uname + "'")
- if len(res) > 1: raise Exception ("db", "many entries for " + uname)
- if len(res) == 0: return ("")
- (_, _, surname, _, _) = res[0]
- return (surname)
-
-def get_user_mail (db, uname):
- res = get_all_from_db (db, "users", "id='" + uname + "'")
- if len(res) > 1: raise Exception ("db", "many entries for " + uname)
- if len(res) == 0: return ("")
- (_, _, _, email, _) = res[0]
- return (email)
-
-def change_user_data (db, uid, udata):
- if uid == "": return ("You must login first to change data.")
- if len(udata) != 3: return ("Internal error, data not changed.")
- uid_s = "id='" + uid + "'"
- db.execute ("update users set name='" + udata[0] + "' where " + uid_s)
- db.execute ("update users set surname='" + udata[1] + "' where " + uid_s)
- db.execute ("update users set email='" + udata[2] + "' where " + uid_s)
- db.commit ()
- return ("OK")
-
-def user_plays (db, usr):
- name = get_user_name (db, usr);
- plays = ""
- for g in MakeDB.GAMES:
- plays += "$" + list_plays (db, g, usr)
- return (usr + "$" + name + plays)
-
-def suggest_offset (offset, db, client, g, p1, p2, pid, m):
- sel_s = game_select_s (g, p1, p2, pid, m)
- res = get_all_from_db (db, "cur_states", sel_s)
- (_, _, _, _, _, toss, loc, _, _) = res[0]
- game_res = get_all_from_db (db, "games", "game='" + g + "'")
- (_, game_toss) = game_res[0]
- client.open_from_str (game_toss + "\n MODEL " + toss)
- client.set_cur_loc (loc)
- #depth = client.get_data ("depth")
- #if depth == "none": depth = 2
- adv_ratio = client.get_data ("adv_ratio")
- if adv_ratio == "none": adv_ratio = 4
- return (client.suggest (offset, adv_ratio))
-
-def suggest (db, client, time, g, p1, p2, pid, m):
- return (suggest_offset (time, db, client, g, p1, p2, pid, m))
-
-def handler(req):
- req.content_type = "text/plain"
- db = sqlite3.connect(MakeDB.DB_FILE)
- usr = confirm_username (db, req)
- msg = req.read ()
- #tmp_log(msg)
- cmd, sep, data = msg.partition('#')
- if cmd == "USERNAME":
- req.write(usr)
- return apache.OK
- if cmd == "USERPLAYS":
- if usr == "":
- req.write(usr)
- return apache.OK
- req.write (user_plays (db, usr))
- return apache.OK
- if cmd == "REGISTER":
- ui = data.split('$')
- if register_user (db, ui):
- req.write("Registration successful for " + ui[0] + ".")
- return apache.OK
- req.write("Registration failed:\n username "+ui[0]+" already in use."+
- "\nPlease choose another username and try again.")
- return apache.OK
- if cmd == "LOGIN":
- ui = data.split("$")
- res = "internal error"
- if len(ui) == 3:
- res = login_user (db, req, ui[0], ui[1], ui[2])
- if res == "OK":
- req.write("OK")
- return apache.OK
- req.write("Login failed for " + ui[0] + ": " + res)
- return apache.OK
- if cmd == "LOGOUT":
- cookie1 = Cookie.Cookie(MakeDB.TUID + 'passphrase', "a")
- cookie2 = Cookie.Cookie(MakeDB.TUID + 'username', "a")
- Cookie.add_cookie(req, cookie1)
- Cookie.add_cookie(req, cookie2)
- req.write ("User logged out: " + usr + ".")
- return apache.OK
- if cmd == "ADDOPP":
- req.write(str(add_opponent (db, usr, data)))
- return apache.OK
- if cmd == "GET_NAME":
- req.write(str(get_user_name (db, data)))
- return apache.OK
- if cmd == "GET_SURNAME":
- req.write(str(get_user_surname (db, data)))
- return apache.OK
- if cmd == "LIST_FRIENDS":
- requsr = usr
- if data == "**": requsr = "**"
- req.write(str(list_friends (db, requsr)))
- return apache.OK
- if cmd == "GET_MAIL":
- if usr == "": return ("You must login first to get email data.")
- req.write(str(get_user_mail (db, data)))
- return apache.OK
- if cmd == "CHANGEUSR":
- req.write(str(change_user_data (db, usr, data.split("$"))))
- return apache.OK
- if (cmd == "LIST_PLAYS") or (cmd == "OPEN_DB") or (cmd == "UPD_SVG"):
- res = eval (cmd.lower() + "(db, " + data + ")")
- req.write(str(res))
- return apache.OK
- if ((cmd == "NEW_PLAY") or (cmd == "MOVE_PLAY") or (cmd == "SUGGEST")):
- port = get_toss_port (db)
- c = SystemClient ("localhost", port)
- res = eval (cmd.lower() + "(db, " + data + ")")
- release_toss_port (db, port)
- req.write(str(res))
- return apache.OK
- req.write("MOD_PYTHON ERROR ; Traceback: Unknown Toss Command! \n " + cmd)
- return apache.OK
Deleted: trunk/Toss/WebClient/MakeDB.py
===================================================================
--- trunk/Toss/WebClient/MakeDB.py 2011-05-13 12:42:31 UTC (rev 1437)
+++ trunk/Toss/WebClient/MakeDB.py 2011-05-13 22:22:02 UTC (rev 1438)
@@ -1,68 +0,0 @@
-#!/usr/bin/python
-
-import os
-from pysqlite2 import dbapi2 as sqlite3
-
-TUID = "toss_id_05174_"
-
-DB_FILE = "/var/www/WebClient/tossdb.sqlite"
-
-SERVER_FILE = "/var/www/WebClient/TossServer"
-
-GAMES_PATH = "../examples"
-
-GAMES = ["Breakthrough", "Checkers", "Chess", "Connect4", "Entanglement",
- "Gomoku", "Pawn-Whopping", "Tic-Tac-Toe"]
-
-
-def create_db (db_file, games_path, games):
- conn = sqlite3.connect(db_file)
- conn.execute("create table users(id string primary key," +
- " name string, surname string, email string, passwd string)")
- conn.execute("create table cur_states(playid int primary key," +
- " game string, player1 string, player2 string," +
- " move int, toss string, loc string, info string, svg string)")
- conn.execute("create table old_states(playid int," +
- " game string, player1 string, player2 string," +
- " move int, toss string, loc string, info string, svg string)")
- conn.execute("create table games(game string primary key, toss string)")
- conn.execute("create table ports(port int primary key, locked bool)")
- conn.execute("create table lock(tid int primary key, locked bool)")
- conn.execute("create table friends(id string, fid string)")
- conn.commit ()
- conn.execute ("insert into lock(tid, locked) values (?, ?)",
- (TUID, 'false'))
- conn.execute ("insert into users(id, name, surname, email, passwd) values"+
- " (?, ?, ?, ?, ?)",
- ("computer", "Computer", "tPlay", "co...@tp...", "xxx"))
- for g in games:
- f = open(games_path + "/" + g + ".toss")
- toss = f.read()
- f.close()
- conn.execute ("insert into games(game, toss) values (?, ?)", (g, toss))
- print ("Added " + g)
- conn.commit ()
- os.chmod (db_file, 0777)
-
-
-def reload_games (db_file, games_path, games):
- conn = sqlite3.connect(db_file)
- conn.execute ("delete from games");
- print "Deleted old games";
- for g in games:
- f = open(games_path + "/" + g + ".toss")
- toss = f.read()
- f.close()
- conn.execute ("insert into games(game, toss) values (?, ?)", (g, toss))
- print ("Reloading games: added " + g)
- conn.commit ()
-
-if __name__ == "__main__":
- if os.path.exists (DB_FILE):
- print ("Reloading games into Toss DB (" + DB_FILE + ")")
- reload_games (DB_FILE, GAMES_PATH, GAMES)
- print "Games reloaded"
- else:
- print ("Creating empty Toss DB (" + DB_FILE + ")")
- create_db (DB_FILE, GAMES_PATH, GAMES)
- print "Created tossdb.sqlite"
Deleted: trunk/Toss/WebClient/README
===================================================================
--- trunk/Toss/WebClient/README 2011-05-13 12:42:31 UTC (rev 1437)
+++ trunk/Toss/WebClient/README 2011-05-13 22:22:02 UTC (rev 1438)
@@ -1,25 +0,0 @@
-This is an experimental new Toss Client, which runs in a browser.
-
-Connection with Server goes through a python wrapper and it uses sqlite, so do:
- sudo apt-get install libapache2-mod-python sqlite3 python-pysqlite2
-to run the wrapper. Make sure apache works (you may need to edit the file
-/etc/apache2/apache2.conf and uncoment ServerRoot to e.g. /etc/apache2) and
-then in the file /etc/apache2/sites-enabled/[your-site] add e.g.
- <Directory /var/www/WebClient>
- AddHandler mod_python .py
- PythonHandler Handler
- # During development you might turn debugging on
- PythonDebug On
- </Directory>
-The main handler script is called Hander.py (server side) and corresponding
-JavaScript functions are in *.js. To start client open index.html, but
-first make sure that WebClient is linked in /var/www (ln -s should suffice).
-Then run "./MakeDB.py" from WebClient and make sure Handler entry (above) is ok.
-Also copy Server from main Toss dir as TossServer to the WebClient directory.
-
-
-TODO:
- - sort plays by who's turn it is
- - option to give up game and offer a draw
- - enable google (or other) analytics
- - refresh (async?) plays in which the other player moves
Deleted: trunk/Toss/WebClient/Wrapper.py
===================================================================
--- trunk/Toss/WebClient/Wrapper.py 2011-05-13 12:42:31 UTC (rev 1437)
+++ trunk/Toss/WebClient/Wrapper.py 2011-05-13 22:22:02 UTC (rev 1438)
@@ -1,234 +0,0 @@
-#!/usr/bin/python
-
-import socket
-
-class ModelClient:
- """Ask the Toss server for approproate results.
-
- This is just a client to an XML RPC server serving Toss Model.
- """
-
- def __init__ (self, server, i, pos):
- self.s = server
- self.i = i
- self.p = pos
-
- def __str__ (self):
- return ("Nbr " + (str (self.i)) + " pos " + (str (self.i)) + ";")
-
- def id (self):
- return ("SOME MODEL", "SFX")
-
- def _pos (self):
- if self.i == ";MODEL":
- return (" MODEL ")
- if self.p == 0:
- return (" RULE " + (str (self.i)) + " LEFT ")
- return (" RULE " + (str (self.i)) + " RIGHT ")
-
- def get_elem_val (self, el_id, val):
- v = self.s.msg ("GET FUN" + (self._pos ()) + val + " " + (str (el_id)))
- return (float (v))
-
- def get_elem_pos (self, el_id):
- x = self.get_elem_val (el_id, "x")
- y = self.get_elem_val (el_id, "y")
- return (x, y)
-
- def get_elems (self):
- m = self.s.msg ("GET ALLOF ELEM" + (self._pos ()))
- if len(m) < 1:
- els = []
- else:
- els = [s.strip() for s in m.split (';')]
- return (els)
-
- def get_dim (self, elems = []):
- """Return the width, height and middle-mass x, y of [elems].
-
- If the list [elems] is empty, then it means all elements.
- """
- if elems == []: elems = self.get_elems ()
- pos = map (self.get_elem_pos , elems)
- posx, posy = [x for (x, y) in pos], [y for (x, y) in pos]
- minx, maxx, miny, maxy = min(posx), max(posx), min(posy), max(posy)
- sumx, sumy, l = sum(posx), sum(posy), len(pos)
- return (maxx, minx, maxy, miny, sumx / l, sumy / l)
-
-
- def get_rel_names_arities (self):
- mrel = self.s.msg ("GET SIGNATURE REL" + (self._pos ()))
- if len(mrel) < 1: return ([])
- pair_strs = [s.strip() for s in mrel.split (',')]
- rels_ar_lst = [p.split(':') for p in pair_strs]
- rels = [(rl[0].strip(), int (rl[1].strip())) for rl in rels_ar_lst]
- return ([r for r in set(rels)])
-
- def get_rel (self, rel_name):
- m = self.s.msg ("GET ALLOF REL" + (self._pos ()) + rel_name)
- cur = m.find('{')
- par = m.find('(')
- if cur < 0 and par < 0: return ([])
- tps = [ts.strip('{}() ') for ts in m[max(cur,par):].split(";")]
- return ([[t.strip() for t in ts.split(",")] for ts in tps])
-
- def get_rels_simple (self):
- """Return list of (rel, args, rel_id) for all rel(args) tuples."""
- sig = self.get_rel_names_arities ()
- tuples = []
- for (r, _) in sig:
- tuples = [(r, a) for a in self.get_rel (r)] + tuples
- return ("; ".join ([str(t) for t in tuples]))
-
- def get_elems_with_pos (self):
- m = self.s.msg ("GET ALLOF ELEM" + (self._pos ()))
- if len(m) < 1: return ([])
- els = [s.strip() for s in m.split (';')]
- els_p = [(e, self.get_elem_pos (e)) for e in els]
- return ([e + " ; " + str(x) + " ; " + str(y) for (e, (x, y)) in els_p])
-
-
-class SystemClient:
- """Representing the model and rewrite rules.
- """
- def __init__ (self, host, port):
- """Initialize the system given its URL and port.
- """
- self.host = host
- self.port = port
- self.model = ModelClient (self, ";MODEL", 0)
-
-
- def __str__ (self):
- return ("System")
-
- def msg (self, s):
- sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
- sock.connect ((self.host, self.port))
- sock.send (s + "\n")
- res = ""
- while 1:
- data = sock.recv(1024)
- if not data: break
- res += data
- sock.close ()
- return (res.strip ())
-
- def get_state (self):
- return (self.msg ("GET STATE"))
-
- def get_model (self):
- return (self.msg ("GET MODEL"))
-
- def set_state (self, state):
- m = self.msg ("SET STATE " + state)
- return (m)
-
- def get_cur_loc (self):
- """Get current game location from server."""
- m = self.msg ("GET LOC").split("/")
- return (int (m[0].strip()))
-
- def set_cur_loc (self, i):
- """Set current game location."""
- m = self.msg ("SET LOC " + str(i))
- return (m)
-
- def get_payoffs (self):
- """Get (evaluated) payoffs for all players in the current location."""
- m = self.msg ("GET PAYOFF")
- return (m)
-
- def get_loc_moves (self, i):
- """Get moves for the i-th position."""
- msg = self.msg("GET LOC MOVES " + (str (i)))
- if len (msg) < 1: return ([])
- moves = msg.split(';')
- def make_itvl (v):
- sep = v.split(':')
- d = sep[1].split('--')
- return (sep[0].strip(), float(d[0].strip()), float(d[1].strip()))
- def make_move (m):
- gs = m.split('->')
- lab = gs[0].split(',')
- return ((lab[0].strip(),
- [make_itvl(v.strip()) for v in lab[1:]],
- int (gs[1].strip())))
- return ([make_move(m.strip('[] ')) for m in moves])
-
- def query (self, rule_nm):
- msg = self.msg ("GET RULE " + rule_nm + " MODEL")
- if msg.find('->') < 0: return ([])
- def make_match (m_str):
- m = dict ()
- for p in m_str.split(','):
- p_str = p.split("->")
- m[p_str[0].strip()] = p_str[1].strip()
- return (m)
- return ([make_match (m.strip()) for m in msg.split(';')])
-
- def apply_rule (self, rule_nm, match, time, params):
- match_s = ", ".join([str(l) + ": " + str(r) for (l,r) in match.items()])
- param_s = ", ".join([str(p) + ": " + repr(v) for (p,v) in params])
- m = self.msg ("SET RULE "+ rule_nm + " MODEL " + match_s +
- " " + repr(time) + " " + param_s)
- shifts = dict ()
- for s in [s.strip() for s in m.split(";")]:
- seq = [e.strip() for e in s.split(",")]
- if len(seq) > 2:
- if not (seq[0] in shifts.keys()): shifts[seq[0]] = dict ()
- shifts[seq[0]][seq[1]] = [float(f) for f in seq[2:]]
- return (shifts)
-
- def open_from_str (self, s):
- state_str = ("#db#") + "$".join (s.split ("\n"))
- self.set_state (state_str)
-
- def cur_moves (self):
- cur_loc = self.get_cur_loc ()
- moves = []
- for (r, itvls, endp) in self.get_loc_moves (cur_loc):
- for m in self.query (r):
- # FIXME! currently we ignore params in html (skip itvls here)
- moves.append ((m, r, endp))
- return ("; ".join([str(m) for m in moves]))
-
- def get_loc_player (self, i):
- """Get player for the i-th location."""
- m = self.msg ("GET LOC PLAYER " + (str (i)))
- return (m)
-
- def make_move (self, m, r, endp):
- self.apply_rule (r, m, 1.0, [])
- self.set_cur_loc (endp)
- return (self.get_loc_player(endp))
-
- def get_data (self, did):
- m = self.msg ("GET DATA " + did)
- if len(m) < 3: return (m)
- if m[0:3] == "ERR": return ("none")
- return (m)
-
- def set_time (self, tstep, t):
- m = self.msg ("SET dynamics " + repr(tstep) + " " + repr(t))
- return (m)
-
- def get_time (self):
- m = self.msg ("GET dynamics")
- t = [s.strip() for s in m.split('/')]
- return ((float(t[0]), float(t[1])))
-
- def suggest (self, timeout, advr):
- loc = self.get_cur_loc ()
- (ts, t) = self.get_time ()
- m = self.msg ("EVAL LOC MOVES " + str(advr) + ".0 " + str(loc) +
- " TIMEOUT "+ str(timeout) + " 55500 alpha_beta_ord")
- self.set_time (ts, t)
- msg = [s.strip() for s in m.split(';')]
- if len(msg) < 2: return ("")
- emb = dict()
- for s in msg[1].split(','):
- es = [x.strip() for x in s.split(':')]
- emb[es[0]] = es[1]
- # we ignore params in html for now
- return ((emb, msg[0], int(msg[3])))
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|