]> code.delx.au - gnu-emacs-elpa/blob - chess-network.el
Added support for network play
[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 (concat "\\(Black\\|White\\):\\s-*"
15 chess-algebraic-regexp "\\s-+")
16 'chess-network-perform-move)
17 (cons "PASS"
18 (function
19 (lambda ()
20 (message "Your opponent has passed the move to you"))))
21 (cons "CONNECT\\s-+\\(.*\\)"
22 (function
23 (lambda ()
24 ;; jww (2002-04-07): Set the appropriate Black or
25 ;; White tag at this point
26 (message "Your opponent, %s, has connected"
27 (match-string 1)))))
28 (cons "SETBOARD\\s-+\\(.*\\)"
29 (function
30 (lambda ()
31 (let* ((position (chess-fen-to-pos (match-string 1)))
32 (ply (chess-ply-create position)))
33 (chess-game-set-plies (chess-engine-game nil)
34 (list ply))))))))
35
36 (defun chess-network-perform-move ()
37 (let ((position (chess-engine-position nil))
38 (move (match-string 2)) ply)
39 (when (string= (if (chess-pos-side-to-move position)
40 "White" "Black")
41 (match-string 1))
42 (setq ply (chess-algebraic-to-ply position move))
43 (unless ply
44 (error "Could not convert engine move: %s" move))
45 (let ((chess-network-now-moving t))
46 (funcall chess-engine-response-handler 'move ply)))))
47
48 (defun chess-network-handler (event &rest args)
49 "Initialize the network chess engine."
50 (cond
51 ((eq event 'initialize)
52 (let ((which (read-char "cAre you the c)lient or s)erver? "))
53 proc)
54 (message "Starting network client/server...")
55 (setq proc (if (eq which ?s)
56 (start-process "*chess-network*"
57 (current-buffer) "/usr/bin/nc"
58 "-l" "-p" (read-string "Port: "))
59 (open-network-stream "*chess-network*" (current-buffer)
60 (read-string "Host: ")
61 (read-string "Port: "))))
62 (if (eq which ?s)
63 (message "Now waiting for your opponent to connect...")
64 (process-send-string proc (format "CONNECT %s\n" (user-full-name)))
65 (message "You have connected; pass now or make your move."))
66 proc))
67
68 ((eq event 'shutdown)
69 (chess-engine-send nil "QUIT\n"))
70
71 ((eq event 'setup)
72 (chess-engine-send nil (format "SETBOARD %s\n"
73 (chess-pos-to-fen (car args)))))
74
75 ((eq event 'pass)
76 (chess-engine-send nil "PASS\n"))
77
78 ((eq event 'move)
79 (unless chess-network-now-moving
80 (chess-engine-send
81 nil (concat (if (chess-pos-side-to-move (chess-ply-pos (car args)))
82 "White:"
83 "Black:")
84 (chess-ply-to-algebraic (car args))
85 "\n"))))))
86
87 (provide 'chess-network)
88
89 ;;; chess-network.el ends here