]> code.delx.au - gnu-emacs-elpa/blob - chess-network.el
*** no comment ***
[gnu-emacs-elpa] / chess-network.el
1 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2 ;;
3 ;; Play against an opponent over the network
4 ;;
5 ;; $Revision$
6
7 (require 'chess-engine)
8 (require 'chess-fen)
9 (require 'chess-algebraic)
10
11 (defvar chess-network-now-moving nil)
12
13 (defvar chess-network-regexp-alist
14 (list (cons chess-algebraic-regexp
15 'chess-network-perform-move)
16 (cons "pass"
17 (function
18 (lambda ()
19 (funcall chess-engine-response-handler 'pass))))
20 (cons "name\\s-+\\(.+\\)"
21 (function
22 (lambda ()
23 (funcall chess-engine-response-handler 'connect
24 (match-string 1)))))
25 (cons "fen\\s-+\\(.+\\)"
26 (function
27 (lambda ()
28 (funcall chess-engine-response-handler 'setup
29 (match-string 1)))))
30 (cons "quit"
31 (function
32 (lambda ()
33 (funcall chess-engine-response-handler 'quit))))))
34
35 (defun chess-network-perform-move ()
36 (let* ((move (match-string 1))
37 (ply (chess-algebraic-to-ply (chess-engine-position nil) move)))
38 (unless ply
39 (error "Could not convert engine move: %s" move))
40 (let ((chess-network-now-moving t))
41 (funcall chess-engine-response-handler 'move ply))))
42
43 (defun chess-network-handler (event &rest args)
44 "Initialize the network chess engine."
45 (cond
46 ((eq event 'initialize)
47 (let ((which (read-char "Are you the c)lient or s)erver? "))
48 proc)
49 (message "Starting network client/server...")
50 (setq proc (if (eq which ?s)
51 (start-process "*chess-network*"
52 (current-buffer) "/usr/bin/nc"
53 "-l" "-p" (read-string "Port: "))
54 (open-network-stream "*chess-network*" (current-buffer)
55 (read-string "Host: ")
56 (read-string "Port: "))))
57 (if (eq which ?s)
58 (message "Now waiting for your opponent to connect...")
59 (process-send-string proc (format "name %s\n" (user-full-name)))
60 (message "You have connected; pass now or make your move."))
61 proc))
62
63 ((eq event 'shutdown)
64 (ignore-errors
65 (chess-engine-send nil "quit\n")))
66
67 ((eq event 'setup)
68 (chess-engine-send nil (format "fen %s\n"
69 (chess-pos-to-fen (car args)))))
70
71 ((eq event 'pass)
72 (chess-engine-send nil "pass\n"))
73
74 ((eq event 'move)
75 (unless chess-network-now-moving
76 (chess-engine-send nil (concat (chess-ply-to-algebraic (car args))
77 "\n"))))))
78
79 (provide 'chess-network)
80
81 ;;; chess-network.el ends here