]> 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 (message "Your opponent has passed the move to you"))))
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 (let* ((position (chess-fen-to-pos (match-string 1)))
29 (ply (chess-ply-create position)))
30 (chess-game-set-plies (chess-engine-game nil)
31 (list ply))))))
32 (cons "quit"
33 (function
34 (lambda ()
35 (message "Your opponent has quit playing"))))))
36
37 (defun chess-network-perform-move ()
38 (let* ((move (match-string 1))
39 (ply (chess-algebraic-to-ply (chess-engine-position nil) move)))
40 (unless ply
41 (error "Could not convert engine move: %s" move))
42 (let ((chess-network-now-moving t))
43 (funcall chess-engine-response-handler 'move ply))))
44
45 (defun chess-network-handler (event &rest args)
46 "Initialize the network chess engine."
47 (cond
48 ((eq event 'initialize)
49 (let ((which (read-char "Are you the c)lient or s)erver? "))
50 proc)
51 (message "Starting network client/server...")
52 (setq proc (if (eq which ?s)
53 (start-process "*chess-network*"
54 (current-buffer) "/usr/bin/nc"
55 "-l" "-p" (read-string "Port: "))
56 (open-network-stream "*chess-network*" (current-buffer)
57 (read-string "Host: ")
58 (read-string "Port: "))))
59 (if (eq which ?s)
60 (message "Now waiting for your opponent to connect...")
61 (process-send-string proc (format "name %s\n" (user-full-name)))
62 (message "You have connected; pass now or make your move."))
63 proc))
64
65 ((eq event 'shutdown)
66 (ignore-errors
67 (chess-engine-send nil "quit\n")))
68
69 ((eq event 'setup)
70 (chess-engine-send nil (format "fen %s\n"
71 (chess-pos-to-fen (car args)))))
72
73 ((eq event 'pass)
74 (chess-engine-send nil "pass\n"))
75
76 ((eq event 'move)
77 (unless chess-network-now-moving
78 (chess-engine-send nil (concat (chess-ply-to-algebraic (car args))
79 "\n"))))))
80
81 (provide 'chess-network)
82
83 ;;; chess-network.el ends here