aboutsummaryrefslogtreecommitdiff
path: root/server/api/game-manager.lisp
blob: 751aae1d27e7be6b4dd19825d93617d0d798c948 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
(in-package :remote-snake-server-api)

(defclass game-manager ()
  ((games
    :initform '())
   (next-id
    :initform 0)))

(defgeneric create-game (gm)
  (:documentation "Create a game in the Game Manager."))

(defmethod print-object :around ((gm game-manager) stream)
  (with-slots (games) gm
    (format stream "Games: ~a" games)))

(defgeneric delete-game (gm game-id)
  (:documentation "Delete a game from Game Manager."))

(defgeneric get-game (gm game-id)
  (:documentation "Fetch a game from Game Manager."))

(defmethod delete-game ((gm game-manager) game-id)
  (get-game gm game-id) ; First try to get the game (if not found, an error will be raised)
  (with-slots (games) gm
    (setf games (remove-if #'(lambda (entry) (eql game-id (getf entry :id))) games))))

(defgeneric dump (g game-id)
  (:documentation "Dump a game in the Game manager. Return a plist."))

(defmethod dump ((g game-manager) game-id)
  (with-slots (games) g
    (append (list :id game-id) (remote-snake-server-game:dump (get-game g game-id)))))


(defmethod get-game ((gm game-manager) game-id)
  (with-slots (games) gm
    (let ((game (remove-if-not #'(lambda (entry) (eql game-id (getf entry :id))) games)))
      (when (< (length game) 1) (error "Game ~a not found !" game-id))
      (getf (first game) :game))))

;;; Create a new game in gm and return its id
(defmethod create-game ((gm game-manager))
  (let ((new-game-id nil))
    (with-slots (games next-id) gm
      (push (list :id next-id :game (make-instance 'game)) games)
      (setf new-game-id next-id)
      (incf next-id))
    new-game-id))