id
int64
0
45.1k
file_name
stringlengths
4
68
file_path
stringlengths
14
193
content
stringlengths
32
9.62M
size
int64
32
9.62M
language
stringclasses
1 value
extension
stringclasses
6 values
total_lines
int64
1
136k
avg_line_length
float64
3
903k
max_line_length
int64
3
4.51M
alphanum_fraction
float64
0
1
repo_name
stringclasses
779 values
repo_stars
int64
0
882
repo_forks
int64
0
108
repo_open_issues
int64
0
90
repo_license
stringclasses
8 values
repo_extraction_date
stringclasses
146 values
sha
stringlengths
64
64
__index_level_0__
int64
0
45.1k
exdup_ids_cmlisp_stkv2
sequencelengths
1
47
20,503
https.lisp
jnc-nj_jack-tools/src/https.lisp
(in-package #:jack.tools.https) (defun jsonp (str) (and (stringp str) (not (string= str "")) (or (eq (char str 0) #\{) (eq (char str 0) #\[)))) (defun htmlp (str) (and (stringp str) (substringp "<!DOCTYPE html>" str))) (defun decode-http-body (body &key (decoder :jonathan)) (cond ((and (stringp body) (jsonp body) (eq decoder :jonathan)) (jonathan:parse (regex-replace-all "\\r" body "") :as :alist)) ((and (stringp body) (jsonp body)) (cl-json:decode-json-from-string (regex-replace-all "\\r" body ""))) ((or (stringp body) (numberp body)) (regex-replace-all "\\r" body "")) (t (decode-http-body (babel:octets-to-string (coerce body '(vector (unsigned-byte 8)))))))) (defun encode-http-body (body &key (msg t)) (cond ((or (jsonp body) (htmlp body)) body) ((and msg (stringp body)) (format nil "{\"message\": \"~d\"}" body)) ((stringp body) (write-to-string body)) ((listp body) (jonathan:to-json body :from :alist)) (t (jonathan:to-json body)))) (defun local-address () (let ((listener-thread (find-thread "handler"))) (when listener-thread (cl-ppcre:scan-to-strings "\\d+\\.\\d+\\.\\d+\\.\\d+\\:\\d+" (bt:thread-name listener-thread))))) (defun stop-port (port) (run/nil `(pipe (lsof -ti ,(format nil ":~d" port)) (xargs kill -9)) :on-error nil)) (defmacro defhandler ((app uri &key class-map multicast (decode? t) (method :get) (content-type "application/json") (cross-domain t)) &body body) `(handler-case (let ((headers (list :content-type ,content-type))) (when ,cross-domain (setf headers (append headers (list :vary "accept-encoding,origin,access-control-request-headers,access-control-request-method,accept-encoding-gzip") (list :access-control-allow-origin "*") (list :access-control-allow-headers "X-Requested-With,Authorization,Content-Type,Keep-Alive,User-Agent,Cache-Control,If-Modified-Since,DNT,X-Mx-ReqToken") (list :access-control-allow-methods "PUT,POST,GET,DELETE,OPTIONS")))) (setf (ningle:route ,app ,uri :method ,method) #'(lambda (params) (declare (ignorable params)) (setf (response-headers ningle:*response*) (append (response-headers ningle:*response*) headers)) (let ((http-content* (cond (,multicast (cast-all (request-parameters ningle:*request*) ,class-map)) (,class-map (cast (request-parameters ningle:*request*) ,class-map)) (,decode? (request-parameters ningle:*request*)) (t (request-content ningle:*request*))))) (declare (ignorable http-content*)) (encode-http-body (progn ,@body))))) (setf (ningle:route ,app ,uri :method :options) #'(lambda (params) (declare (ignorable params)) (setf (response-headers ningle:*response*) (append (response-headers ningle:*response*) headers)) "Success"))) (error () (bad-request)))) ;; HTTP CODES (defun success (payload &key (message "success") (status 200) (msg t)) (format nil "{\"rawStatus\":~d,\"successful\":~:[false~;true~],\"message\":\"~d\",\"data\":~d}" status (= status 200) message (encode-http-body payload :msg msg))) (defun bad-request (&key (message "bad request")) (success nil :message message :status 400)) (defun gone (&key (message "gone")) (success nil :message message :status 410)) (defun reset-content (&key (message "reset content")) (success nil :message message :status 205))
3,446
Common Lisp
.lisp
78
39.75641
159
0.65356
jnc-nj/jack-tools
2
0
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
5ad5fc72cf6d6572643422bd68eb6e6f48f900115bb6249e84704bebf1fb1b6e
20,503
[ -1 ]
20,504
serialize.lisp
jnc-nj_jack-tools/src/serialize.lisp
(in-package :jack.tools.serialize) (defclass serial-dict () ((n2s :initarg :n2s :initform (make-hash-table :test #'equal)) (s2n :initarg :s2n :initform (make-hash-table :test #'equal)) (ix :initarg :ix :initform -1))) (defclass serial-object () ((var-dict :initarg :var-dict :initform (make-instance 'serial-dict)) (fn-dict :initarg :fn-dict :initform (make-instance 'serial-dict)) (sexp-dict :initarg :sexp-dict :initform '()))) (defvar *serial* (make-instance 'serial-object)) (defmethod n2s-of ((serial-dict serial-dict)) (with-slots (n2s) serial-dict n2s)) (defmethod s2n-of ((serial-dict serial-dict)) (with-slots (s2n) serial-dict s2n)) (defmethod ix-of ((serial-dict serial-dict)) (with-slots (ix) serial-dict ix)) (defmethod serial-update (item (serial-dict serial-dict)) (with-slots (ix) serial-dict (cond ((listp item) (mapcar #'(lambda (itm) (serial-update itm serial-dict)) item)) ((numberp item) item) ((gethash item (n2s-of serial-dict)) item) ((gethash item (s2n-of serial-dict)) (gethash item (s2n-of serial-dict))) (t (setf (gethash (incf ix) (n2s-of serial-dict)) item (gethash item (s2n-of serial-dict)) ix))))) (defmethod serial-read (item (serial-dict serial-dict)) (if (numberp item) (gethash item (n2s-of serial-dict)) (gethash item (s2n-of serial-dict)))) (defmethod serial-output ((serial-object serial-object)) (let ((sexp-table (make-hash-table :test #'equal))) (with-slots (var-dict fn-dict sexp-dict) serial-object (dolist (item sexp-dict) (setf (gethash (serial-update (first item) var-dict) sexp-table) `(,(second item) ,@(loop for itm in (cddr item) collect (serial-update itm var-dict))))) (make-instance 'serial-object :var-dict (s2n-of var-dict) :fn-dict (s2n-of fn-dict) :sexp-dict sexp-table)))) (defun serial (objects) (setf *serial* (make-instance 'serial-object)) (with-slots (sexp-dict) *serial* (dolist (object objects) (let ((head (first object)) (form (serialize (second object))) (rest (cddr object))) (push `(,head ,form ,@rest) sexp-dict))) (serial-output *serial*))) (defun serialize (object) (with-slots (var-dict fn-dict) *serial* (cond ((listp object) (reverse (cons (serial-update (car object) fn-dict) (mapcar #'serialize (cdr object))))) (object (serial-update object var-dict)))))
2,429
Common Lisp
.lisp
58
37.551724
87
0.66822
jnc-nj/jack-tools
2
0
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
cc99ddf9d9eac3fda09c1414adda3c3e5cdf3762870c004c2e821f9336c9ae5b
20,504
[ -1 ]
20,505
lists.lisp
jnc-nj_jack-tools/src/lists.lisp
(in-package #:jack.tools.lists) (defun agethash (keyword alist &key (test #'string=) (key #'(lambda (arg) (remove #\* (string-upcase arg))))) (when (alistp alist) (cdr (assoc (funcall key (string keyword)) alist :test test :key key)))) (defun set-agethash (slot place new) (setf (cdr (assoc slot place :test #'string=)) new)) (defsetf agethash set-agethash) (defun agethash-vals (keyword alist &key (result-type 'vector) (test #'string=) (key #'string-upcase)) (map result-type #'(lambda (arg) (agethash keyword arg :test test :key key)) alist)) (defun split-list (lst) (delete-if #'null (loop for item in lst for idx from 0 collect (when (evenp idx) (cons item (nth (+ idx 1) lst)))) :key #'cdr)) (defun combinations (&rest lsts) "Get all combinations cross lists. For single list: (combinations lst lst)" (let ((lists (remove nil lsts))) (if (car lists) (mapcan #'(lambda (inner-val) (mapcar #'(lambda (outer-val) (cons outer-val inner-val)) (car lists))) (apply #'combinations (cdr lists))) (list nil)))) (defun alistp (lst) (and (listp lst) (listp (car lst)) (not (listp (caar lst))))) (defun trim-seq (seq start &optional end) (cond ((null end) (subseq seq start end)) ((> start (length seq)) seq) ((> end (length seq)) (subseq seq start)) (t (subseq seq start end)))) (defun trim-sort (key seq limit direction &key (start 0)) (trim-seq (sort seq direction :key key) start limit)) (defun union-sort (key seq-1 seq-2 direction) (sort (union seq-1 seq-2 :key key) direction :key key)) (defun all-positions (object lst &key (test 'equal)) (let (positions) (loop for item in lst for index from 0 do (when (funcall test object item) (push index positions))) positions)) (defun map-reduce (map-fn reduce-fn objects &key reduce-key) (reduce reduce-fn (mapcar map-fn objects) :key reduce-key)) (defun reduce-map (reduce-fn map-fn objects &key reduce-key) (mapcar map-fn (reduce reduce-fn objects :key reduce-key))) (defun window (window object lst &key (test 'equal)) "Get all elements within window N of OBJECT in LST." (let ((lst-length (length lst))) (reduce #'append (loop for position in (all-positions object lst :test test) for lower-bound = (- position window) for upper-bound = (+ position window 1) collect (delete object (subseq lst (if (> lower-bound 0) lower-bound 0) (when (< upper-bound lst-length) upper-bound)) :test test))))) (defun random-item (lst &key value) (when lst (cond ((listp lst) (nth (random (length lst)) lst)) ((and value (hash-table-p lst)) (gethash (random-item (hash-table-keys lst)) lst)) ((hash-table-p lst) (random-item (hash-table-keys lst)))))) (defun random-selection (lst &key (limit 5) value) (cond ((listp lst) (trim-seq (loop repeat (+ 1 (random (- (length lst) 1))) collect (random-item lst)) 0 limit)) ((hash-table-p lst) (trim-seq (if value (mapcar #'(lambda (item) (gethash item lst)) (random-selection (hash-table-keys lst))) (random-selection (hash-table-keys lst))) 0 limit)))) (defun set-equals (lst-1 lst-2 &key (test #'equal) key) (null (set-exclusive-or lst-1 lst-2 :key key :test test))) (defun dotted-pair-p (obj) (and (listp obj) (not (listp (cdr obj))))) (defun every-list-p (obj &key not) (when (listp obj) (if not (every #'(lambda (arg) (not (listp arg))) obj) (every #'listp obj)))) (defun push-all (lst place) (dolist (item lst) (push item place)))
3,867
Common Lisp
.lisp
94
34.212766
109
0.607676
jnc-nj/jack-tools
2
0
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
046bc2867ed4d91ad00d95fa6b940326053ac161cd8b836aee800974a431df0a
20,505
[ -1 ]
20,506
threads.lisp
jnc-nj_jack-tools/src/threads.lisp
(in-package #:jack.tools.threads) (defun count-threads (key) "Count threads matching key." (let ((count 0)) (dolist (thread (bt:all-threads)) (when (search key (bt:thread-name thread)) (incf count))) count)) (defun connect-client (client-name) (handler-case (join-thread client-name) (sb-sys:interactive-interrupt () (sb-ext:exit)) (error () nil))) (defun join-thread (thread-name) (bt:join-thread (find-thread thread-name))) (defun destroy-thread (&rest thread-names) (dolist (thread-name thread-names) (let ((thread (find-thread thread-name))) (when thread (bt:destroy-thread thread))))) (defun find-thread (thread-name) (find-if #'(lambda (thread) (search thread-name (bt:thread-name thread))) (bt:all-threads))) (defun all-thread-names () (mapcar #'bt:thread-name (bt:all-threads)))
854
Common Lisp
.lisp
24
31.791667
75
0.682039
jnc-nj/jack-tools
2
0
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
958c96bc98d1ce5645d8c5c30c29d77a5302687583f1ce0cb06dcec217b239fd
20,506
[ -1 ]
20,507
misc.lisp
jnc-nj_jack-tools/src/misc.lisp
(in-package #:jack.tools.misc) (defun empty-p (obj) (or (null obj) (and (stringp obj) (string= "" obj)))) (defun dekeywordfy (name) (symbol-munger:lisp->camel-case name)) (defun keywordfy (name) (values (intern (string-upcase name) "KEYWORD"))) (defun prompt-read (prompt) "Prompts and reads." (format *query-io* "~d " prompt) (force-output *query-io*) (read-line *query-io*)) (defun read-flag (flag alist &key force-string) (let ((str (agethash flag alist)) collect) (when str (dolist (substring (split-sequence:split-sequence #\space str)) (cond ((string= substring "") nil) (force-string (push substring collect)) (t (let ((new (handler-case (read-from-string substring) (error () substring)))) (if (integerp new) (push new collect) (push substring collect)))))) (car collect)))) (defmacro if-exist-return (if-part &body else-part) "Else-part is unsafe (side-effects via incf etc.)" `(let ((condition (progn ,if-part))) (if condition condition (progn ,@else-part)))) (defun string-alist-values (alist &key reverse) "Convert values in alist to string if they were not previously, or vice versa." (cond ((dotted-pair-p alist) (cons (car alist) (string-alist-values (cdr alist) :reverse reverse))) ((listp alist) (mapcar #'(lambda (arg) (string-alist-values arg :reverse reverse)) alist)) ((equal "" alist) nil) ((and reverse (stringp alist) (every #'digit-char-p alist)) (read-from-string alist)) ((numberp alist) (write-to-string alist)) (alist alist))) (defun list-package-symbols (package) (let (collect) (do-external-symbols (symbol (find-package package)) (push symbol collect)) (sort collect #'string>))) (defun largest-key (table &key outputs) (let ((val 0) out) (maphash #'(lambda (key value) (let ((int (if (listp value) (length value) value))) (cond ((> int val) (setf out (list key) val int)) ((= int val) (push key out))))) table) (if outputs (map-reduce #'(lambda (key) (gethash key table)) #'append out) out))) (defun system-version (system-designator) (let ((system (asdf:find-system system-designator nil))) (when (and system (slot-boundp system 'asdf:version)) (asdf:component-version system)))) (defun ql-installed-systems () (mapcar #'ql::name (ql::installed-systems (ql::find-dist "quicklisp")))) (defmacro return-var-name (var) `(format nil "~d" ',var))
2,452
Common Lisp
.lisp
61
36.311475
81
0.668768
jnc-nj/jack-tools
2
0
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
6217de14765ebdd2889527a58f6c5ad60bfdf800ec2c780b2a0b50351da4de6b
20,507
[ -1 ]
20,508
packages.lisp
jnc-nj_jack-tools/src/packages.lisp
(in-package :cl-user) (defpackage #:jack.tools.strings (:use #:cl) (:export #:RREPLACE #:STRINGFY #:SEXPP #:SUBSTRINGP #:REGEXFY #:CONCATSTRING #:GET-REGEX-MATCH #:STRING-TEST-P #:TRIM-WHITESPACE #:TRIM-STRING #:BRACE-BALANCE-P #:PERFECT-MATCH)) (defpackage #:jack.tools.threads (:use #:cl) (:export #:COUNT-THREADS #:CONNECT-CLIENT #:JOIN-THREAD #:DESTROY-THREAD #:FIND-THREAD #:ALL-THREAD-NAMES)) (defpackage #:jack.tools.filesystems (:use #:cl #:cl-ppcre) (:export #:CREATE-DIRECTORY #:WRITE-FILE #:ADD-LINE #:OPEN-FILE #:BATCH-DELETE #:CMD-READ-PATH #:*PROBE-FILE #:TRUENAMEP #:GET-EXTENSION)) (defpackage #:jack.tools.lists (:use #:cl #:alexandria) (:export #:AGETHASH #:AGETHASH-VALS #:SPLIT-LIST #:COMBINATIONS #:ALISTP #:TRIM-SEQ #:TRIM-SORT #:UNION-SORT #:ALL-POSITIONS #:MAP-REDUCE #:REDUCE-MAP #:WINDOWS #:RANDOM-ITEM #:RANDOM-SELECTION #:SET-EQUALS #:DOTTED-PAIR-P #:EVERY-LIST-P #:PUSH-ALL)) (defpackage #:jack.tools.misc (:use #:cl #:symbol-munger #:lack.response #:lack.request #:jack.tools.lists) (:export #:EMPTY-P #:DEKEYWORDFY #:KEYWORDFY #:PROMPT-READ #:READ-FLAG #:IF-EXIST-RETURN #:STRING-ALIST-VALUES #:LIST-PACKAGE-SYMBOLS #:LARGEST-KEY #:SYSTEM-VERSION #:QL-INSTALLED-SYSTEMS #:RETURN-VAR-NAME)) (defpackage #:jack.tools.maths (:use #:cl #:jack.tools.lists) (:export #:RANDOM-FLOAT #:AVERAGE-VECTORS #:EUCLIDEAN-DISTANCE #:DOT-PROD #:SQUARE #:SUM-OF-SQUARES #:COS-SIMILARITY #:SAFE-OP #:STRICT-OP #:*/ #:*MAX #:CLOSEST-2-BASE #:FY-SHUFFLE)) (defpackage #:jack.tools.trees (:use #:cl #:alexandria #:jack.tools.misc #:jack.tools.lists #:jack.tools.maths) (:export #:TREE-SIMILARITY #:UPSILON #:COMPARE-TREES #:ELIMINATE #:SUBBER #:UNQUOTE #:RECURSIVE-ALIST-HASH-TABLE)) (defpackage #:jack.tools.objects (:use #:cl #:alexandria #:jonathan #:jack.tools.trees #:jack.tools.lists #:jack.tools.misc) (:export #:ADDRESS-BOOK #:INTERFACES #:STACK #:COPY-INSTANCE #:TO-ADDRESS-BOOK #:CAST #:CAST-ALL #:CREATE-CLASS-MAP #:FIND-CLASS-MAP #:GET-CLASS-ID #:GET-OBJECT-ID #:GET-SLOT-NAMES #:SLOTS-EQUAL? #:OBJECTP #:OBJECT-TO-ALIST #:GENERATE-JSON-METHOD #:GET-OBJECT-SIZE #:*SLOT-VALUE)) (defpackage #:jack.tools.couchdb (:use #:cl #:alexandria #:clouchdb #:jack.tools.objects #:jack.tools.strings) (:export #:+COUCH-HOST+ #:+COUCH-PORT+ #:+COUCH-USER+ #:+COUCH-KEY+ #:WITH-COUCH #:GET-IDS #:RETURN-DOCUMENT #:RETURN-ALL-DOCUMENTS #:RETURN-VIEW #:ADD-DOC #:DELETE-DOC #:RESTART-DB)) (defpackage #:jack.tools.cli (:use #:cl #:alexandria #:jack.tools.lists #:jack.tools.misc #:jack.tools.objects) (:export #:MENU #:NAME #:PROMPT #:FORM #:LINKS #:FUNCTIONS #:RUN #:EXIT #:LOAD-MENU #:NAME-OF #:NEXT-LINK #:GET-SUB-MENU #:ADD-SUB-MENU #:ADD-RUN #:ADD-FUNCTION #:WITH-CLI)) (defpackage #:jack.tools.https (:use #:cl #:cl-ppcre #:inferior-shell #:lack.response #:lack.request #:jack.tools.objects #:jack.tools.threads #:jack.tools.strings #:jack.tools.lists) (:export #:JSONP #:HTMLP #:DECODE-HTTP-BODY #:ENCODE-HTTP-BODY #:LOCAL-ADDRESS #:DEFHANDLER #:HTTP-CONTENT* #:STOP-PORT ;; HTTP CODES #:SUCCESS #:BAD-REQUEST #:GONE #:RESET-CONTENT)) (defpackage #:jack.tools.keys (:use #:cl #:jack.tools.objects #:jack.tools.lists #:jack.tools.maths #:jack.tools.misc #:jack.tools.filesystems #:jack.tools.https) (:export #:*PRNG* #:PANTS #:BELTS #:BRIEFS #:PANTS-ON #:PANTS-OFF #:REMOVE-PANTS #:REMOVE-BELTS #:READ-ENCODED-KEY #:PARSE-PEM-FILE #:TEST-KEYS #:BYTE-ARRAY? #:CREATE-HASH #:CREATE-DIGEST #:KEY-DISTANCE #:PAD-KEY #:CREATE-CUSTOM-KEY #:TRIM-KEY #:COMPRESS-BIGNUM #:DECOMPRESS-BIGNUM #:USB8-ARRAY-TO-INTEGER #:DECOMPRESS-KEY #:RSA-ENCRYPT-MESSAGE #:RSA-DECRYPT-MESSAGE #:AES-ENCRYPT-MESSAGE #:AES-DECRYPT-MESSAGE #:SIGN-MESSAGE #:VERIFY-SIGNATURE #:CREATE-ID #:CREATE-RANDOM-PATH #:MAKE-CIPHER #:GENERATE-PRIVATE-PEM #:GENERATE-PUBLIC-PEM #:GENERATE-PEMS #:PUBKEYP)) (defpackage #:jack.tools.time (:use #:cl #:jack.tools.maths) (:export #:UNIVERSAL-TO-TIMESTRING #:SEC-NOW #:CREATE-TIME #:TIME-DIFFERENCE #:YEAR-DIFFERENCE #:TIMESTAMP> #:TIMESTAMP>= #:TIMED-INDEX #:TIMEOUT #:WAIT #:RELEASE #:SUBTRACT-TIME #:ADD-TIME)) #+nil (defpackage #:jack.tools.mysql (:use #:cl #:alexandria #:cl-mysql #:jack.tools.time #:jack.tools.misc #:jack.tools.lists) (:export #:*MYSQL-HOST* #:*MYSQL-PORT* #:*MYSQL-USER* #:*MYSQL-KEY* #:*MYSQL-MAIN-DB* #:RECONNECT #:INSERT #:UPDATE #:SELECT-BY-PARAMS #:SELECT-BY-COLUMNS #:QUERY-RESULT-TO-ALIST)) (defpackage #:jack.tools.withs (:use #:cl #:sxql #:jack.tools.lists #:jack.tools.misc #:jack.tools.keys #:jack.tools.time #:jack.tools.threads #:jack.tools.https #:jack.tools.objects) (:export #:*WITH-ENTER-LEAVE-PRINT* #:WITH-PROFILER #:WITH-EXCEPTED-API #:WITH-BT-THREAD #:WITH-INFO #:WITH-ENTER-LEAVE #:WITH-TIMER #:WITH-TIMED-LOOP #:WITH-SUPPRESSED-OUTPUT #:WITH-MUTLIPLE-SLOTS #:WITH-SECURE-API #:WITH-ENSURE-PACKAGE #:SECURE-CONTENT* #:WITH-QUERY #:HTTP-BODY* #:HTTP-CODE* #:CONNECTION-ALIVE-P #:WITH-LOG #:WITH-DB-QUERY #:WITH-DB-INSERT #:WITH-DB-UPDATE)) (defpackage #:jack.tools.matrices (:use #:cl #:jack.tools.trees) (:export #:LOAD-MATRIX)) (defpackage #:jack.tools.bootstraps (:use #:cl #:cl-bootstrap #:cl-who #:jack.tools.withs #:jack.tools.lists #:jack.tools.keys) (:export #:CREATE-BOOTSTRAP-ID #:BS-BTN #:BS-BTN-LG #:BS-BTN-SM #:BS-BTN-XS #:BS-BTN-DEFAULT #:BS-BTN-PRIMARY #:BS-BTN-SUCCESS #:BS-BTN-INFO #:BS-BTN-WARNING #:BS-BTN-DANGER #:BS-LINK-BTN #:BS-BTN-DROPDOWN #:BS-FORM-TEXT #:BS-FORM-EMBD-STATIC #:BS-FORM-EMBD-CHECKBOX #:BS-EMBD-MODAL #:BS-EMBD-TABLE)) (defpackage #:jack.tools.serialize (:use #:cl #:alexandria #:jack.tools.misc) (:export #:*SERIAL* #:SERIAL-DICT #:SERIAL-OBJECT #:N2S-OF #:S2N-OF #:IX #:SERIAL-UPDATE #:SERIAL-READ #:SERIAL-OUTPUT #:SERIAL #:SERIALIZE))
6,878
Common Lisp
.lisp
338
15.683432
37
0.609992
jnc-nj/jack-tools
2
0
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
cd27269fff230726884718c16285c8fe17feb6d25d20c0f73ef86ed69521ae46
20,508
[ -1 ]
20,509
couchdb.lisp
jnc-nj_jack-tools/src/couchdb.lisp
(in-package #:jack.tools.couchdb) (eval-when (:compile-toplevel :load-toplevel :execute) (defvar +couch-host+ nil) (defvar +couch-port+ nil) (defvar +couch-user+ nil) (defvar +couch-key+ nil)) (defmacro with-couch (name &body body) "FFS the clouchdb package doesn't have a proper with macro." `(let ((*couchdb* (make-db :name ,name :host ,+couch-host+ :port ,+couch-port+ :user ,+couch-user+ :password ,+couch-key+))) (ignore-errors ,@body))) (defmacro get-ids (database) `(with-couch ,database (remove-if #'(lambda (id) (substringp "_design" id)) (query-document '(:** :|id|) (get-all-documents))))) (defmacro return-document (id database &key class-map) `(with-couch ,database (let ((document (get-document ,id :if-missing :ignore))) (when document (if ,class-map (cast (cddr document) ,class-map) document))))) (defmacro return-all-documents (database &key class-map) `(let (collect) (dolist (item (get-ids ,database)) (push (return-document item ,database :class-map ,class-map) collect)) (reverse collect))) (defmacro return-view (view database &key class-map) `(with-couch ,database (let ((items (ad-hoc-view ,view))) (when items (if ,class-map (cast-all items ,class-map) items))))) (defmacro add-doc (database object &optional id) `(with-couch ,database (let ((document (when ,id (get-document ,id :if-missing :ignore)))) (cond ((null ,id) (post-document (object-to-alist ,object))) (document (put-document (append (list (assoc :|_id| document) (assoc :|_rev| document)) (object-to-alist ,object)))) (,id (put-document (object-to-alist ,object) :id ,id)))))) (defmacro delete-doc (database id) `(with-couch ,database (let ((doc (get-document ,id :if-missing :ignore))) (when doc (delete-document doc :if-missing :ignore))))) (defun restart-db (db) (dolist (id (get-ids db)) (delete-doc db id)))
2,031
Common Lisp
.lisp
56
31.196429
72
0.636826
jnc-nj/jack-tools
2
0
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
ac1977617cbe0ab21cbe7ea53d1d91ef35738163e941d5eb7992597cc0dc7fbc
20,509
[ -1 ]
20,510
jack-tools.asd
jnc-nj_jack-tools/jack-tools.asd
(in-package #:cl-user) (asdf:defsystem jack-tools :author "Jack Nai-Chieh Chou <[email protected]>" :maintainer "Jack Nai-Chieh Chou <[email protected]>" :serial t :components ((:file "src/packages") (:file "src/threads") (:file "src/filesystems") (:file "src/keys") (:file "src/lists") (:file "src/maths") (:file "src/misc") (:file "src/objects") (:file "src/couchdb") (:file "src/https") (:file "src/strings") (:file "src/trees") (:file "src/withs") (:file "src/time") (:file "src/cli") (:file "src/bootstraps") (:file "src/serialize") #+nil(:file "src/mysql") ) :depends-on (:alexandria :cl-ppcre :cl-json :cl-fad :ironclad :split-sequence :local-time :babel :uuid :bordeaux-threads :cl-base64 :log4cl :pem :asn1 :timer-wheel :inferior-shell :uuid :cl-bootstrap :jonathan :symbol-munger :closer-mop :usocket :ningle :lack :drakma :dexador :clouchdb ;; :cl-mysql :cl-dbi :sxql))
1,308
Common Lisp
.asd
54
15.425926
58
0.487241
jnc-nj/jack-tools
2
0
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
5283aa559fe4891952eb736609aa03d61b748fb3d64c510211e81135a9e07905
20,510
[ -1 ]
20,512
.gitmodules
jnc-nj_jack-tools/.gitmodules
[submodule "submodules/asn1"] path = submodules/asn1 url = https://github.com/jnc-nj/asn1.git [submodule "submodules/pem"] path = submodules/pem url = https://github.com/jnc-nj/pem.git [submodule "submodules/timer-wheel"] path = submodules/timer-wheel url = https://github.com/jnc-nj/timer-wheel.git
306
Common Lisp
.l
9
32.333333
48
0.757576
jnc-nj/jack-tools
2
0
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
69f5bd04808bda81ff619bd4be9a7dec794ec5d54d39fe81a55d191c01c8b180
20,512
[ -1 ]
20,542
mars-rover.lisp
stewart123579_mars-rover-challenge-lisp/mars-rover.lisp
;; Mars Rover Challenge in common lisp ;; Copyright (C) 2020 Stewart V. Wright, for Vifortech Solutions ;; ;; https://blog.vifortech.com/posts/lisp-mars-rover/ ;; ;; This program is free software: you can redistribute it and/or modify ;; it under the terms of the GNU General Public License as published by ;; the Free Software Foundation, either version 3 of the License, or ;; (at your option) any later version. ;; ;; This program is distributed in the hope that it will be useful, ;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;; GNU General Public License for more details. ;; ;; You should have received a copy of the GNU General Public License ;; along with this program. If not, see <https://www.gnu.org/licenses/>. (defparameter *x_max* nil) (defparameter *y_max* nil) (defun rotate (move orientation) ;; N ;; W E ;; S (let* ((compass '((N . (W E)) (E . (N S)) (S . (E W)) (W . (S N)))) (possible (assoc orientation compass))) (if (eq move #\L) (cadr possible) (caddr possible)))) (defun plateaup (coord max) (when (and (>= coord 0) (<= coord max)) t)) (defun move (pos orientation) (cond ((eq orientation 'N) (setf (cdr pos) (1+ (cdr pos)))) ((eq orientation 'S) (setf (cdr pos) (1- (cdr pos)))) ((eq orientation 'E) (setf (car pos) (1+ (car pos)))) ((eq orientation 'W) (setf (car pos) (1- (car pos)))) (t (error "Unknown orientation: ~a" orientation))) (unless (and (plateaup (car pos) *x_max*) (plateaup (cdr pos) *y_max*)) (error "Outside of plateau")) pos) (defun update-position (pos orientation cmds) (let ((move (car cmds))) (if move (progn (cond ((or (eq move #\L) (eq move #\R)) (setq orientation (rotate move orientation))) ((eq move #\M) (setq pos (move pos orientation))) (t (error "Unknown move"))) (update-position pos orientation (cdr cmds))) (format t "~d ~d ~s~%~%" (car pos) (cdr pos) orientation)))) (defun runme (x y orientation cmds) (let ((pos (cons x y))) (update-position pos orientation (coerce cmds 'list))))
2,226
Common Lisp
.lisp
55
36.163636
91
0.63628
stewart123579/mars-rover-challenge-lisp
2
1
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
112adae55603ef308db5b25cd7e9a22ed7b4463a8d148b0225203da9d7fdfc8b
20,542
[ -1 ]
20,543
mars-rover-v2.lisp
stewart123579_mars-rover-challenge-lisp/mars-rover-v2.lisp
(load "mars-rover.lisp") (defun set-plateau-size (plateau-shape) (setf *x_max* (car plateau-shape)) (setf *y_max* (cadr plateau-shape))) (defun loop-over-starting-positions (input) "Loop over the starting poition/orientation and commands INPUT is a list of pairs of lists (x y orientation) (commands)" (when input (let* ((start (car input)) (commands (coerce (string (car (cadr input))) 'list)) (pos (cons (car start) (cadr start))) (orientation (caddr start))) (update-position pos orientation commands)) (loop-over-starting-positions (cddr input)))) (defun read-input-file (filename) ;; Throw away blank lines (let ((setup (loop for line in (uiop:read-file-lines filename) if (not (equal line "")) collect (read-from-string (concatenate 'string "(" line ")"))))) (set-plateau-size (car setup)) (loop-over-starting-positions (cdr setup))))
952
Common Lisp
.lisp
21
39.047619
82
0.651892
stewart123579/mars-rover-challenge-lisp
2
1
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
0957324e4cbb215a00af233fa4fd1ee8e2339d24ea61211ca71fa8736d7a3b15
20,543
[ -1 ]
20,561
ui.lisp
lockie_spring-lisp-jam-2024/src/ui.lisp
(in-package #:cycle-of-evil) (ecs:defcomponent ui-window (name :|| :type keyword :index ui-window :unique t) (function #'identity :type function) (shown 0 :type bit)) (ecs:defsystem render-ui-windows (:components-ro (ui-window) :when (plusp ui-window-shown) :arguments ((:ui-context cffi:foreign-pointer))) (funcall ui-window-function ui-context)) (defun toggle-ui-window (name &key (on nil value-supplied-p)) (with-ui-window () (ui-window name) (setf shown (if value-supplied-p (if on 1 0) (logxor shown 1))))) (defmacro defwindow (name options &body body) (with-gensyms ((window-name name)) (let ((keyword (make-keyword name))) `(progn (let ((,window-name (ui-window ,keyword :missing-error-p nil))) ;; allow hot reload (when (ecs:entity-valid-p ,window-name) (ecs:delete-entity ,window-name))) (ecs:make-object `((:ui-window :name ,,keyword :function ,(ui:defwindow ,name () ,options ,@body)))))))) (defun load-ui-image (name) (al:ensure-loaded #'nk:allegro-create-image name)) (declaim (type boolean *should-quit*)) (defvar *should-quit* nil) (define-modify-macro mulf (factor) *) (defparameter *options* (make-hash-table :size 4)) (defparameter *option-names* (vector "Purity" "Sabotage" "Shaman" "Miser")) (defparameter *option-descriptions* (vector "So it was." "We burned down their forge. Their blacksmith hangs from a tree. Does anyone among them still know which side of the hammer to hold?" "Oh, what blue fairies. If I wave my hands just as quickly, I will be able to fly alongside them." "I know who they buy weapons from. If we sell them some of our weapons, we can be sure that the blades will have a defect.")) (defparameter *option-processors* (vector (lambda ()) (lambda () (dolist (character (team 0)) (setf (character-defense-multiplier character) 2.0))) (lambda () (dolist (character (team 1)) (mulf (character-attack-cooldown character) 0.5) (mulf (character-projectile-speed character) 2.0))) (lambda () (dolist (character (team 0)) (setf (character-damage-min character) (round (* 0.5 (character-damage-min character))) (character-damage-max character) (round (* 0.5 (character-damage-max character))))) (dolist (character (team 1)) (setf (character-damage-min character) (round (* 0.7 (character-damage-min character))) (character-damage-max character) (round (* 0.7 (character-damage-max character)))))))) (defparameter *selected-map* 0) (defparameter *selected-option* 0) (declaim (inline find-max-key)) (defun find-max-key (hash-table) (let ((max-key 0) (max-val most-negative-fixnum)) (declare (type fixnum max-val)) (maphash (lambda (key val) (when (> val max-val) (setf max-val val max-key key))) hash-table) max-key)) (defparameter *outcome-descriptions* (vector "You're lying, it can't be true. You're a cheater." "The last of the knights has fallen. We passed through fire across the world. No one escaped our righteous wrath. And only ashes remain everywhere... But we also depart, and the land yields no more fruit. This is an endless winter." "The nation's color vanished in the mad haste of potions. The knights will follow suit, but what do we care for them? Only the elders watch the dying embers of the plague that followed, the world erases us." "The dealers deceived us all... But at least we survived. Just like the knights. Perhaps there is a higher meaning in this? All this bloodshed wasn't worth it, but it's good that our mistake prevented the worst. We may not be able to accept the knights for a long time yet, but peace is possible, and maybe we won't destroy everything around us.")) (defun load-ui () (let ((win-background (load-ui-image "images/ui/ribbon_red_3slides.png"))) (defwindow win-message (:x 544 :y 368 :w 192 :h 64 :flags (:no-scrollbar) :styles ((:item-color :window-fixed-background :a 0) (:item-image :button-normal win-background) (:item-image :button-hover win-background) (:item-image :button-active win-background))) (toggle-ui-window :main-menu :on nil) (ui:layout-space (:format :dynamic :height 64 :widget-count 1) (ui:layout-space-push :x 0 :y 0 :w 1 :h 1) (ui:button-label "You won!" (when (= *selected-map* *current-progress*) (incf *current-progress*) (incf (gethash *selected-option* *options* 0))) (setf *selected-map* *current-progress* *selected-option* 0) (toggle-ui-window :win-message :on nil) (if (= *current-progress* (/ (length *map-descriptions*) 2)) (toggle-ui-window :outcome :on t) (toggle-ui-window :map-selector :on t)))))) (let ((loose-background (load-ui-image "images/ui/ribbon_blue_3slides.png"))) (defwindow loose-message (:x 544 :y 368 :w 192 :h 64 :flags (:no-scrollbar) :styles ((:item-color :window-fixed-background :a 0) (:item-image :button-normal loose-background) (:item-image :button-hover loose-background) (:item-image :button-active loose-background))) (toggle-ui-window :main-menu :on nil) (ui:layout-space (:format :dynamic :height 64 :widget-count 1) (ui:layout-space-push :x 0 :y 0 :w 1 :h 1) (ui:button-label "You've lost!" (setf *selected-option* 0) (toggle-ui-window :loose-message :on nil) (toggle-ui-window :map-selector :on t))))) (let+ ((backgrounds (vector (load-ui-image "images/outcomes/0.png") (load-ui-image "images/outcomes/1.png") (load-ui-image "images/outcomes/2.png") (load-ui-image "images/outcomes/3.png"))) ((&flet background () (aref backgrounds (find-max-key *options*)))) ((&flet description () (aref *outcome-descriptions* (find-max-key *options*))))) (defwindow outcome (:x 0 :y 0 :w +window-width+ :h +window-height+ :flags (:no-scrollbar) :styles ((:item-image :window-fixed-background (background)) (:color :text-color :r 0 :g 0 :b 0))) (toggle-ui-window :main-menu :on nil) (ui:layout-space (:format :dynamic :height 110 :widget-count 1) (ui:layout-space-push :x 0.15 :y 0.05 :w 0.7 :h 1.0) (ui:label-wrap (description)) (ui:layout-space-push :x 0.64 :y 0 :w 0.20 :h 0.35) (ui:button-label "Maybe there's another way" (setf *options* (make-hash-table :size 4) *selected-map* 0 *current-progress* 0) (toggle-ui-window :outcome :on nil) (toggle-ui-window :map-selector :on t))))) (let ((button-normal (load-ui-image "images/ui/button_red_3slides.png")) (button-pressed (load-ui-image "images/ui/button_red_3slides_pressed.png")) (button-disabled (load-ui-image "images/ui/button_disable_3slides.png"))) (defwindow main-menu (:x 0 :y 0 :w +window-width+ :h +window-height+ :styles ((:item-color :window-fixed-background :a 192) (:item-image :button-normal button-normal) (:item-image :button-hover button-normal) (:item-image :button-active button-pressed) (:color :button-text-normal :r 86 :g 83 :b 97) (:color :button-text-hover :r 22 :g 28 :b 46) (:color :button-text-active :r 22 :g 28 :b 46))) (ui:layout-space (:format :dynamic :height 64 :widget-count 1) (ui:layout-space-push :x 0.425 :y 4 :w 0.15 :h 0.8) (let ((has-map-p (ecs:entity-valid-p *current-map*))) (ui:styles ((:item-image :button-normal (if has-map-p button-normal button-disabled)) (:item-image :button-hover (if has-map-p button-normal button-disabled)) (:item-image :button-active (if has-map-p button-pressed button-disabled)) (:color :button-text-hover :r (if has-map-p 22 86) :g (if has-map-p 28 83) :b (if has-map-p 46 97)) (:color :button-text-active :r (if has-map-p 22 86) :g (if has-map-p 28 83) :b (if has-map-p 46 97))) (ui:button-label "Continue" (when has-map-p (toggle-ui-window :main-menu :on nil))) (ui:button-label "Abandon battle" (when has-map-p (ecs:delete-entity *current-map*) (setf *current-map* -1 *selected-option* 0) (toggle-ui-window :main-menu :on nil) (toggle-ui-window :map-selector :on t))))) (ui:button-label "RAGEQUIT!" (setf *should-quit* t))))) (let ((maps-background (load-ui-image "images/ui/map.png")) (button-normal (load-ui-image "images/ui/button_blue_3slides.png")) (button-pressed (load-ui-image "images/ui/button_blue_3slides_pressed.png"))) (defwindow map-selector (:x 0 :y 0 :w +window-width+ :h +window-height+ :flags (:no-scrollbar) :styles ((:item-image :window-fixed-background maps-background))) (ui:with-context context (ui:layout-space (:format :dynamic :height +window-height+ :widget-count 3) (ui:layout-space-push :x 0.06 :y 0.06 :w 0.5 :h 0.9) (ui:defgroup battles (:flags (:no-scrollbar :title) :styles ((:item-color :window-fixed-background :a 190) (:item-color :window-header-normal :a 190) (:item-color :window-header-hover :a 190) (:item-color :window-header-active :a 190))) (loop :for (name description) :on *map-descriptions* :by #'cddr :for i :of-type fixnum :from 0 :do (ui:layout-row-static :height 30 :item-width 780 :columns 1) (when (plusp (nk:option-label context name (if (= i *selected-map*) 1 0))) (setf *selected-map* i)) (ui:layout-row-dynamic :height 100 :columns 1) (ui:label-wrap description) (when (= i *current-progress*) (nk:widget-disable-begin context)) :finally (nk:widget-disable-end context))) (ui:layout-space-push :x 0.58 :y 0.06 :w 0.38 :h 0.7) (ui:defgroup options (:flags (:no-scrollbar) :styles ((:item-color :window-fixed-background :a 190))) (loop :for i :of-type fixnum :from 0 :below 4 :do (ui:layout-row-static :height 30 :item-width 350 :columns 1) (when (plusp (nk:option-label context (aref *option-names* i) (if (= i *selected-option*) 1 0))) (setf *selected-option* i)) (ui:layout-row-dynamic :height 100 :columns 1) (ui:label-wrap (aref *option-descriptions* i)))) (ui:layout-space-push :x 0.58 :y 0.80 :w 0.38 :h 0.158) (ui:defgroup button (:flags (:no-scrollbar) :styles ((:item-color :window-fixed-background :a 190) (:item-image :button-normal button-normal) (:item-image :button-hover button-normal) (:item-image :button-active button-pressed) (:color :button-text-normal :r 86 :g 83 :b 97) (:color :button-text-hover :r 22 :g 28 :b 46) (:color :button-text-active :r 22 :g 28 :b 46))) (ui:layout-space (:format :dynamic :height 64 :widget-count 1) (ui:layout-space-push :x 0.31 :y 0.5 :w 0.39 :h 0.75) (ui:button-label "To arms!" (let+ (((&values map width height) (load-map (format nil "/~a.tmx" *selected-map*)))) (funcall (aref *option-processors* *selected-option*)) (toggle-ui-window :map-selector :on nil) (setf *current-map* map *world-width* width *world-height* height))))))))) nil)
13,339
Common Lisp
.lisp
259
38.073359
351
0.549874
lockie/spring-lisp-jam-2024
2
0
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
1ae395cb13d535b05ac4626f3fe8f8b765f6577c55ee96d350eb9932de853575
20,561
[ -1 ]
20,562
package.lisp
lockie_spring-lisp-jam-2024/src/package.lisp
(defpackage #:cycle-of-evil (:use #:cl #:let-plus #:trivial-adjust-simple-array) (:local-nicknames (#:tiled #:cl-tiled) (#:ui #:cl-liballegro-nuklear/declarative)) (:import-from #:alexandria #:array-length #:array-index #:clamp #:define-constant #:doplist #:format-symbol #:if-let #:length= #:make-keyword #:non-negative-fixnum #:positive-fixnum #:random-elt #:shuffle #:when-let #:with-gensyms) (:import-from #:global-vars #:define-global-parameter) (:import-from #:cl-fast-behavior-trees #:complete-node #:define-behavior-tree #:define-behavior-tree/debug #:define-behavior-tree-node #:delete-behavior-tree #:make-behavior-tree) (:import-from #:cl-astar #:encode-float-coordinates #:decode-float-coordinates #:float-coordinate) (:export #:main))
942
Common Lisp
.lisp
19
38.368421
80
0.591549
lockie/spring-lisp-jam-2024
2
0
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
c4d6d5686f2fb219d5d9880de97d41946811f9f673b646feb5fb1235317e6188
20,562
[ -1 ]
20,563
damage.lisp
lockie_spring-lisp-jam-2024/src/damage.lisp
(in-package #:cycle-of-evil) (ecs:defcomponent health (points 0 :type fixnum) (max-points points :type fixnum)) (defconstant +damage-numbers-display-time+ 2.0) (ecs:defcomponent damage-number (damage 0 :type fixnum) (display-time +damage-numbers-display-time+ :type single-float)) (ecs:defsystem disspate-damage-numbers (:components-rw (damage-number) :arguments ((:dt single-float))) (decf damage-number-display-time dt) (when (minusp damage-number-display-time) (ecs:delete-entity entity))) (defvar *damage-numbers-font*) (ecs:defsystem render-damange-numbers (:components-ro (position damage-number)) (let ((dissipation (/ damage-number-display-time +damage-numbers-display-time+))) (al:draw-text *damage-numbers-font* (if (plusp damage-number-damage) (al:map-rgba-f 1.0 0.0 0.0 dissipation) (al:map-rgba-f 0.0 1.0 0.0 dissipation)) (- position-x (/ +scaled-tile-size+ 4)) (+ position-y (* (- dissipation 1.5) +scaled-tile-size+)) 0 (princ-to-string (abs damage-number-damage))))) (ecs:defsystem render-health-bars (:components-ro (position health) :with (half-tile :of-type single-float := (/ +scaled-tile-size+ 2))) (let ((health (/ (float health-points) health-max-points))) (al:draw-filled-rectangle (- (ftruncate position-x) half-tile -2) (- (ftruncate position-y) half-tile 10) (+ (ftruncate position-x) (* health half-tile) -3) (- (ftruncate position-y) half-tile 17) `(al::r ,(- 1.0 health) al::g ,health al::b 0.0 al::a 1.0)) (al:draw-rectangle (- (ftruncate position-x) half-tile -2) (- (ftruncate position-y) half-tile 10) (+ (ftruncate position-x) half-tile -2) (- (ftruncate position-y) half-tile 18) +black+ 1))) (declaim (ftype (function (ecs:entity positive-fixnum)) make-damage)) (defun make-damage (entity damage) (let ((damage-taken (round (* damage (character-defense-multiplier entity))))) (declare (type fixnum damage-taken)) (decf (health-points entity) damage-taken) (with-position () entity (ecs:make-object `((:parent :entity ,entity) (:position :x ,x :y ,y) (:damage-number :damage ,damage-taken)))))) (defun make-healing (entity healing) (with-health () entity (let* ((new-points (min max-points (+ points healing))) (healed (- new-points points))) (setf points new-points) (with-position () entity (ecs:make-object `((:parent :entity ,entity) (:position :x ,x :y ,y) (:damage-number :damage ,(- healed))))))))
2,761
Common Lisp
.lisp
61
37.393443
80
0.615985
lockie/spring-lisp-jam-2024
2
0
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
24e3047479247a0d3d101782b6c8581ebfa14b7c6dbb24f168c7214154137ca2
20,563
[ -1 ]
20,564
offensive.lisp
lockie_spring-lisp-jam-2024/src/offensive.lisp
(in-package #:cycle-of-evil) (ecs:defcomponent meat (points 0 :type fixnum) (carry -1 :type ecs:entity :index meat-carried-by)) (ecs:defsystem setup-behaviors (:components-ro (behavior) :components-no (behavior-tree-marker)) (make-behavior-tree behavior-type entity)) (define-behavior-tree-node (idle :components-rw (sprite)) () "Sets sprite animation to idle." (setf sprite-sequence-name :idle) (complete-node t)) (define-behavior-tree-node (wander-off :components-ro (position)) () (let+ (((&values sx sy) (tile-start position-x position-y)) (possible-locations nil)) (funcall (a*:make-8-directions-enumerator :node-width +scaled-tile-size+ :node-height +scaled-tile-size+ :min-x +scaled-tile-size+ :min-y +scaled-tile-size+ :max-x +window-width+ :max-y +window-height+) sx sy (lambda (next-x next-y) (let* ((next-hash (encode-float-coordinates next-x next-y)) (cost (total-map-tile-movement-cost next-hash))) (when (< cost +max-movement-cost+) (push next-hash possible-locations))))) (when possible-locations (let+ ((location (random-elt possible-locations)) ((&values target-x target-y) (decode-float-coordinates location))) (assign-movement entity :target-x target-x :target-y target-y))) (complete-node possible-locations))) (define-behavior-tree-node (defender-team :components-ro (character)) () "Succeeds if character belongs to defender team." (complete-node (zerop character-team))) (define-behavior-tree-node (full-health :components-ro (health)) () (complete-node (= health-points health-max-points))) (define-behavior-tree-node (pick-snack :components-ro (position character)) () "Picks the nearest meat as a target. Fails if there is no meat nearby." (flet ((sqr (x) (* x x))) (loop :with snacks :of-type list := (shuffle (meat-carried-by -1)) :for snack :of-type ecs:entity :in snacks :for distance := (with-position (snack-x snack-y) snack (distance* position-x position-y snack-x snack-y)) :when (<= distance (sqr character-vision-range)) :do (assign-target entity :entity snack) (return-from ecs::current-entity (complete-node t)) :finally (complete-node nil)))) (define-behavior-tree-node (test-snack :components-ro (target)) () (complete-node (and (has-meat-p target-entity) (not (ecs:entity-valid-p (meat-carry target-entity)))))) (define-behavior-tree-node (eat-snack :components-rw (target health)) () (unless (has-meat-p target-entity) ;; already eaten? (return-from ecs::current-entity (complete-node nil))) (if (has-poison-p target-entity) (with-poison () target-entity (make-poisoned entity :dps dps :duration duration)) (make-healing entity (meat-points target-entity))) (delete-meat target-entity) (delete-sprite target-entity) (delete-animation-sequence target-entity) (delete-animation-state target-entity) (delete-image target-entity) (delete-target entity) (complete-node t)) (define-behavior-tree-node (pick-nearest-enemy :components-ro (position character) :with (teams := (vector (team 0) (team 1)))) () "Picks the nearest enemy as a target. Fails if there are no enemies nearby." (flet ((sqr (x) (* x x))) (loop :with nearest-enemy :of-type ecs:entity := -1 :with nearest-enemy-distance := most-positive-single-float :for enemy :of-type ecs:entity :in (aref teams (logxor character-team 1)) :for distance := (with-position (enemy-x enemy-y) enemy (distance* position-x position-y enemy-x enemy-y)) :when (and (<= distance (sqr character-vision-range)) (< distance nearest-enemy-distance)) :do (setf nearest-enemy-distance distance nearest-enemy enemy) :finally (cond ((minusp nearest-enemy) (complete-node nil)) (t (assign-target entity :entity enemy) (complete-node t)))))) (define-behavior-tree-node (pick-random-enemy :components-ro (position character)) () "Picks an enemy at random. Fails if there are no enemies nearby." (flet ((sqr (x) (* x x))) (loop :with enemies :of-type list := (shuffle (team (logxor character-team 1))) :for enemy :of-type ecs:entity :in enemies :for distance := (with-position (enemy-x enemy-y) enemy (distance* position-x position-y enemy-x enemy-y)) :when (<= distance (sqr character-vision-range)) :do (assign-target entity :entity enemy) (return-from ecs::current-entity (complete-node t)) :finally (complete-node nil)))) (define-behavior-tree-node (calculate-path :components-ro (position target)) () "Calculates and caches the path points using A* algorithm." (with-position (target-x target-y) (target-entity entity) (let ((has-path-p (has-path-p entity))) (if (or (not has-path-p) (not (same-tile-p (path-target-x entity) (path-target-y entity) target-x target-y))) (complete-node (find-path position-x position-y target-x target-y :entity entity :has-path-p has-path-p)) (complete-node t))))) (declaim (inline approx-equal)) (defun approx-equal (a b &optional (epsilon 0.01)) (< (abs (- a b)) epsilon)) (define-behavior-tree-node (follow-path :components-rw (position)) () "Follows path previously calculated by A* algorithm." (let ((path-points (path-points entity :count 2))) (if-let (first-point (first path-points)) (with-path-point (point-x point-y) first-point (if (approx-equal 0 (distance* position-x position-y point-x point-y)) (block point-reached (setf position-x point-x position-y point-y position-tile (encode-float-coordinates position-x position-y)) (ecs:delete-entity first-point) (if-let (next-point (second path-points)) (with-path-point (next-point-x next-point-y) next-point (assign-movement entity :target-x next-point-x :target-y next-point-y) (complete-node t)) (block path-completed (complete-node nil)))) (block point-not-reached (unless (has-movement-p entity) (dolist (point (path-points entity)) (ecs:delete-entity point)))))) (complete-node nil)))) (define-behavior-tree-node (move :components-ro (movement) :components-rw (position sprite animation-state) :arguments ((:dt single-float))) ((speed 0.0 :type single-float) (animation-sequence :run :type keyword)) "Moves towards the target." (if (approx-equal 0 (distance* position-x position-y movement-target-x movement-target-y)) (block finished (setf position-x movement-target-x position-y movement-target-y position-tile (encode-float-coordinates position-x position-y)) (delete-movement entity) (complete-node t)) (let+ (((&flet sqr (x) (* x x))) (diffx (- movement-target-x position-x)) (diffy (- movement-target-y position-y)) (max-delta (sqrt (+ (sqr diffx) (sqr diffy)))) (delta (min (* dt move-speed) max-delta)) (angle (atan diffy diffx)) (dx (* delta (cos angle))) (dy (* delta (sin angle))) (newx (+ position-x dx)) (newy (+ position-y dy))) (declare (type single-float diffx diffy delta angle dx dy newx newy)) (if (obstaclep newx newy) (block struck (warn "character ~a stuck @ ~a ~a~%" entity newx newy) (setf sprite-sequence-name :idle) (delete-movement entity) (complete-node nil)) (setf position-x newx position-y newy position-tile (encode-float-coordinates position-x position-y) sprite-sequence-name move-animation-sequence animation-state-flip (if (minusp dx) 1 0)))))) (define-behavior-tree-node (test-target-near :components-ro (position target)) ((range 0.0 :type single-float)) "Succeeds if entity's target is within given range." (flet ((sqr (x) (* x x))) (with-position (target-x target-y) target-entity (complete-node (and (<= (distance* position-x position-y target-x target-y) (sqr test-target-near-range))))))) (define-behavior-tree-node (test-target-alive :components-ro (target)) () "Succeeds if entity's target is still alive." (complete-node (has-health-p target-entity))) (define-behavior-tree-node (attack :components-ro (position target character animation-sequence) :components-rw (sprite animation-state)) ((started 0 :type bit) (done 0 :type bit :documentation "Attack happened, but animation's still playing")) (with-position (target-x target-y) target-entity (if (zerop attack-started) (let* ((dx (- target-x position-x)) (dy (- target-y position-y)) (abs-dx (abs dx)) (abs-dy (abs dy)) (flip (minusp dx)) (sequence (cond ((> abs-dx abs-dy) :attack-right) ((plusp dy) :attack-down) (t :attack-up)))) (when (eq sprite-name :warrior-blue) ;; NOTE warrior has alternating attack animations (setf sequence (format-symbol :keyword "~a-~a" sequence (1+ (random 2))))) (when (eq sprite-name :barrel-red) (make-sound-effect entity :fuse position-x position-y :variations 1)) (setf sprite-sequence-name sequence animation-state-flip (if flip 1 0) attack-started 1)) (cond ((and (zerop attack-done) (= animation-state-frame (- animation-sequence-frames ;; NOTE this abomination stems from different ;; animation lengths of characters in tileset (cond ((and (plusp character-melee-attack) (plusp character-splash-attack)) 1) ((plusp character-melee-attack) 3) ((plusp character-splash-attack) 5) (t 2))))) (cond ((zerop character-melee-attack) (make-sound-effect (make-projectile-object position-x position-y target-x target-y sprite-name (randint character-damage-min character-damage-max) character-projectile-speed character-splash-attack animation-state-flip) (if (eq sprite-name :archer-blue) :shoot :throw) position-x position-y)) ((plusp character-fire-damage) (make-damage target-entity (randint character-damage-min character-damage-max)) (make-on-fire target-entity :dps character-fire-damage) (make-sound-effect entity :wood position-x position-y)) ((plusp character-splash-attack) (make-explosion-effects position-x position-y (randint character-damage-min character-damage-max))) (t (make-damage target-entity (randint character-damage-min character-damage-max)) (make-sound-effect entity :sword position-x position-y))) (setf attack-done 1)) ((and (plusp animation-state-finished) (= animation-state-frame (1- animation-sequence-frames))) (setf sprite-sequence-name :idle) (complete-node t)))))) (define-behavior-tree-node (wait :arguments ((:dt single-float))) ((time 1.0 :type single-float :documentation "Wait time in seconds.")) (if (plusp wait-time) (decf wait-time dt) (complete-node t))) (define-behavior-tree offensive ((repeat :name "root") ((fallback) ((sequence :name "snack") ((defender-team)) ((invert) ((full-health))) ((pick-snack)) ((repeat-until-fail) ((sequence :name "grab-snack") ((test-snack)) ((invert) ((test-target-near :range +scaled-tile-size+))) ((calculate-path)) ((follow-path)) ((move :speed (character-movement-speed entity))))) ((test-snack)) ((eat-snack))) ((sequence) ((pick-random-enemy)) ((invert) ((repeat-until-fail) ((sequence :name "deal-with-enemy") ((sequence) ((repeat-until-fail) ((sequence :name "pursuit") ((test-target-alive)) ((invert) ((test-target-near :range (character-attack-range entity)))) ((calculate-path)) ((follow-path)) ((move :speed (character-movement-speed entity))))) ((test-target-alive)) ((test-target-near :range (character-attack-range entity)))) ((repeat-until-fail) ((sequence :name "attacks") ((test-target-alive)) ((test-target-near :range (character-attack-range entity))) ((attack)) ((wait :time (character-attack-cooldown entity))))) ((invert) ((test-target-near :range (character-attack-range entity)))))))) ((invert) ((idle))) ((invert) ((sequence :name "wander-off") ((random :probability 0.01)) ((wander-off)) ((move :speed (character-movement-speed entity))) ((idle)))))))
15,515
Common Lisp
.lisp
334
32.634731
80
0.536381
lockie/spring-lisp-jam-2024
2
0
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
d72eb329ca0dbbdffa24d3f400278bfd1c6a4d28253a3795b28f89e2e1555adb
20,564
[ -1 ]
20,565
poison.lisp
lockie_spring-lisp-jam-2024/src/poison.lisp
(in-package #:cycle-of-evil) (ecs:defcomponent poison (duration 0.0 :type single-float) (dps 0 :type fixnum :documentation "Damage per second")) (ecs:defsystem intoxicate (:components-rw (poison animation-state character) :arguments ((:dt single-float))) (let ((previous-duration poison-duration)) (decf poison-duration dt) (unless (plusp poison-duration) (setf animation-state-tint 0) (return-from ecs::current-entity (delete-poison entity))) (unless (= (the fixnum (truncate previous-duration)) (the fixnum (truncate poison-duration))) (when (has-health-p entity) (make-damage entity poison-dps))))) (defun make-poisoned (entity &key (dps 1) (duration 10.0)) (assign-poison entity :duration duration :dps dps) (setf (animation-state-tint entity) #x00ff00ff) entity)
842
Common Lisp
.lisp
20
37.4
63
0.705379
lockie/spring-lisp-jam-2024
2
0
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
c3e379511171255437f89945f79442283c7ae3728e79fb3f7d7c1fe55d971e97
20,565
[ -1 ]
20,566
sound.lisp
lockie_spring-lisp-jam-2024/src/sound.lisp
(in-package #:cycle-of-evil) (ecs:defcomponent sound-prefab (name :|| :type keyword :documentation "Sound name" :index sound-prefab :unique t) (sample (cffi:null-pointer) :type cffi:foreign-pointer)) (ecs:defcomponent sound (sample-instance (cffi:null-pointer) :type cffi:foreign-pointer) (repeat 0 :type bit) (time 0.0 :type single-float)) (ecs:defsystem expire-sound (:components-rw (sound) :arguments ((:dt single-float))) (decf sound-time dt) (when (and (not (plusp sound-time)) (zerop sound-repeat)) (ecs:delete-entity entity))) (ecs:hook-up ecs:*entity-deleting-hook* (lambda (entity) (when (has-sound-p entity) (let ((sample-instance (sound-sample-instance entity))) (al:stop-sample-instance sample-instance) (al:destroy-sample-instance sample-instance)) (setf (sound-sample-instance entity) (cffi:null-pointer))))) (defconstant +distance-factor+ ;; NOTE this math is very experimental math (/ 4.0 (sqrt (+ (* +window-width+ +window-width+) (* +window-height+ +window-height+))))) (defconstant +pan-factor+ (/ 2.0 +window-width+)) (declaim (inline position-sound) (ftype (function (cffi:foreign-pointer single-float single-float)) position-sound)) (defun position-sound (sample-instance x y) (let ((gain (/ 1.0 (exp (* +distance-factor+ (distance x y (/ +window-width+ 2.0) (/ +window-height+ 2.0)))))) (pan (clamp (* +pan-factor+ (- x (/ +window-width+ 2.0))) -1.0 1.0))) (al:set-sample-instance-gain sample-instance gain) (al:set-sample-instance-pan sample-instance pan))) (ecs:defsystem position-sound (:components-ro (sound parent) :components-rw (position) :when (ecs:entity-valid-p parent-entity)) (with-position (parent-x parent-y) parent-entity (when (or (/= position-x parent-x) (/= position-y parent-y)) (position-sound sound-sample-instance (setf position-x parent-x) (setf position-y parent-y)) (setf position-tile (encode-float-coordinates position-x position-y))))) (defun make-sound-effect (parent name x y &key repeat (variations 4)) (let* ((name (format-symbol :keyword "~a~a" name (random variations))) (prefab (sound-prefab name)) (sample (sound-prefab-sample prefab)) (sample-instance (al:create-sample-instance sample)) (time (al:get-sample-instance-time sample-instance))) (al:attach-sample-instance-to-mixer sample-instance (al:get-default-mixer)) (position-sound sample-instance x y) (al:set-sample-instance-playmode sample-instance (if repeat :loop :once)) (al:play-sample-instance sample-instance) (ecs:make-object `((:parent :entity ,parent) (:position :x ,x :y ,y) (:sound :sample-instance ,sample-instance :repeat ,(if repeat 1 0) :time ,time))))) (defun load-sound-file (full-filename) (let ((sample (al:ensure-loaded #'al:load-sample full-filename)) (name (make-keyword (string-upcase (kebabize (pathname-name full-filename)))))) (ecs:make-object `((:sound-prefab :name ,name :sample ,sample))))) (cffi:defcallback process-sound-file :int ((file (:pointer (:struct al::fs-entry))) (data :pointer)) (declare (ignore data)) (if (zerop (logand (al::get-fs-entry-mode file) (cffi:foreign-bitfield-value 'al::file-mode '(:isdir)))) (progn (load-sound-file (al::get-fs-entry-name file)) (cffi:foreign-enum-value 'al::for-each-fs-entry-result :ok)) (cffi:foreign-enum-value 'al::for-each-fs-entry-result :skip))) (defun load-sounds () (let ((sounds-dir (al:create-fs-entry "sounds"))) (unwind-protect (= (cffi:foreign-enum-value 'al::for-each-fs-entry-result :ok) (al::for-each-fs-entry sounds-dir (cffi:callback process-sound-file) (cffi:null-pointer))) (al:destroy-fs-entry sounds-dir))))
4,269
Common Lisp
.lisp
89
38.573034
79
0.609791
lockie/spring-lisp-jam-2024
2
0
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
5f7ac287da9b7b5fab05515bb5df0ffe5cc41f0feb593e94cf2b6c0e963e430b
20,566
[ -1 ]
20,567
projectile.lisp
lockie_spring-lisp-jam-2024/src/projectile.lisp
(in-package #:cycle-of-evil) (ecs:defcomponent projectile (target-x 0.0 :type float-coordinate) (target-y 0.0 :type float-coordinate) (angle 0.0 :type single-float) (speed 0.0 :type single-float) (damage 0 :type fixnum) (splash 0 :type bit :documentation "Whether projectile deals splash damage. NOTE: assuming splash damage = explosion")) (ecs:defcomponent stuck-arrow "Then I took an arrow in the knee..." (adventurer -1 :type ecs:entity :index stuck-arrows)) (ecs:defcomponent explosion) (ecs:defsystem move-projectiles (:components-ro (projectile animation-state) :components-rw (position) :arguments ((:dt single-float))) (let+ (((&flet sqr (x) (* x x))) (diffx (- projectile-target-x position-x)) (diffy (- projectile-target-y position-y)) (max-delta (sqrt (+ (sqr diffx) (sqr diffy)))) (delta (min (* dt projectile-speed) max-delta)) (dx (* delta (cos projectile-angle))) (dy (* delta (sin projectile-angle))) (newx (+ position-x dx)) (newy (+ position-y dy))) (setf position-x newx position-y newy position-tile (encode-float-coordinates newx newy)))) (ecs:defsystem impact-projectiles (:components-ro (projectile position sprite animation-state)) (when (< (distance* projectile-target-x projectile-target-y position-x position-y) (* +scaled-tile-size+ +scaled-tile-size+)) (if (zerop projectile-splash) (with-tiles (encode-float-coordinates projectile-target-x projectile-target-y) object (when (has-health-p object) (make-damage object projectile-damage) (ecs:make-object `((:parent :entity ,object) (:position :x ,projectile-target-x :y ,projectile-target-y) (:sprite :name ,sprite-name :sequence-name :projectile-stuck) (:animation-state :rotation ,animation-state-rotation) (:stuck-arrow :adventurer ,object))) (make-sound-effect object :arrow position-x position-y) (loop-finish))) (make-explosion-effects projectile-target-x projectile-target-y projectile-damage)) (ecs:delete-entity entity))) (declaim (ftype (function (float-coordinate float-coordinate positive-fixnum) (values ecs:entity &optional)) make-explosion-effects)) (defun make-explosion-effects (x y damage) (with-tiles (encode-float-coordinates x y) object (when (has-health-p object) (make-damage object damage)) (when (has-fire-p object) (setf (fire-duration object) 0.0))) (make-sound-effect *current-map* :explosion x y :variations 1) (ecs:make-object `((:parent :entity ,*current-map*) (:position :x ,x :y ,y) (:sprite :name :explosions :sequence-name :explosion) (:explosion)))) (ecs:defsystem move-stuck-arrows (:components-ro (stuck-arrow) :components-rw (position)) (with-position (adventurer-x adventurer-y) stuck-arrow-adventurer (setf position-x adventurer-x position-y adventurer-y position-tile (encode-float-coordinates position-x position-y)))) (ecs:defsystem stop-explosions (:components-ro (explosion animation-sequence animation-state)) (when (= animation-state-frame animation-sequence-frames) (ecs:delete-entity entity))) (declaim (ftype (function (float-coordinate float-coordinate float-coordinate float-coordinate keyword positive-fixnum single-float bit bit) (values ecs:entity &optional)) make-projectile-object)) (defun make-projectile-object (x y target-x target-y sprite damage speed splash flip) (let* ((angle (atan (- target-y y) (- target-x x))) (splashp (plusp splash)) (object (ecs:make-object `((:parent :entity ,*current-map*) (:position :x ,x :y ,y) (:sprite :name ,sprite :sequence-name :projectile) (:projectile :target-x ,target-x :target-y ,target-y :angle ,angle :speed ,speed :damage ,damage :splash ,splash) (:animation-state :rotation ,(if splashp 0.0 angle) :flip ,(if splashp (logxor flip 1) 0)))))) (when splashp (make-sound-effect object :fuse x y :repeat t :variations 1)) object))
5,027
Common Lisp
.lisp
113
31.849558
77
0.56301
lockie/spring-lisp-jam-2024
2
0
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
2371ebfc7cec4f806ead700a8f458dfc02d6828d2f16339726d70d0bcfbdcccc
20,567
[ -1 ]
20,568
map.lisp
lockie_spring-lisp-jam-2024/src/map.lisp
(in-package #:cycle-of-evil) (ecs:defcomponent map-tile (movement-cost 0.0 :type single-float) (grass 0 :type bit :index grass) (castle 0 :type bit :index castle)) (ecs:defsystem render-map-tiles (:components-ro (position size image map-tile) :initially (al:hold-bitmap-drawing t) :finally (al:hold-bitmap-drawing nil)) (al:draw-scaled-bitmap image-bitmap 0.0 0.0 size-width size-height position-x position-y (* +scale-factor+ size-width) (* +scale-factor+ size-height) 0) ;; (al:draw-rectangle position-x position-y ;; (+ position-x (* +scale-factor+ size-width)) ;; (+ position-y (* +scale-factor+ size-height)) ;; (al:map-rgb 0 0 0) 1) ) (declaim (type ecs:entity *current-map*)) (defparameter *current-map* -1) (declaim (ftype (function (fixnum) single-float) total-map-tile-movement-cost)) (defun total-map-tile-movement-cost (tile-hash) (let ((sum 0.0)) (declare (type single-float sum)) (with-tiles tile-hash tile (when (has-map-tile-p tile) (incf sum (map-tile-movement-cost tile)))) (max sum 0.0))) (defconstant +max-movement-cost+ 1.0) (declaim (ftype (function (float-coordinate float-coordinate) boolean) obstaclep)) (defun obstaclep (x y) "Takes tile position and returns T if there are obstacles in there." (>= (total-map-tile-movement-cost (encode-float-coordinates x y)) +max-movement-cost+)) (defun read-file-into-string (pathname &key (buffer-size 4096)) (with-open-stream (stream (al:make-character-stream pathname)) (alexandria:read-stream-content-into-string stream :buffer-size buffer-size))) (defun load-bitmap (filename) (al:ensure-loaded #'al:load-bitmap (namestring filename))) (declaim (inline maybe-keyword)) (defun maybe-keyword (value) (if (and (stringp value) (> (length value) 1) (string= ":" value :end2 1)) (make-keyword (string-upcase (subseq value 1))) value)) (declaim (inline maybe-boolean)) (defun maybe-boolean (value) "We use bit instead of boolean in components to save space." (cond ((eq value t) 1) ((eq value nil) 0) (t value))) (defun properties->spec (properties) (loop :for component :being :the :hash-key :using (hash-value slots) :of properties :when (typep slots 'hash-table) :collect (list* (make-keyword (string-upcase component)) (loop :for name :being :the :hash-key :using (hash-value value) :of slots :nconcing (list (make-keyword (string-upcase name)) (maybe-keyword (maybe-boolean value))))))) (defun tile->spec (tile tile-width tile-height bitmap map-entity) (copy-list `((:parent :entity ,map-entity) ;; TODO : delete sub-bitmaps when no longer needed (:image :bitmap ,(al:create-sub-bitmap bitmap (tiled:tile-pixel-x tile) (tiled:tile-pixel-y tile) tile-width tile-height)) (:size :width ,(float tile-width) :height ,(float tile-height))))) (defun tiled-color->allegro (color) (when color `(al::r ,(/ (tiled:tiled-color-r color) 255.0) al::g ,(/ (tiled:tiled-color-g color) 255.0) al::b ,(/ (tiled:tiled-color-b color) 255.0) al::a ,(/ (tiled:tiled-color-a color) 255.0)))) (defun ensure-relative (pathname) (let ((dirs (rest (pathname-directory pathname)))) (make-pathname :directory (when dirs (list* :relative dirs)) :defaults pathname))) (defun load-map (filename) (let* ((map (tiled:load-map filename (lambda (path &rest rest) (apply #'read-file-into-string (ensure-relative path) rest)))) (tile-width (tiled:map-tile-width map)) (tile-height (tiled:map-tile-height map)) (tilemap (make-hash-table)) (map-entity (ecs:make-object `((:map :tint (tiled-color->allegro (gethash "tint" (tiled:properties map)))))))) (assert (and (= tile-width +tile-size+) (= tile-height +tile-size+))) (dolist (tileset (tiled:map-tilesets map)) (let ((bitmap (load-bitmap (ensure-relative (tiled:image-source (tiled:tileset-image tileset)))))) (dolist (tile (tiled:tileset-tiles tileset)) (let* ((external-tile-spec (when (typep tile 'tiled:tiled-tileset-tile) (properties->spec (tiled:properties tile)))) (internal-tile-spec (tile->spec tile tile-width tile-height bitmap map-entity)) (tile-spec (nconc internal-tile-spec external-tile-spec))) (setf (gethash tile tilemap) (adjoin '(:map-tile) tile-spec :test #'eq :key #'first)))))) (dolist (layer (tiled:map-layers map)) (cond ((typep layer 'tiled:tile-layer) (dolist (cell (tiled:layer-cells layer)) (ecs:make-object (append (gethash (tiled:cell-tile cell) tilemap) `((:position :x ,(* +scale-factor+ (tiled:cell-x cell)) :y ,(* +scale-factor+ (tiled:cell-y cell)))))))) ((typep layer 'tiled:object-layer) (dolist (object (tiled:object-group-objects layer)) (ecs:make-object (nconc (properties->spec (tiled:properties object)) `((:parent :entity ,map-entity) (:position :x ,(* +scale-factor+ (+ (tiled:object-x object) (* 0.5 (tiled:object-width object)))) :y ,(* +scale-factor+ (- (tiled:object-y object) (* 0.5 (tiled:object-height object)))))))))))) (values map-entity (tiled:map-width map) (tiled:map-height map))))
6,380
Common Lisp
.lisp
139
34.100719
79
0.550522
lockie/spring-lisp-jam-2024
2
0
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
caeb2ce28042eaa3586007777295b7105da5c6ac7086fd97b091522a2996293b
20,568
[ -1 ]
20,569
character.lisp
lockie_spring-lisp-jam-2024/src/character.lisp
(in-package #:cycle-of-evil) (ecs:defcomponent target (entity -1 :type ecs:entity)) (ecs:defcomponent movement (target-x 0.0 :type single-float) (target-y 0.0 :type single-float)) (ecs:defcomponent path "A path previously calculated by A* algorithm." (target-x 0.0 :type single-float) (target-y 0.0 :type single-float)) (ecs:defcomponent path-point (x 0.0 :type float-coordinate) (y 0.0 :type float-coordinate) (traveller -1 :type ecs:entity :index path-points)) (ecs:defsystem mortify-characters (:components-ro (health character position) :components-rw (sprite animation-state) :when (not (plusp health-points))) "This parrot is no more. It has ceased to be." (when (eq sprite-name :barrel-red) ;; delete fuse sound effect (dolist (child (children entity)) (when (has-sound-p child) (ecs:delete-entity child)))) (make-sound-effect entity (case character-team (0 :death) (1 :monster-death)) position-x position-y) (setf sprite-name :dead sprite-sequence-name :dead animation-state-tint 0) (delete-health entity) (delete-character entity) (when (has-behavior-p entity) (delete-behavior-tree (behavior-type entity) entity) (delete-behavior entity)) (dolist (arrow (stuck-arrows entity)) (ecs:delete-entity arrow))) (defconstant +sqrt2+ (sqrt 2)) (a*:define-path-finder find-path (entity has-path-p) (:world-size (the array-length (* *world-width* *world-height*)) :indexer (a*:make-row-major-indexer *world-width* :node-width +scaled-tile-size+ :node-height +scaled-tile-size+) :goal-reached-p same-tile-p :neighbour-enumerator (lambda (x y f) (let+ (((&values cx cy) (tile-center x y))) (funcall (a*:make-8-directions-enumerator :node-width +scaled-tile-size+ :node-height +scaled-tile-size+ :max-x +window-width+ :max-y +window-height+) cx cy f))) :exact-cost (lambda (x1 y1 x2 y2) (let+ (((&flet cost (x y) (total-map-tile-movement-cost (multiple-value-call #'encode-float-coordinates (tile-start x y))))) (diagonal-cost (if (and (/= x1 x2) (/= y1 y2)) (+ (cost x1 y2) (cost x2 y1)) 0.0))) (+ (cost x2 y2) diagonal-cost))) :heuristic-cost (a*:make-octile-distance-heuristic 9.765625e-6) :max-movement-cost +max-movement-cost+ :path-initiator (lambda (length) (declare (ignore length)) (when has-path-p (dolist (point (path-points entity)) (ecs:delete-entity point))) (assign-path entity :target-x start-x :target-y start-y) (ecs:make-object `((:path-point :x ,start-x :y ,start-y :traveller ,entity) (:parent :entity ,entity)))) :path-processor (lambda (x y) (with-position (current-x current-y) entity (unless (and (= current-x x) (= current-y y)) (ecs:make-object `((:path-point :x ,x :y ,y :traveller ,entity) (:parent :entity ,entity))))))) "Find path for given entity.")
3,307
Common Lisp
.lisp
86
30.151163
73
0.596639
lockie/spring-lisp-jam-2024
2
0
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
bfc9cd370bbb41f572a68cf8a6181d094a83accfb68c56c234ce9a9d423e092f
20,569
[ -1 ]
20,570
main.lisp
lockie_spring-lisp-jam-2024/src/main.lisp
(in-package #:cycle-of-evil) (defvar *resources-path* (asdf:system-relative-pathname :cycle-of-evil #P"Resources/")) (deploy:define-hook (:boot set-resources-path) () (setf *resources-path* (merge-pathnames #P"Resources/" (uiop:pathname-parent-directory-pathname (deploy:runtime-directory))))) (define-constant +repl-update-interval+ 0.3d0) (define-constant +fps-font-path+ "fonts/inconsolata.ttf" :test #'string=) (define-constant +fps-font-size+ 24) (define-constant +damage-numbers-font-path+ "fonts/acme.ttf" :test #'string=) (define-constant +damage-numbers-font-size+ 26) (define-constant +ui-font-path+ "fonts/acme.ttf" :test #'string=) (define-constant +ui-font-size+ 28) (define-constant +config-path+ "../config.cfg" :test #'string=) (defun init () (ecs:bind-storage) (load-ui) (load-sprites) (load-sounds) (setf *map-descriptions* (read (al:make-character-stream "descriptions.txt"))) (toggle-ui-window :map-selector :on t) (trivial-garbage:gc :full t)) (declaim (type fixnum *fps*)) (defvar *fps* 0) (defun update (dt ui-context) (unless (zerop dt) (setf *fps* (round 1 dt))) (ecs:run-systems :dt (float dt 0.0) :ui-context ui-context)) (define-constant +white+ (al:map-rgba 255 255 255 0) :test #'equalp) (defun render (fps-font) (nk:allegro-render) (when (al:get-config-value (al:get-system-config) "trace" "fps") (al:draw-text fps-font +white+ 0 0 0 (format nil "~d FPS" *fps*)))) (declaim (inline pressed-key)) (defun pressed-key (event) (cffi:with-foreign-slots ((al::keycode) event (:struct al:keyboard-event)) al::keycode)) (cffi:defcallback %main :int ((argc :int) (argv :pointer)) (declare (ignore argc argv)) (handler-bind ((error #'(lambda (e) (unless *debugger-hook* (al:show-native-message-box (cffi:null-pointer) "Hey guys" "We got a big error here :(" (with-output-to-string (s) (uiop:print-condition-backtrace e :stream s)) (cffi:null-pointer) :error))))) (uiop:chdir *resources-path*) (al:set-app-name "cycle-of-evil") (unless (al:init) (error "Initializing liballegro failed")) (let ((config (al:load-config-file +config-path+))) (unless (cffi:null-pointer-p config) (al:merge-config-into (al:get-system-config) config))) (al:set-config-value (al:get-system-config) "trace" "level" "debug") (unless (al:init-primitives-addon) (error "Initializing primitives addon failed")) (unless (al:init-image-addon) (error "Initializing image addon failed")) (unless (al:init-font-addon) (error "Initializing liballegro font addon failed")) (unless (al:init-ttf-addon) (error "Initializing liballegro TTF addon failed")) (unless (al:install-audio) (error "Intializing audio addon failed")) (unless (al:init-acodec-addon) (error "Initializing audio codec addon failed")) (unless (al:restore-default-mixer) (error "Initializing default audio mixer failed")) (al:set-new-display-option :vsync 2 :require) (let ((display (al:create-display +window-width+ +window-height+)) (event-queue (al:create-event-queue))) (when (cffi:null-pointer-p display) (error "Initializing display failed")) (al:draw-bitmap (al:ensure-loaded #'al:load-bitmap "images/loading.png") 0 0 0) (al:set-mouse-cursor display (al:create-mouse-cursor (al:ensure-loaded #'al:load-bitmap "images/ui/01.png") 22 17)) (al:flip-display) (al:inhibit-screensaver t) (al:set-window-title display "Cycle of Evil") (al:register-event-source event-queue (al:get-display-event-source display)) (al:install-keyboard) (al:register-event-source event-queue (al:get-keyboard-event-source)) (al:install-mouse) (al:register-event-source event-queue (al:get-mouse-event-source)) (al:set-new-bitmap-flags '(:min-linear)) (unwind-protect (cffi:with-foreign-object (event '(:union al:event)) (init) (#+darwin trivial-main-thread:call-in-main-thread #-darwin funcall #'livesupport:setup-lisp-repl) (loop :named main-game-loop :with *should-quit* := nil :with fps-font := (al:ensure-loaded #'al:load-ttf-font +fps-font-path+ (- +fps-font-size+) 0) :with *damage-numbers-font* := (al:ensure-loaded #'al:load-ttf-font +damage-numbers-font-path+ (- +damage-numbers-font-size+) 0) :with ui-font := (al:ensure-loaded #'nk:allegro-font-create-from-file +ui-font-path+ (- +ui-font-size+) 0) :with ui-context := (nk:allegro-init ui-font display +window-width+ +window-height+) :with ticks :of-type double-float := (al:get-time) :with last-repl-update :of-type double-float := ticks :with dt :of-type double-float := 0d0 :while (loop :named event-loop :initially (nk:input-begin ui-context) :while (al:get-next-event event-queue event) :for type := (cffi:foreign-slot-value event '(:union al:event) 'al::type) :do (if (and (eq type :key-down) (eq (pressed-key event) :escape)) (toggle-ui-window :main-menu) (nk:allegro-handle-event event)) :always (not (eq type :display-close)) :finally (nk:input-end ui-context)) :never *should-quit* ;; lol :do (let ((new-ticks (al:get-time))) (setf dt (- new-ticks ticks) ticks new-ticks)) (when (> (- ticks last-repl-update) +repl-update-interval+) (livesupport:update-repl-link) (setf last-repl-update ticks)) (al:clear-to-color +black+) (livesupport:continuable (update dt ui-context) (render fps-font)) (al:flip-display) :finally (nk:allegro-shutdown) (nk:allegro-font-del ui-font) (al:destroy-font *damage-numbers-font*) (al:destroy-font fps-font))) (al:inhibit-screensaver nil) (al:destroy-event-queue event-queue) (al:destroy-display display) (al:stop-samples) (al:uninstall-system) (al:uninstall-audio) (al:shutdown-ttf-addon) (al:shutdown-font-addon) (al:shutdown-image-addon)))) 0) (defun main () (#+darwin trivial-main-thread:with-body-in-main-thread #-darwin progn nil (float-features:with-float-traps-masked (:divide-by-zero :invalid :inexact :overflow :underflow) (al:run-main 0 (cffi:null-pointer) (cffi:callback %main)))))
7,750
Common Lisp
.lisp
165
33.70303
80
0.547688
lockie/spring-lisp-jam-2024
2
0
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
59b1e8b22852eac151f7910201883842ee495b63c2098d7358eda82f5e8438a7
20,570
[ -1 ]
20,571
sprite.lisp
lockie_spring-lisp-jam-2024/src/sprite.lisp
(in-package #:cycle-of-evil) (ecs:defcomponent (animation-prefab :composite-index (animation-prefab (sprite-name sequence-name) :unique t)) "Animated sprite prefab to copy data from." (sprite-name :|| :type keyword :documentation "Sprite name") (sequence-name :|| :type keyword :documentation "Animation sequence name")) (ecs:defcomponent sprite "Animated sprite." (name :|| :type keyword :documentation "Sprite name") (sequence-name :idle :type keyword :documentation "Animation sequence name")) (ecs:defcomponent animation-sequence "Animated sprite sequence." (name :|| :type keyword :documentation "Animation sequence name") (sprite-name :|| :type keyword :documentation "Sprite name") (frames 0 :type fixnum :documentation "Number of frames in animation") (layers 0 :type fixnum :documentation "Number of layers in sprite") (frame-duration 0.0 :type single-float :documentation "Each frame duration, in seconds. NOTE: assuming duration is the same for all frames") (repeat 0 :type bit :documentation "Whether to repeat animation")) (ecs:defcomponent animation-state "Sprite animation state." (frame 0 :type fixnum :documentation "Current animation frame") (time 0.0 :type single-float :documentation "Time elapsed from the beginning of frame, seconds") (flip 0 :type bit :documentation "Flip sprite horizontally so character looks left") (rotation 0.0 :type single-float :documentation "Rotation (mostly used for projectiles)") (finished 0 :type bit :documentation "Only for cases with repeat=0") (tint 0 :type fixnum :documentation "RGBA value for tint, 0 for no tint")) (define-constant +transparent+ (al:map-rgba 255 255 255 255) :test #'equalp) (ecs:defsystem render-sprites (:components-ro (position size image animation-sequence animation-state) :initially (al:hold-bitmap-drawing t) :finally (al:hold-bitmap-drawing nil)) (loop :for layer :of-type fixnum :from 0 :below animation-sequence-layers :with x-offset := (* animation-state-frame size-width) :with tint := (if (zerop animation-state-tint) +transparent+ `(al::r ,(float (ldb (byte 8 24) animation-state-tint)) al::g ,(float (ldb (byte 8 16) animation-state-tint)) al::b ,(float (ldb (byte 8 8) animation-state-tint)) al::a ,(float (ldb (byte 8 0) animation-state-tint)))) :for y-offset := (* layer size-height) :for scaled-width := (* +scale-factor+ size-width) :for scaled-height := (* +scale-factor+ size-height) :do (al:draw-tinted-scaled-rotated-bitmap-region image-bitmap x-offset y-offset size-width size-height (if (zerop layer) ;; no tint on shadow, which is usually layer 0 +transparent+ tint) (* 0.5 size-width) (* 0.5 size-height) position-x position-y +scale-factor+ +scale-factor+ animation-state-rotation (if (zerop animation-state-flip) 0 :flip-horizontal))) ;; (al:draw-circle position-x position-y 2 (al:map-rgb 0 255 255) 2) ;; (al:draw-rectangle ;; (- position-x (* 0.5 (* +scale-factor+ size-width))) ;; (- position-y (* 0.5 (* +scale-factor+ size-height))) ;; (+ (- position-x (* 0.5 (* +scale-factor+ size-width))) ;; (* +scale-factor+ size-width)) ;; (+ (- position-y (* 0.5 (* +scale-factor+ size-height))) ;; (* +scale-factor+ size-height)) ;; (al:map-rgb 255 0 0) ;; 1) ) (ecs:defsystem update-sprites (:components-ro (animation-sequence) :components-rw (animation-state) :arguments ((:dt single-float))) (incf animation-state-time dt) (when (> animation-state-time animation-sequence-frame-duration) (multiple-value-bind (nframes rest-time) (floor animation-state-time animation-sequence-frame-duration) (declare (type non-negative-fixnum nframes)) (setf animation-state-time rest-time) (multiple-value-bind (repeat frame) (truncate (+ animation-state-frame nframes) animation-sequence-frames) (setf animation-state-frame (cond ((zerop repeat) frame) ((zerop animation-sequence-repeat) (setf animation-state-finished 1) (1- animation-sequence-frames)) (t frame))))))) (ecs:defsystem change-sprites-animation (:components-ro (sprite) :components-rw (animation-sequence) :when (not (and (eq animation-sequence-sprite-name sprite-name) (eq animation-sequence-name sprite-sequence-name)))) (let ((prefab (animation-prefab :sprite-name sprite-name :sequence-name sprite-sequence-name))) ;; TODO : for prefab=nil case, restart with list of loaded sprites (replace-animation-sequence entity prefab) (replace-image entity prefab) (replace-size entity prefab) (assign-animation-state entity :frame 0 :time 0.0 :flip (if (has-animation-state-p entity) (animation-state-flip entity) 0) :finished 0))) (ecs:defsystem setup-sprites (:components-ro (sprite) :components-no (animation-sequence)) (assign-animation-sequence entity)) (cffi:defcfun memcpy :pointer (dst :pointer) (src :pointer) (size :unsigned-long)) (defun load-sprite-file (full-filename) (loop :with name := (make-keyword (string-upcase (kebabize (pathname-name full-filename)))) :with sprite := (ase:load-sprite (al:make-binary-stream full-filename)) :with sprite-width := (ase:sprite-width sprite) :with sprite-height := (ase:sprite-height sprite) :with layers := (ase:sprite-layers sprite) :with nlayers := (floor (length layers) 2) :with duration :of-type fixnum := 0 :for (tag-name tag) :on (ase:sprite-tags sprite) :by #'cddr :for first-frame := (ase:tag-first-frame tag) :for last-frame := (ase:tag-last-frame tag) :for tag-length := (- last-frame first-frame -1) :for sequence-name := (make-keyword (kebabize (string tag-name))) :for tag-repeat := (ase:tag-repeat tag) :for bitmap-width := (* tag-length sprite-width) :for bitmap-height := (* nlayers sprite-height) :for bitmap := (al:create-bitmap bitmap-width bitmap-height) :for bitmap-lock := (al:lock-bitmap bitmap :abgr-8888 :readwrite) :for row :of-type fixnum := 0 :do (doplist (layer-name layer layers) (loop :for frame :from first-frame :upto last-frame :for col :of-type fixnum :from 0 :for cel := (aref (ase:layer-cels layer) frame) :when cel :do (cffi:with-foreign-slots ((al::data al::pitch al::pixel-size) bitmap-lock (:struct al::locked-region)) (loop :with cel-data := (ase:cel-data cel) :with cel-width := (ase:cel-width cel) :with cel-width-bytes := (* 4 cel-width) :with start-x := (+ (* sprite-width col) (ase:cel-x cel)) :with start-y := (+ (* sprite-height row) (ase:cel-y cel)) :with end-y := (+ start-y (ase:cel-height cel)) :for y :from start-y :below end-y :for dst := (cffi:inc-pointer al::data (+ (* 4 start-x) (* y al::pitch))) :do (cffi:with-pointer-to-vector-data (src cel-data) (memcpy dst (cffi:inc-pointer src (* (- y start-y) cel-width-bytes)) cel-width-bytes)))) (setf duration (ase:cel-duration cel)) :finally (incf row))) (al:unlock-bitmap bitmap) (ecs:make-object `((:image :bitmap ,bitmap) (:size :width ,(float sprite-width) :height ,(float sprite-height)) (:animation-prefab :sprite-name ,name :sequence-name ,sequence-name) (:animation-sequence :name ,sequence-name :sprite-name ,name :frames ,tag-length :layers ,nlayers :frame-duration ,(/ duration 1000.0) :repeat ,(if (zerop tag-repeat) 1 0)))))) (cffi:defcallback process-sprite-file :int ((file (:pointer (:struct al::fs-entry))) (data :pointer)) (declare (ignore data)) (if (zerop (logand (al::get-fs-entry-mode file) (cffi:foreign-bitfield-value 'al::file-mode '(:isdir)))) (progn (load-sprite-file (al::get-fs-entry-name file)) (cffi:foreign-enum-value 'al::for-each-fs-entry-result :ok)) (cffi:foreign-enum-value 'al::for-each-fs-entry-result :skip))) (defun load-sprites () (let ((sprites-dir (al:create-fs-entry "sprites"))) (unwind-protect (= (cffi:foreign-enum-value 'al::for-each-fs-entry-result :ok) (al::for-each-fs-entry sprites-dir (cffi:callback process-sprite-file) (cffi:null-pointer))) (al:destroy-fs-entry sprites-dir))))
10,242
Common Lisp
.lisp
203
36.743842
80
0.55202
lockie/spring-lisp-jam-2024
2
0
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
4c725ea6bce38a6fcc015c5c33f184c6ebb01d9a5d64d2a4f052723d11ac22a5
20,571
[ -1 ]
20,572
priority-queue.lisp
lockie_spring-lisp-jam-2024/src/priority-queue.lisp
;;;; This priority queue implementation is heavily based on ;;;; pettomato-indexed-priority-queue ;;;; Copyright (c) 2012 Austin Haas <[email protected]> ;;;; which is in turn based on code from Peter Norvig's AIMA book ;;;; Copyright (c) 1998-2002 by Peter Norvig. (in-package #:cycle-of-evil) (define-condition empty-queue-error (error) () (:documentation "Signaled when an operation depends on a non-empty queue.")) (declaim (inline parent)) (defun parent (i) (declare (fixnum i)) (the fixnum (floor (- i 1) 2))) (declaim (inline left)) (defun left (i) (declare (fixnum i)) (the fixnum (+ 1 i i))) (declaim (inline right)) (defun right (i) (declare (fixnum i)) (the fixnum (+ 2 i i))) (defun heapify (heap priorities i N) "Assume that the children of i are heaps, but that heap[i] may be worse than its children. If it is, move heap[i] down where it belongs. [Page 130 CL&R 2nd ed.]." (declare (type (simple-array fixnum) heap) (type (simple-array single-float) priorities) (type fixnum i N)) (loop :with item :of-type fixnum := (aref heap i) :with item-priority :of-type single-float := (aref priorities i) :for l :of-type fixnum := (left i) :for r :of-type fixnum := (right i) :for best :of-type fixnum := i :for best-item :of-type fixnum := item :for best-priority :of-type single-float := item-priority :do (when (< l N) (let ((left-item (aref heap l)) (left-priority (aref priorities l))) (when (< left-priority item-priority) (setf best l best-item left-item best-priority left-priority)))) (when (< r N) (let ((right-item (aref heap r)) (right-priority (aref priorities r))) (when (< right-priority best-priority) (setf best r best-item right-item best-priority right-priority)))) (cond ((/= best i) (setf (aref heap i) best-item (aref priorities i) best-priority i best)) (t (setf (aref heap i) item (aref priorities i) item-priority) (return))))) (declaim (ftype (function ((simple-array fixnum) (simple-array single-float) array-length)) improve-key)) (defun improve-key (heap priorities i) "The item at i may be better than its parent. Promote the item until it is in the correct position." (let ((item (aref heap i)) (item-priority (aref priorities i))) (loop :for index :of-type fixnum := i :then parent-index :while (> index 0) :for parent-index :of-type fixnum := (parent index) :for parent :of-type fixnum := (aref heap parent-index) :while (< item-priority (aref priorities parent-index)) :do (setf (aref heap index) parent (aref priorities index) (aref priorities parent-index)) :finally (setf (aref heap index) item (aref priorities index) item-priority)))) (defstruct q (items nil :type (simple-array fixnum)) (priorities nil :type (simple-array single-float)) ;; actual number of elements; length might be bigger (size 0 :type array-length)) (declaim (inline make-queue)) (defun make-queue (items priorities) (make-q :items items :priorities priorities)) (declaim (inline queue-empty-p) (ftype (function (q) boolean) queue-empty-p)) (defun queue-empty-p (q) "Are there no items in the queue?" (zerop (q-size q))) (declaim (ftype (function (q) fixnum) queue-pop)) (defun queue-pop (q) "Remove the element from the front of the queue and return it. Signals empty-queue-error if the queue is empty. [Page 139 CL&R 2nd ed.]." (if (queue-empty-p q) (error 'empty-queue-error) (let* ((size (q-size q)) (heap (q-items q)) (priorities (q-priorities q)) (min (aref heap 0))) (when (> size 1) (setf (aref heap 0) (aref heap (1- size))) (setf (aref priorities 0) (aref priorities (1- size)))) (when (plusp size) (setf size (1- size) (q-size q) size)) (heapify heap (q-priorities q) 0 size) min))) (declaim (ftype (function (q fixnum single-float) q) queue-insert)) (defun queue-insert (q item priority) "Insert the item by priority according to the compare function. Returns the queue. [Page 140 CL&R 2nd ed.]." (let ((heap (q-items q)) (priorities (q-priorities q)) (size (q-size q))) (when (>= size (length heap)) (let ((new-size (ecs::new-capacity size))) (setf heap (adjust-simple-array heap new-size :element-type 'fixnum) (q-items q) heap priorities (adjust-simple-array priorities new-size :element-type 'single-float) (q-priorities q) priorities))) (setf (aref heap size) item (aref priorities size) priority) (improve-key heap priorities size) (incf (q-size q)) q))
5,352
Common Lisp
.lisp
125
33.328
78
0.582359
lockie/spring-lisp-jam-2024
2
0
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
56507e42144b3fbea2878dadd219fed66531ebec60dd6c7b3796b735406cd41c
20,572
[ -1 ]
20,573
progress.lisp
lockie_spring-lisp-jam-2024/src/progress.lisp
(in-package #:cycle-of-evil) (ecs:defsystem test-win (:components-ro (map) :when (length= 0 (team 0))) (make-sound-effect -1 :win (/ +window-width+ 2.0) (/ +window-height+ 2.0) :variations 1) (ecs:delete-entity entity) (setf *current-map* -1) (toggle-ui-window :win-message :on t)) (ecs:defsystem test-defeat (:components-ro (map) :when (length= 0 (team 1))) (make-sound-effect -1 :lose (/ +window-width+ 2.0) (/ +window-height+ 2.0) :variations 1) (ecs:delete-entity entity) (setf *current-map* -1) (toggle-ui-window :loose-message :on t))
697
Common Lisp
.lisp
21
24.761905
44
0.543834
lockie/spring-lisp-jam-2024
2
0
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
85c821f376d6b3b3e61624d700e6910ff7d5c052a4288441be80082a75f826dd
20,573
[ -1 ]
20,574
fire.lisp
lockie_spring-lisp-jam-2024/src/fire.lisp
(in-package #:cycle-of-evil) (ecs:defcomponent fire (duration 0.0 :type single-float) (dps 0 :type fixnum :documentation "Damage per second")) (ecs:defcomponent fire-effect (character -1 :type ecs:entity :index flames :unique t)) (ecs:defsystem spread-fire (:components-ro (fire position)) (with-tiles (encode-float-coordinates position-x position-y) object (when (and (/= object entity) (not (has-fire-p object)) (not (has-fire-effect-p object)) (has-character-p object)) (make-on-fire object :dps (1+ (random fire-dps)))))) (ecs:defsystem move-fire-effect (:components-ro (fire-effect) :components-rw (position)) (with-position (character-x character-y) fire-effect-character (setf position-x character-x position-y character-y position-tile (encode-float-coordinates position-x position-y)))) (ecs:defsystem burn (:components-rw (fire) :arguments ((:dt single-float))) (let ((previous-duration fire-duration)) (decf fire-duration dt) (unless (plusp fire-duration) (ecs:delete-entity (flames entity)) (return-from ecs:current-entity (delete-fire entity))) (unless (= (the fixnum (truncate previous-duration)) (the fixnum (truncate fire-duration))) (when (has-health-p entity) (make-damage entity fire-dps))))) (defun make-on-fire (entity &key (dps 1) (duration 3.9)) (assign-fire entity :duration duration :dps dps) (let ((already-burning (flames entity :missing-error-p nil))) (unless (ecs:entity-valid-p already-burning) (with-position () entity (make-sound-effect (ecs:make-object `((:parent :entity ,entity) (:position :x ,x :y ,y) (:fire-effect :character ,entity) (:sprite :name :fire :sequence-name :fire))) :fire x y :repeat t :variations 1)))))
1,905
Common Lisp
.lisp
45
35.8
75
0.655154
lockie/spring-lisp-jam-2024
2
0
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
f57c627a2d40643b9b965e5b0584cbd2bde08027c38b60e52a78f1e50dbae7ef
20,574
[ -1 ]
20,575
common.lisp
lockie_spring-lisp-jam-2024/src/common.lisp
(in-package #:cycle-of-evil) (define-constant +window-width+ 1280) (define-constant +window-height+ 800) (define-constant +black+ (al:map-rgb 0 0 0) :test #'equalp) (ecs:defcomponent parent (entity -1 :type ecs:entity :index children)) (ecs:defcomponent character (team 0 :type bit :index team :documentation "0 = defender, 1 = attacker") (vision-range 0.0 :type single-float) (attack-range 0.0 :type single-float) (movement-speed 0.0 :type single-float) (melee-attack 0 :type bit) (splash-attack 0 :type bit) (projectile-speed 0.0 :type single-float) (damage-min 0 :type fixnum) (damage-max 0 :type fixnum) (defense-multiplier 1.0 :type single-float :documentation "Incoming damage is multiplied by this value") (fire-damage 0 :type fixnum :documentation "If non-zero, character's attacks ignite with this DPS") (attack-cooldown 0.0 :type single-float)) (ecs:hook-up ecs:*entity-deleting-hook* (lambda (entity) (dolist (child (children entity)) (ecs:delete-entity child)))) (ecs:defcomponent behavior (type :|| :type keyword)) (ecs:defcomponent map (tint nil :type list :documentation "Global map tint color.")) (defvar *map-descriptions*) (defparameter *current-progress* 0) (eval-when (:compile-toplevel :load-toplevel :execute) (declaim (type single-float +scale-factor+ +tile-size+ +scaled-tile-size+)) (defconstant +scale-factor+ 0.5) (defconstant +tile-size+ 64.0) (defconstant +scaled-tile-size+ (* +tile-size+ +scale-factor+))) (declaim (inline distance)) (defun distance (x1 y1 x2 y2) (flet ((sqr (x) (* x x))) (declare (inline sqr)) (sqrt (+ (sqr (- x1 x2)) (sqr (- y1 y2)))))) (declaim (inline distance*) (ftype (function (float-coordinate float-coordinate float-coordinate float-coordinate) single-float) distance*)) (defun distance* (x1 y1 x2 y2) (flet ((sqr (x) (* x x))) (declare (inline sqr)) (+ (sqr (- x1 x2)) (sqr (- y1 y2))))) (declaim (inline tile-start) (ftype (function (float-coordinate float-coordinate) (values float-coordinate float-coordinate)) tile-start)) (defun tile-start (x y) (values (* +scaled-tile-size+ (the fixnum (floor x +scaled-tile-size+))) (* +scaled-tile-size+ (the fixnum (floor y +scaled-tile-size+))))) (declaim (inline tile-center) (ftype (function (float-coordinate float-coordinate) (values float-coordinate float-coordinate)) tile-center)) (defun tile-center (x y) (values (* +scaled-tile-size+ (+ 0.5 (the fixnum (floor x +scaled-tile-size+)))) (* +scaled-tile-size+ (+ 0.5 (the fixnum (floor y +scaled-tile-size+)))))) (declaim (inline same-tile-p) (ftype (function (float-coordinate float-coordinate float-coordinate float-coordinate) boolean) same-tile-p)) (defun same-tile-p (x1 y1 x2 y2) (and (= (floor x1 +scaled-tile-size+) (floor x2 +scaled-tile-size+)) (= (floor y1 +scaled-tile-size+) (floor y2 +scaled-tile-size+)))) (ecs:defcomponent position "The object position in pixels." (x 0.0 :type float-coordinate :documentation "x position aka screen pixel coordinate") (y 0.0 :type float-coordinate :documentation "y position aka screen pixel coordinate") (tile (encode-float-coordinates x y) :type fixnum :index tiles :documentation "Tile index, for fast map tile lookups.")) (ecs:defcomponent size "Unscaled object size in pixels." (width 0.0 :type float-coordinate) (height 0.0 :type float-coordinate)) (ecs:defcomponent image (bitmap (cffi:null-pointer) :type cffi:foreign-pointer)) (declaim (ftype (function (string) string) kebabize) (inline kebabize)) (defun kebabize (name) (substitute #\- #\Space (substitute #\- #\_ name))) (declaim (type array-length *world-width* *world-height*)) (define-global-parameter *world-width* 0 "World width in tiles") (define-global-parameter *world-height* 0 "World height in tiles") (declaim (inline randint) (ftype (function (fixnum fixnum) fixnum) randint)) (defun randint (start end) (+ start (random (+ 1 (- end start)))))
4,477
Common Lisp
.lisp
110
33.809091
77
0.635673
lockie/spring-lisp-jam-2024
2
0
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
28160c02c066f95501fc5dc0d4501ec1bc9ac02ee40afd785fa7c1bd1f12ea37
20,575
[ -1 ]
20,576
tint.lisp
lockie_spring-lisp-jam-2024/src/tint.lisp
(in-package #:cycle-of-evil) (ecs:defsystem render-map-tint (:components-ro (map) :when map-tint) (al:draw-filled-rectangle 0 0 +window-width+ +window-height+ map-tint))
179
Common Lisp
.lisp
5
33
73
0.72093
lockie/spring-lisp-jam-2024
2
0
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
c54874943a4995782f4054fadf7269554e7b4e50dc326e0320cc3241502a31b5
20,576
[ -1 ]
20,577
sheep.lisp
lockie_spring-lisp-jam-2024/src/sheep.lisp
(in-package #:cycle-of-evil) (ecs:defcomponent sheep (meat-points 0 :type fixnum) (sex 0 :type bit :index sheep-of-sex) (vision-range 0.0 :type single-float) (movement-speed 0.0 :type single-float) (feed-probability 0.0 :type single-float) (breed-probability 0.0 :type single-float)) (ecs:defsystem mortify-sheep (:components-ro (health sheep position) :components-rw (sprite) :when (not (plusp health-points))) "Polly Parrot, wake up. Polly." (make-sound-effect entity :slaughter position-x position-y :variations 1) (setf sprite-name :resources sprite-sequence-name :m-spawn) (delete-health entity) (when (has-behavior-p entity) (delete-behavior-tree (behavior-type entity) entity) (delete-behavior entity)) (make-meat entity :points sheep-meat-points) (delete-sheep entity)) (defconstant +female+ 0) (defconstant +male+ 1) (declaim (inline male-p)) (defun male-p (sex) (= sex +male+)) (define-behavior-tree-node (pick-grass :components-ro (position sheep) :with (grass-bushes := (shuffle (grass 1)))) () "Picks the random grass bush as a target. Fails if there is no grass nearby." (flet ((sqr (x) (* x x))) (loop :for grass :of-type ecs:entity :in grass-bushes :for distance := (with-position (grass-x grass-y) grass (distance* position-x position-y grass-x grass-y)) :when (<= distance (sqr sheep-vision-range)) :do (assign-target entity :entity grass) (return-from ecs:current-entity (complete-node t)) :finally (complete-node nil)))) (define-constant +max-sheep-population+ 10) (define-behavior-tree-node (pick-mate :components-ro (sheep position) :with (females := (shuffle (sheep-of-sex +female+))) :enable (< (length females) +max-sheep-population+)) () "Picks the random sheep to mate. Fails if there is no possible mate nearby." (if (male-p sheep-sex) (flet ((sqr (x) (* x x))) (loop :for female :of-type ecs:entity :in females :for distance := (with-position (female-x female-y) female (distance* position-x position-y female-x female-y)) :when (<= distance (sqr sheep-vision-range)) :do (assign-target entity :entity female) (return-from ecs:current-entity (complete-node t)) :finally (complete-node nil))) (complete-node nil))) (define-behavior-tree-node (hump :components-ro (position) :components-rw (target sprite animation-state) :arguments ((:dt single-float))) ((time 2.0 :type single-float :documentation "Hump time in seconds.")) "A little bit of Netflix & chill." (cond ((plusp hump-time) (when (= hump-time 2.0) (make-sound-effect entity :sheep position-x position-y :variations 1)) (setf sprite-sequence-name :hump animation-state-flip (animation-state-flip target-entity)) (decf hump-time dt)) (t (setf sprite-sequence-name :idle) (complete-node t)))) (define-behavior-tree-node (reproduce :components-ro (position health sheep target)) () "Sheep birth." (let+ ((mom target-entity) ((&flet average (a b) (* 0.5 (+ a b)))) ((&macrolet inherit (feature) `(random (+ 1 ,feature (,feature mom)))))) (with-position (mom-x mom-y) mom (ecs:make-object `((:parent :entity ,entity) (:position :x ,(average position-x mom-x) :y ,(average position-y mom-y)) (:health :points ,(inherit health-points)) (:sheep :meat-points ,(inherit sheep-meat-points) :sex ,(random 2) :vision-range ,(inherit sheep-vision-range) :movement-speed ,(inherit sheep-movement-speed) :feed-probability ,(clamp (inherit sheep-feed-probability) 0.0 1.0) :breed-probability ,(clamp (inherit sheep-breed-probability) 0.0 1.0)) (:behavior :type :sheep) (:sprite :name :happy-sheep :sequence-name :idle))))) (complete-node t)) (define-behavior-tree sheep ((repeat :name "root") ((fallback) ((sequence :name "feed") ((random :probability (sheep-feed-probability entity))) ((pick-grass)) ((repeat-until-fail) ((sequence :name "browse") ((invert) ((test-target-near :range +scaled-tile-size+))) ((calculate-path)) ((follow-path)) ((move :speed (sheep-movement-speed entity))))) ((wait :name "munch" :time 2.0))) ((sequence :name "breed") ((random :probability (sheep-breed-probability entity))) ((pick-mate)) ((repeat-until-fail) ((sequence :name "animal-sex") ((repeat-until-fail) ((sequence :name "pursuit") ((test-target-alive)) ((invert) ((test-target-near :range +scaled-tile-size+))) ((calculate-path)) ((follow-path)) ((move :speed (sheep-movement-speed entity))))) ((hump)) ((test-target-alive)) ((test-target-near :range +scaled-tile-size+)) ((invert) ((reproduce)))))) ((idle)) ((wait :time 1.0)))))
5,546
Common Lisp
.lisp
137
31.065693
81
0.579103
lockie/spring-lisp-jam-2024
2
0
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
887627fd0ea042915324efbb674fba806ea0a98e80ef7fec29fdb3f5120cc0d6
20,577
[ -1 ]
20,578
peasant.lisp
lockie_spring-lisp-jam-2024/src/peasant.lisp
(in-package #:cycle-of-evil) (ecs:defcomponent peasant (vision-range 0.0 :type single-float) (movement-speed 0.0 :type single-float) (slaughter-range 0.0 :type single-float) (slaughter-damage 0 :type fixnum) (slaughter-cooldown 0.0 :type single-float) (unload-range 0.0 :type single-float) (eagerness 0.5 :type single-float :documentation "Probability to not to slack off, 0 to 1") (poison-probability 0.0 :type single-float :documentation "Probability to poision the meat") (poison-dps 0 :type fixnum) (rest-time 5.0 :type single-float)) (ecs:defsystem carry-meat (:components-ro (meat) :components-rw (position) :when (ecs:entity-valid-p meat-carry)) (with-position (carry-x carry-y) meat-carry (setf position-x carry-x position-y (- carry-y (/ +scaled-tile-size+ 2))))) (define-behavior-tree-node (pick-sheep :components-ro (position peasant) :with (livestock := (shuffle (sheep-of-sex (random 2))))) () "Picks the random sheep as a target. Fails if there is no sheep nearby." (flet ((sqr (x) (* x x))) (loop :for sheep :of-type ecs:entity :in livestock :for distance := (with-position (sheep-x sheep-y) sheep (distance* position-x position-y sheep-x sheep-y)) :when (<= distance (sqr peasant-vision-range)) :do (assign-target entity :entity sheep) (return-from ecs::current-entity (complete-node t)) :finally (complete-node nil)))) (define-behavior-tree-node (butcher :components-ro (position peasant target animation-sequence) :components-rw (sprite animation-state)) ((started 0 :type bit) (done 0 :type bit :documentation "Attack happened, but animation's still playing")) (with-position (target-x target-y) target-entity (cond ((zerop butcher-started) (setf sprite-sequence-name :build animation-state-flip (if (minusp (- target-x position-x)) 1 0) butcher-started 1)) ((and (zerop butcher-done) (= animation-state-frame (- animation-sequence-frames 3))) (make-damage target-entity peasant-slaughter-damage) (make-sound-effect entity :punch position-x position-y) (setf butcher-done 1)) ((and (plusp animation-state-finished) (= animation-state-frame (1- animation-sequence-frames))) (setf sprite-sequence-name :idle) (complete-node t))))) (define-behavior-tree-node (poison-meat :components-ro (target peasant)) () (make-poisoned target-entity :dps peasant-poison-dps) (complete-node t)) (define-behavior-tree-node (pick-up :components-ro (peasant target) :components-rw (sprite)) () (with-meat () target-entity (if (ecs:entity-valid-p carry) (complete-node nil) ;; someone else took it (complete-node (setf sprite-sequence-name :carry carry entity))))) (define-behavior-tree-node (locate-drop-off :components-ro (position peasant) :with (castles := (castle 1))) () (assign-target entity :entity (random-elt castles)) (complete-node t)) (define-behavior-tree-node (unload :components-ro (peasant target) :components-rw (sprite)) () (when-let (meat (first (meat-carried-by entity :count 1))) (setf (meat-carry meat) -1)) (setf sprite-sequence-name :idle) (complete-node t)) ;; "More work?" (define-behavior-tree peasant ((repeat :name "root") ((fallback) ((sequence) ((random :probability (peasant-eagerness entity))) ((pick-sheep)) ((invert) ((repeat-until-fail) ((sequence :name "slaughter") ((sequence) ((repeat-until-fail) ((sequence :name "pursuit") ((test-target-alive)) ((invert) ((test-target-near :range (peasant-slaughter-range entity)))) ((calculate-path)) ((follow-path)) ((move :speed (peasant-movement-speed entity))))) ((test-target-near :range (peasant-slaughter-range entity)))) ((repeat-until-fail) ((sequence :name "attacks") ((test-target-alive)) ((test-target-near :range (peasant-slaughter-range entity))) ((butcher)) ((wait :time (peasant-slaughter-cooldown entity))))) ((fallback) ((test-target-alive)) ((sequence) ((fallback) ((sequence :name "poision") ((random :probability (peasant-poison-probability entity))) ((poison-meat))) ((always-true))) ((pick-up)) ((locate-drop-off)) ((invert) ((repeat-until-fail) ((sequence :name "carry") ((invert) ((test-target-near :range (peasant-unload-range entity)))) ((calculate-path)) ((follow-path)) ((move :speed (peasant-movement-speed entity) :animation-sequence :run-carry)))))) ((invert) ((unload)))))))) ((invert) ((idle))) ((invert) ((sequence :name "wander-off") ((wander-off)) ((move :speed (peasant-movement-speed entity))) ((idle)))) ((sequence :name "slack-off") ((wait :time (peasant-rest-time entity)))))))
5,885
Common Lisp
.lisp
143
29.734266
79
0.552531
lockie/spring-lisp-jam-2024
2
0
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
51a2f401d5c1d8cd2b7ba133670c989965cf69ba6157b9dafb0626ee9f1ad7eb
20,578
[ -1 ]
20,579
build.lisp
lockie_spring-lisp-jam-2024/package/build.lisp
(proclaim '(optimize (speed 3) (safety 0) (debug 0) (compilation-speed 0))) (ql:register-local-projects) (ql-util:without-prompting (ql:update-all-dists)) (push :ecs-unsafe *features*) (ql:quickload '(#:cycle-of-evil #:deploy)) (asdf:make :cycle-of-evil)
255
Common Lisp
.lisp
6
41.5
75
0.726908
lockie/spring-lisp-jam-2024
2
0
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
15a16b67abcf3ece1372a9f30cbb85b0044364d37d952292487de0a4a3ce0be1
20,579
[ -1 ]
20,580
cycle-of-evil.asd
lockie_spring-lisp-jam-2024/cycle-of-evil.asd
(defsystem "cycle-of-evil" :version "0.0.3" :author "Andrew Kravchuk" :license "GPLv3" :depends-on (#:alexandria #:cl-aseprite #:cl-astar #:cl-fast-behavior-trees #:cl-fast-ecs #:cl-liballegro #:cl-liballegro-nuklear #:cl-liballegro-nuklear/declarative #:cl-tiled #:global-vars #:let-plus #:livesupport) :serial t :components ((:module "src" :components ((:file "package") (:file "common") (:file "sound") (:file "damage") (:file "sprite") (:file "tint") (:file "map") (:file "poison") (:file "fire") (:file "projectile") (:file "priority-queue") (:file "character") (:file "offensive") (:file "sheep") (:file "peasant") (:file "ui") (:file "progress") (:file "main")))) :description "Spring Lisp Game Jam 2024 entry" :defsystem-depends-on (#:deploy) :build-operation "deploy-op" :build-pathname #P"cycle-of-evil" :entry-point "cycle-of-evil:main")
1,357
Common Lisp
.asd
42
19.214286
50
0.438783
lockie/spring-lisp-jam-2024
2
0
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
79d3c45957d27d596b7c8e09bdc5e64646510af95fbdbdede757d7624857dfa2
20,580
[ -1 ]
20,582
cycle-of-evil.desktop
lockie_spring-lisp-jam-2024/package/cycle-of-evil.desktop
[Desktop Entry] Type=Application Name=Cycle of Evil Exec=cycle-of-evil Terminal=false Categories=Game; Icon=icon
113
Common Lisp
.cl
7
15.142857
18
0.867925
lockie/spring-lisp-jam-2024
2
0
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
cbea3eede3030d6da75afd03a56293a62c9ec3c8dba2440e4bef8c4bc23e15a9
20,582
[ -1 ]
20,603
package.yml
lockie_spring-lisp-jam-2024/.github/workflows/package.yml
name: Build packages on: push: tags: - '**' env: HOME: "/root" jobs: build-linux: runs-on: ubuntu-latest container: image: lockie/docker-lisp-gamedev:latest options: --user root steps: - name: Checkout repository uses: actions/checkout@v3 - name: Build package run: ./package.sh linux - name: Archive package uses: actions/upload-artifact@v3 with: name: linux path: '*.AppImage' if-no-files-found: error build-macos: runs-on: macos-12 steps: - name: Install macports run: | wget -q https://github.com/macports/macports-base/releases/download/v2.9.1/MacPorts-2.9.1-12-Monterey.pkg -P /tmp sudo installer -pkg /tmp/MacPorts-2.9.1-12-Monterey.pkg -target / echo "/opt/local/bin" >> $GITHUB_PATH - name: Install prerequisites run: sudo /opt/local/bin/port -N install sbcl pkgconfig libffi dylibbundler allegro5 - name: Install Quicklisp run: | wget -q https://beta.quicklisp.org/quicklisp.lisp -P /tmp HOME=/Users/runner sbcl --non-interactive --load /tmp/quicklisp.lisp --eval '(quicklisp-quickstart:install :dist-version nil :client-version nil)' --eval '(ql-util:without-prompting (ql:add-to-init-file))' --eval '(ql-dist:install-dist "http://dist.ultralisp.org/" :prompt nil)' --eval '(setf (ql-dist:preference (ql-dist:find-dist "ultralisp")) 0)' --eval '(ql-dist:install-dist "http://dist.luckylambda.technology/releases/lucky-lambda.txt" :prompt nil)' - name: Checkout repository uses: actions/checkout@v3 - name: Build package run: HOME=/Users/runner DYLD_FALLBACK_LIBRARY_PATH=/opt/local/lib PKG_CONFIG_PATH=/opt/local/lib/pkgconfig ./package.sh macos - name: Archive package uses: actions/upload-artifact@v3 with: name: macos path: '*.dmg' if-no-files-found: error build-windows: runs-on: ubuntu-latest container: image: lockie/docker-lisp-gamedev:windows options: --user root steps: - name: Checkout repository uses: actions/checkout@v3 - name: Build package # NOTE: Github actions fuck up Docker's ENTRYPOINT, hence this atrocity run: set +e; cd /opt/quasi-msys2/env; . /opt/quasi-msys2/env/all.src; cd -; WINEPATH="Z:/ucrt64/bin;C:/Program Files (x86)/NSIS" PKG_CONFIG_PATH="Z:/ucrt64/lib/pkgconfig" CC=gcc-wrapper wine busybox sh -c 'export HOME="C:/users/root"; ./package.sh windows' - name: Archive package uses: actions/upload-artifact@v3 with: name: windows path: '*.exe' if-no-files-found: error release: runs-on: ubuntu-latest needs: [build-linux, build-macos, build-windows] steps: - name: Download artifacts uses: actions/download-artifact@v3 - name: Release uses: ncipollo/release-action@v1 with: artifacts: "linux/*.AppImage,macos/*.dmg,windows/*.exe" omitBody: true allowUpdates: true artifactErrorsFailBuild: true
3,140
Common Lisp
.l
78
32.807692
467
0.644677
lockie/spring-lisp-jam-2024
2
0
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
c477edb5531ed11ace7540b78395c1306d73128031d4dd83713ce4bf07d69e31
20,603
[ -1 ]
20,604
ground-flat.tsx
lockie_spring-lisp-jam-2024/Resources/ground-flat.tsx
<?xml version="1.0" encoding="UTF-8"?> <tileset version="1.8" tiledversion="1.8.6" name="ground-flat" tilewidth="64" tileheight="64" tilecount="40" columns="10"> <image source="images/tilemap_flat.png" width="640" height="256"/> <tile id="0"> <properties> <property name="map-tile" type="class" propertytype="map-tile"> <properties> <property name="movement-cost" type="float" value="-1"/> </properties> </property> </properties> </tile> <tile id="1"> <properties> <property name="map-tile" type="class" propertytype="map-tile"> <properties> <property name="movement-cost" type="float" value="-1"/> </properties> </property> </properties> </tile> <tile id="2"> <properties> <property name="map-tile" type="class" propertytype="map-tile"> <properties> <property name="movement-cost" type="float" value="-1"/> </properties> </property> </properties> </tile> <tile id="3"> <properties> <property name="map-tile" type="class" propertytype="map-tile"> <properties> <property name="movement-cost" type="float" value="-1"/> </properties> </property> </properties> </tile> <tile id="5"> <properties> <property name="map-tile" type="class" propertytype="map-tile"> <properties> <property name="movement-cost" type="float" value="-1"/> </properties> </property> </properties> </tile> <tile id="6"> <properties> <property name="map-tile" type="class" propertytype="map-tile"> <properties> <property name="movement-cost" type="float" value="-1"/> </properties> </property> </properties> </tile> <tile id="7"> <properties> <property name="map-tile" type="class" propertytype="map-tile"> <properties> <property name="movement-cost" type="float" value="-1"/> </properties> </property> </properties> </tile> <tile id="8"> <properties> <property name="map-tile" type="class" propertytype="map-tile"> <properties> <property name="movement-cost" type="float" value="-1"/> </properties> </property> </properties> </tile> <tile id="10"> <properties> <property name="map-tile" type="class" propertytype="map-tile"> <properties> <property name="movement-cost" type="float" value="-1"/> </properties> </property> </properties> </tile> <tile id="11"> <properties> <property name="map-tile" type="class" propertytype="map-tile"> <properties> <property name="movement-cost" type="float" value="-1"/> </properties> </property> </properties> </tile> <tile id="12"> <properties> <property name="map-tile" type="class" propertytype="map-tile"> <properties> <property name="movement-cost" type="float" value="-1"/> </properties> </property> </properties> </tile> <tile id="13"> <properties> <property name="map-tile" type="class" propertytype="map-tile"> <properties> <property name="movement-cost" type="float" value="-1"/> </properties> </property> </properties> </tile> <tile id="15"> <properties> <property name="map-tile" type="class" propertytype="map-tile"> <properties> <property name="movement-cost" type="float" value="-1"/> </properties> </property> </properties> </tile> <tile id="16"> <properties> <property name="map-tile" type="class" propertytype="map-tile"> <properties> <property name="movement-cost" type="float" value="-1"/> </properties> </property> </properties> </tile> <tile id="17"> <properties> <property name="map-tile" type="class" propertytype="map-tile"> <properties> <property name="movement-cost" type="float" value="-1"/> </properties> </property> </properties> </tile> <tile id="18"> <properties> <property name="map-tile" type="class" propertytype="map-tile"> <properties> <property name="movement-cost" type="float" value="-1"/> </properties> </property> </properties> </tile> <tile id="20"> <properties> <property name="map-tile" type="class" propertytype="map-tile"> <properties> <property name="movement-cost" type="float" value="-1"/> </properties> </property> </properties> </tile> <tile id="21"> <properties> <property name="map-tile" type="class" propertytype="map-tile"> <properties> <property name="movement-cost" type="float" value="-1"/> </properties> </property> </properties> </tile> <tile id="22"> <properties> <property name="map-tile" type="class" propertytype="map-tile"> <properties> <property name="movement-cost" type="float" value="-1"/> </properties> </property> </properties> </tile> <tile id="23"> <properties> <property name="map-tile" type="class" propertytype="map-tile"> <properties> <property name="movement-cost" type="float" value="-1"/> </properties> </property> </properties> </tile> <tile id="25"> <properties> <property name="map-tile" type="class" propertytype="map-tile"> <properties> <property name="movement-cost" type="float" value="-1"/> </properties> </property> </properties> </tile> <tile id="26"> <properties> <property name="map-tile" type="class" propertytype="map-tile"> <properties> <property name="movement-cost" type="float" value="-1"/> </properties> </property> </properties> </tile> <tile id="27"> <properties> <property name="map-tile" type="class" propertytype="map-tile"> <properties> <property name="movement-cost" type="float" value="-1"/> </properties> </property> </properties> </tile> <tile id="28"> <properties> <property name="map-tile" type="class" propertytype="map-tile"> <properties> <property name="movement-cost" type="float" value="-1"/> </properties> </property> </properties> </tile> <tile id="30"> <properties> <property name="map-tile" type="class" propertytype="map-tile"> <properties> <property name="movement-cost" type="float" value="-1"/> </properties> </property> </properties> </tile> <tile id="31"> <properties> <property name="map-tile" type="class" propertytype="map-tile"> <properties> <property name="movement-cost" type="float" value="-1"/> </properties> </property> </properties> </tile> <tile id="32"> <properties> <property name="map-tile" type="class" propertytype="map-tile"> <properties> <property name="movement-cost" type="float" value="-1"/> </properties> </property> </properties> </tile> <tile id="33"> <properties> <property name="map-tile" type="class" propertytype="map-tile"> <properties> <property name="movement-cost" type="float" value="-1"/> </properties> </property> </properties> </tile> <tile id="35"> <properties> <property name="map-tile" type="class" propertytype="map-tile"> <properties> <property name="movement-cost" type="float" value="-1"/> </properties> </property> </properties> </tile> <tile id="36"> <properties> <property name="map-tile" type="class" propertytype="map-tile"> <properties> <property name="movement-cost" type="float" value="-1"/> </properties> </property> </properties> </tile> <tile id="37"> <properties> <property name="map-tile" type="class" propertytype="map-tile"> <properties> <property name="movement-cost" type="float" value="-1"/> </properties> </property> </properties> </tile> <tile id="38"> <properties> <property name="map-tile" type="class" propertytype="map-tile"> <properties> <property name="movement-cost" type="float" value="-1"/> </properties> </property> </properties> </tile> <tile id="39"> <properties> <property name="map-tile" type="class" propertytype="map-tile"> <properties> <property name="castle" type="bool" value="true"/> </properties> </property> </properties> </tile> </tileset>
7,982
Common Lisp
.l
301
22.774086
122
0.647442
lockie/spring-lisp-jam-2024
2
0
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
ba8cd62e7c901747b93a77e7dd20b6376146cf29de78f55688a665bd4879f32f
20,604
[ -1 ]
20,605
castle.tsx
lockie_spring-lisp-jam-2024/Resources/castle.tsx
<?xml version="1.0" encoding="UTF-8"?> <tileset version="1.8" tiledversion="1.8.6" name="castle" tilewidth="64" tileheight="64" tilecount="20" columns="5"> <image source="images/castle_blue.png" width="320" height="256"/> <tile id="0"> <properties> <property name="map-tile" type="class" propertytype="map-tile"> <properties> <property name="movement-cost" type="float" value="2"/> </properties> </property> </properties> </tile> <tile id="1"> <properties> <property name="map-tile" type="class" propertytype="map-tile"> <properties> <property name="movement-cost" type="float" value="2"/> </properties> </property> </properties> </tile> <tile id="2"> <properties> <property name="map-tile" type="class" propertytype="map-tile"> <properties> <property name="movement-cost" type="float" value="2"/> </properties> </property> </properties> </tile> <tile id="3"> <properties> <property name="map-tile" type="class" propertytype="map-tile"> <properties> <property name="movement-cost" type="float" value="2"/> </properties> </property> </properties> </tile> <tile id="4"> <properties> <property name="map-tile" type="class" propertytype="map-tile"> <properties> <property name="movement-cost" type="float" value="2"/> </properties> </property> </properties> </tile> <tile id="5"> <properties> <property name="map-tile" type="class" propertytype="map-tile"> <properties> <property name="movement-cost" type="float" value="2"/> </properties> </property> </properties> </tile> <tile id="9"> <properties> <property name="map-tile" type="class" propertytype="map-tile"> <properties> <property name="movement-cost" type="float" value="2"/> </properties> </property> </properties> </tile> <tile id="10"> <properties> <property name="map-tile" type="class" propertytype="map-tile"> <properties> <property name="movement-cost" type="float" value="2"/> </properties> </property> </properties> </tile> <tile id="11"> <properties> <property name="map-tile" type="class" propertytype="map-tile"> <properties> <property name="movement-cost" type="float" value="2"/> </properties> </property> </properties> </tile> <tile id="12"> <properties> <property name="map-tile" type="class" propertytype="map-tile"> <properties> <property name="movement-cost" type="float" value="2"/> </properties> </property> </properties> </tile> <tile id="13"> <properties> <property name="map-tile" type="class" propertytype="map-tile"> <properties> <property name="movement-cost" type="float" value="2"/> </properties> </property> </properties> </tile> <tile id="14"> <properties> <property name="map-tile" type="class" propertytype="map-tile"> <properties> <property name="movement-cost" type="float" value="2"/> </properties> </property> </properties> </tile> <tile id="15"> <properties> <property name="map-tile" type="class" propertytype="map-tile"> <properties> <property name="castle" type="bool" value="false"/> <property name="movement-cost" type="float" value="0"/> </properties> </property> </properties> </tile> <tile id="16"> <properties> <property name="map-tile" type="class" propertytype="map-tile"> <properties> <property name="castle" type="bool" value="false"/> <property name="movement-cost" type="float" value="0"/> </properties> </property> </properties> </tile> <tile id="17"> <properties> <property name="map-tile" type="class" propertytype="map-tile"> <properties> <property name="castle" type="bool" value="true"/> <property name="movement-cost" type="float" value="0"/> </properties> </property> </properties> </tile> <tile id="18"> <properties> <property name="map-tile" type="class" propertytype="map-tile"> <properties> <property name="castle" type="bool" value="false"/> <property name="movement-cost" type="float" value="0"/> </properties> </property> </properties> </tile> <tile id="19"> <properties> <property name="map-tile" type="class" propertytype="map-tile"> <properties> <property name="castle" type="bool" value="false"/> <property name="movement-cost" type="float" value="0"/> </properties> </property> </properties> </tile> </tileset>
4,489
Common Lisp
.l
162
23.925926
116
0.650566
lockie/spring-lisp-jam-2024
2
0
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
c3d2828af92247c40cf6979c351d167ef2ec65a2f546b95d0dca88f97626f691
20,605
[ -1 ]
20,606
ground-elevation.tsx
lockie_spring-lisp-jam-2024/Resources/ground-elevation.tsx
<?xml version="1.0" encoding="UTF-8"?> <tileset version="1.8" tiledversion="1.8.6" name="ground-elevation" tilewidth="64" tileheight="64" tilecount="32" columns="4"> <image source="images/tilemap_elevation.png" width="256" height="512"/> </tileset>
250
Common Lisp
.l
4
61.25
126
0.715447
lockie/spring-lisp-jam-2024
2
0
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
46d8cdd964590e4d356cfb4419795df6ae98890209ab3cc410f5a64be26cee3f
20,606
[ -1 ]
20,607
barrel.tsx
lockie_spring-lisp-jam-2024/Resources/barrel.tsx
<?xml version="1.0" encoding="UTF-8"?> <tileset version="1.8" tiledversion="1.8.6" name="barrel" tilewidth="64" tileheight="64" margin="32" tilecount="121" columns="11"> <image source="images/barrel_red.png" width="768" height="768"/> </tileset>
247
Common Lisp
.l
4
60.5
130
0.699588
lockie/spring-lisp-jam-2024
2
0
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
5386ff2e63306679d084ae54ffc11715da936211fe4146450ccb8d2a5d04d4ac
20,607
[ -1 ]
20,608
Info.plist
lockie_spring-lisp-jam-2024/package/Info.plist
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>CFBundlePackageType</key> <string>APPL</string> <key>CFBundleDisplayName</key> <string>Cycle of Evil</string> <key>CFBundleVersion</key> <string>0.0.1</string> <key>CFBundleExecutable</key> <string>cycle-of-evil</string> <key>CFBundleIconFile</key> <string>icon.png</string> <key>NSHumanReadableCopyright</key> <string>Copyright © 2024 Andrew Kravchuk</string> <key>NSHighResolutionCapable</key> <true/> </dict> </plist>
658
Common Lisp
.l
20
28.9
102
0.68652
lockie/spring-lisp-jam-2024
2
0
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
01478adb86ec8de948137f4493e28d4ce820e387105be6b056de6792fadff543
20,608
[ -1 ]
20,609
installer.nsi
lockie_spring-lisp-jam-2024/package/installer.nsi
!include MUI2.nsh !system 'convert icon.png -define icon:auto-resize=16,32,48,64,256 %TEMP%/icon.ico' !system 'convert -resize 150x57 -extent 150x57 -gravity center -background white -alpha remove -alpha off icon.png BMP2:%TEMP%/icon.bmp' !define MUI_PRODUCT "Cycle of Evil" !define MUI_FILE "cycle-of-evil" !define MUI_VERSION $%VERSION% !define MUI_ABORTWARNING !define MUI_ICON "$%TEMP%\icon.ico" !define MUI_HEADERIMAGE !define MUI_HEADERIMAGE_BITMAP "$%TEMP%\icon.bmp" !define MUI_HEADERIMAGE_RIGHT !define MUI_HEADERIMAGE_UNBITMAP "$%TEMP%\icon.bmp" Name "Cycle of Evil" OutFile "../cycle-of-evil-${MUI_VERSION}-setup.exe" ;Default installation folder InstallDir "$LOCALAPPDATA\Programs\${MUI_PRODUCT}" ;Get installation folder from registry if available InstallDirRegKey HKCU "Software\${MUI_PRODUCT}" "" ;Do not request application privileges for Windows Vista+ RequestExecutionLevel user ;Check CRC CRCCheck On ;Best compression SetCompressor /FINAL /SOLID lzma ;Pages !insertmacro MUI_PAGE_WELCOME !insertmacro MUI_PAGE_LICENSE ../LICENSE !insertmacro MUI_PAGE_DIRECTORY !insertmacro MUI_PAGE_INSTFILES !insertmacro MUI_PAGE_FINISH !insertmacro MUI_UNPAGE_CONFIRM !insertmacro MUI_UNPAGE_INSTFILES !insertmacro MUI_UNPAGE_FINISH !insertmacro MUI_LANGUAGE "English" ;Installer section Section "" SetOutPath "$INSTDIR" ;Files File /r "..\bin" File /r "..\Resources" File "${MUI_ICON}" SetOutPath "$INSTDIR\bin" ;Create desktop shortcut CreateShortCut "$DESKTOP\${MUI_PRODUCT}.lnk" "$INSTDIR\bin\${MUI_FILE}.exe" "" "$INSTDIR\icon.ico" 0 ;Create start menu items CreateDirectory "$SMPROGRAMS\${MUI_PRODUCT}" CreateShortCut "$SMPROGRAMS\${MUI_PRODUCT}\Uninstall.lnk" "$INSTDIR\Uninstall.exe" "" "$INSTDIR\Uninstall.exe" 0 CreateShortCut "$SMPROGRAMS\${MUI_PRODUCT}\${MUI_PRODUCT}.lnk" "$INSTDIR\bin\${MUI_FILE}.exe" "" "$INSTDIR\icon.ico" 0 ;Store installation folder WriteRegStr HKCU "Software\${MUI_PRODUCT}" "" $INSTDIR ;Create uninstaller WriteUninstaller "$INSTDIR\Uninstall.exe" SectionEnd ;Uninstaller section Section "Uninstall" ;Delete Files RMDir /r "$INSTDIR\*.*" Delete "$INSTDIR\Uninstall.exe" ;Remove the installation directory RMDir "$INSTDIR" ;Delete Shortcuts Delete "$DESKTOP\${MUI_PRODUCT}.lnk" Delete "$SMPROGRAMS\${MUI_PRODUCT}\*.*" RMDir "$SMPROGRAMS\${MUI_PRODUCT}" DeleteRegKey /ifempty HKCU "Software\${MUI_PRODUCT}" SectionEnd
2,488
Common Lisp
.l
66
34.757576
136
0.753545
lockie/spring-lisp-jam-2024
2
0
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
7f58b4c42a63b46088355f54a3ae3170b65fdd59b38d96582c8612916c81021d
20,609
[ -1 ]
20,626
100_doors.lisp
mzgcz_cl_exercises/100_doors.lisp
;; http://rosettacode.org/wiki/100_doors ;;; 每次访问时,变更门的状态 (defun switch-door (door) (not door)) ;;; 第no次访问时,访问no的倍数号门 (defun access-door (no N doors) (let ((copy-doors (copy-list doors))) (loop for i from no upto N by no do (setf (nth (1- i) copy-doors) (switch-door (nth (1- i) copy-doors)))) copy-doors)) ;;; 启动 (defun start-doors-game (&optional (N 100)) ;;; N扇门,初始状态为关闭 (let ((doors (make-list N :initial-element nil)) (no-list (loop for i from 1 upto 100 collect i))) ;;; 访问N次 (mapcar (lambda (no) (setf doors (access-door no N doors))) no-list) doors)) (print (start-doors-game))
739
Common Lisp
.lisp
21
26.904762
79
0.619874
mzgcz/cl_exercises
2
0
0
LGPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
e408bd18760e7e044c26353fae05b011d733e82a5c989369721ffceeb00c9669
20,626
[ -1 ]
20,627
ABC.lisp
mzgcz_cl_exercises/ABC.lisp
;;; http://rosettacode.org/wiki/ABC_Problem ;; 给定由双元素组成的单词表 ;; 单词表中每个元素仅能使用一次 ;; 判断给定单词能否由单词表组成 ;;; 单词表 (defparameter *word-list* '((B O) (X K) (D Q) (C P) (N A) (G T) (R E) (T G) (Q D) (F S) (J W) (H U) (V I) (A N) (O B) (E R) (F S) (L Y) (P C) (Z M))) ;;; 列表删除某个元素 (defun list-cell (list cell) (let ((flag 0) new-list) (dolist (var list (reverse new-list)) (if (and (= flag 0) (equal var cell)) (incf flag) (push var new-list))))) ;;; 判断给定单词是否能由单词表组成 (defun can-make-word (word word-list) (if (> (length word) 0) ;; 判断首字母能否由word-list组成 ;; 若能,判断剩余字母能否由剩余word-list组成 ;; 若否,则返回nil (dolist (rest-word-list (can-make-letter (char-upcase (aref word 0)) word-list) nil) (if (can-make-word (subseq word 1) rest-word-list) (return t))) t)) ;;; 判断给定字母是否能由单词表组成 (defun can-make-letter (letter word-list) (let (rest-word-list) (dolist (word word-list) (if (member letter (mapcar #'character word)) (push (list-cell word-list word) rest-word-list))) rest-word-list))
1,389
Common Lisp
.lisp
34
27.117647
90
0.552491
mzgcz/cl_exercises
2
0
0
LGPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
011f1ae9da919359e2b6bfb768cf9d702a8bcc4749cc2e9368c9e82f9a6aa7d9
20,627
[ -1 ]
20,628
add_slot.lisp
mzgcz_cl_exercises/add_slot.lisp
;;; http://rosettacode.org/wiki/Add_a_variable_to_a_class_instance_at_runtime ;; add a variable to a class instance at runtime (defclass person () (name)) (defvar *I* (make-instance 'person)) (setf (slot-value *I* 'name) "jwj") (defclass person () (name sex)) (setf (slot-value *I* 'sex) "male") (defclass person () (name sex age)) (setf (slot-value *I* 'age) 30) (format t "Name:~S Sex:~S Age:~S" (slot-value *I* 'name) (slot-value *I* 'sex) (slot-value *I* 'age))
499
Common Lisp
.lisp
13
34.846154
77
0.639413
mzgcz/cl_exercises
2
0
0
LGPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
b33962a5b6071661b14875bfe9b0599caf34c8289622f327db57aecfe2e79271
20,628
[ -1 ]
20,629
AKS.lisp
mzgcz_cl_exercises/AKS.lisp
;;; http://rosettacode.org/wiki/AKS_test_for_primes ;; 任务: ;; 1. 创建生成 (x-1)^p的参数列表的函数 ;; 2. 展示 (x-1)^p的参数列表,p从0到7 ;; 3. 创建使用上述参数列表判断p是否为素数的函数 ;; 4. 测试一系列35以下的素数 ;; 5. 生成50以下的所有素数 ;;; 排列计数 (defun Permutation (n) (if (zerop n) 1 (* n (Permutation (1- n))))) ;;; 组合计数 (defun Combination (n m) (/ (Permutation n) (* (Permutation (- n m)) (Permutation m)))) ;;; 二项式系数列表 (defun Binomial (n &optional (constant 1)) (loop for m from 0 to n collect (* (Combination n m) (expt constant m)))) ;;; p从1-7的参数列表 (loop for i from 0 to 7 collect (Binomial i -1)) ;;; 判断是否能整除 (defun divide? (n m) (let ((remainder (cadr (multiple-value-list (floor n m))))) (if (zerop remainder) t nil))) ;;; 素数判断 (defun Primes? (n) (let* ((binomial-list (Binomial n -1)) (sub-list (loop for i from 0 to n collect (cond ((= i 0) 1) ((= i n) -1) (t 0)))) (judge-list (mapcar #'- binomial-list sub-list))) (dolist (no judge-list) (when (not (divide? no n)) (return-from Primes? nil)))) t) (mapcar #'Primes? '(2 3 5 7 11 13 17 19 23 29 31)) (loop for i from 2 to 50 collect (if (Primes? i) i))
1,421
Common Lisp
.lisp
40
25.4
75
0.563559
mzgcz/cl_exercises
2
0
0
LGPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
20fbec8f92001567c87cfe1b9fb96c686e70142866bca32902f1f0374afb8c6e
20,629
[ -1 ]
20,630
A+B.lisp
mzgcz_cl_exercises/A+B.lisp
;;; http://rosettacode.org/wiki/A%2BB (defun A+B () (format t "Please Input Two Numbers: ") (let ((A (read)) (B (read))) (format t "~S + ~S = ~S~%" A B (+ A B))))
180
Common Lisp
.lisp
6
26.166667
45
0.508671
mzgcz/cl_exercises
2
0
0
LGPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
082a5293a63f750dee378370c5b790c9113b294dca86daef44a4d098c854f80d
20,630
[ -1 ]
20,631
24_game.lisp
mzgcz_cl_exercises/24_game.lisp
;; http://rosettacode.org/wiki/24_game ;;; 24算术游戏,给4个随机数(1 ... 9),利用加、减、乘、除以及括号,使最终结果为24 ;;; 选取N个1~9的随机数 (defun get-nums (num) (let (num-list) (dotimes (no num num-list) (push (1+ (random 9)) num-list)))) ;;; 读取用户输入 (defun read-input () (format t "~&Please Input Your Slove: ") (read *standard-input* nil nil)) ;;; 执行用户输入,判定是否为24 (defun judge-24 () (if (= 24 (eval (read-input))) t nil)) ;;; 启动 (defun start-24-game () ;; 生成四个1~9的随机数 (format t "Task: Use Four Number ~S To Get 24" (get-nums 4)) (if (judge-24) (format t "Well Done!") (format t "Sorry, Try Again!"))) (start-24-game)
775
Common Lisp
.lisp
24
23.291667
62
0.61285
mzgcz/cl_exercises
2
0
0
LGPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
26761bc299e2f40f04a63d4f5b07042586c60e648bad9ea032552931a0cceefc
20,631
[ -1 ]
20,632
abstract_type.lisp
mzgcz_cl_exercises/abstract_type.lisp
;; http://rosettacode.org/wiki/Abstract_type ;;; 抽象类型 (defclass people () (sex age)) (defclass teacher (people) (subject)) (defclass student (people) (id)) (let ((teacher-1 (make-instance 'teacher)) (student-1 (make-instance 'student))) (print (type-of teacher-1)) (print (type-of student-1)) (print (typep teacher-1 'people)) (print (typep student-1 'people)))
389
Common Lisp
.lisp
11
31.909091
44
0.690411
mzgcz/cl_exercises
2
0
0
LGPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
3c20413079771ce970f357dbf12e8da9d32c44c8f7f37cf851491b1c2cdb892a
20,632
[ -1 ]
20,633
ackermann_function.lisp
mzgcz_cl_exercises/ackermann_function.lisp
;;; http://rosettacode.org/wiki/Ackermann_function ;; if m=0, A(m,n)=n+1 ;; if m>0 and n=0, A(m,n)=A(m-1,1) ;; if m>0 and n>0, A(m,n)=A(m-1,A(m,n-1)) (defun ackermann_function (m n) (cond ((= m 0) (1+ n)) ((= n 0) (ackermann_function (1- m) 1)) (t (ackermann_function (1- m) (ackermann_function m (1- n)))))) (print (ackermann_function 0 5)) (print (ackermann_function 0 6)) (print (ackermann_function 1 4)) (print (ackermann_function 1 5)) (print (ackermann_function 2 3)) (print (ackermann_function 2 4)) (print (ackermann_function 3 2)) (print (ackermann_function 3 3)) (print (ackermann_function 3 4))
627
Common Lisp
.lisp
17
34.647059
71
0.647446
mzgcz/cl_exercises
2
0
0
LGPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
9b16b54bebee30799c903339c19901df2b895a75498a109ffbd59a9897d8be26
20,633
[ -1 ]
20,634
accumulator_factory.lisp
mzgcz_cl_exercises/accumulator_factory.lisp
;;; http://rosettacode.org/wiki/Accumulator_factory ;; 累加器 ;; x = foo(1); ;; x(5); ;; foo(3); ;; print x(2.3); ;; it's 8.3 (defun accumulator_factory (sum) (lambda (plus) (incf sum plus))) (defvar x (accumulator_factory 1)) (funcall x 5) (accumulator_factory 3) (print (funcall x 2.3))
304
Common Lisp
.lisp
14
19.428571
51
0.658273
mzgcz/cl_exercises
2
0
0
LGPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
c7f6a6632d1ecd57fdc224fd82e8fe249cb309ed90d34219a7155d210e6fe86e
20,634
[ -1 ]
20,635
99_bottles.lisp
mzgcz_cl_exercises/99_bottles.lisp
;;; http://rosettacode.org/wiki/99_Bottles_of_Beer ;; X bottles of beer on the wall ;; X bottles of beer ;; Take one down, pass it around ;; X-1 bottles of beer on the wall ;; X-1 bottles of beer on the wall ;; ... ;; Take one down, pass it around ;; 0 bottles of beer on the wall ;;; 生成n~0的列表,表示N+1个轮回 (defun get-bottles-list (&optional (n 99)) (loop for no from n downto 1 collect no)) ;;; 按列表信息打印诗歌 (defun print-song (l) (mapcar (lambda (x) (format t "~S bottle~P of beer on the wall~%" x x) (format t "~S bottle~P of beer~%" x x) (format t "Take one down, pass it around~%") (format t "~S bottle~P of beer on the wall~%" (1- x) (1- x)) (if (/= 1 x) (format t "~%"))) l)) ;;; 游戏开始 (defun game-start () (print-song (get-bottles-list)) 'done)
875
Common Lisp
.lisp
25
28.76
72
0.599749
mzgcz/cl_exercises
2
0
0
LGPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
5b94e2b1bc7773f8ef85b328b1c4204fc5eb262de8a6b01a3faae014e44787d1
20,635
[ -1 ]
20,636
24_game_slove.lisp
mzgcz_cl_exercises/24_game_slove/24_game_slove.lisp
;;;; 24_game_slove.lisp ;;; http://rosettacode.org/wiki/24_game/Solve (in-package #:24_game_slove) ;;; "24_game_slove" goes here. Hacks and glory await! ;;; 列表删除某个元素 (defun list-cell (list cell) (let ((flag 0) new-list) (dolist (var list (reverse new-list)) (if (and (= flag 0) (equal var cell)) (incf flag) (push var new-list))))) ;;; 获取n个1~9的数字 (defun get-n-num (n) (loop for i from 1 to n collect (1+ (random 9)))) ;;; 生成列表的全排列 (defun get-num-list (num-list) (if (= 1 (length num-list)) (list num-list) (alexandria:mappend (lambda (num) (let ((rest-list (get-num-list (list-cell num-list num)))) (mapcar (lambda (rest-1) (cons num rest-1)) rest-list))) num-list))) ;;; 获取所有操作的排列组合 (defun get-op-list (n) (let ((ops '(+ - * /))) (if (= n 1) (mapcar #'list ops) (alexandria:mappend (lambda (op-1) (mapcar (lambda (op-2) (cons op-2 op-1)) ops)) (get-op-list (1- n)))))) ;;; 由运算符列表和数字列表,确定组合式 (defun get-equation (op-list num-list) (let ((op-1 (car op-list)) (num-1 (car num-list))) (if (= 1 (length op-list)) (list (cons op-1 num-list) (cons op-1 (reverse num-list))) (alexandria:mappend (lambda (equation-1) (list (list op-1 num-1 equation-1) (list op-1 equation-1 num-1))) (get-equation (cdr op-list) (cdr num-list)))))) ;;; 执行算术表达式 ;;; 若存在除0错误,则返回最大fixnum (defun eval-equation (equation) (handler-case (eval equation) (division-by-zero () most-positive-fixnum))) ;;; game start (defun game-start () (let ((4-num-list (get-n-num 4))) ;获取4个1~9的随机数 (format t "Task: Use Four Number ~S To Get 24" 4-num-list) (mapcar (lambda (op-list) (mapcar (lambda (num-list) (mapcar (lambda (equation-1) (when (= 24 (eval-equation equation-1)) (format t "~&There Is A Slove: ~S" equation-1) (return-from game-start))) (get-equation op-list num-list))) ;生成算符和数字的所有组合 (get-num-list 4-num-list))) ;生成数字列表 (get-op-list 3))) ;生成算符列表 (format t "~&There Is No Slove"))
2,815
Common Lisp
.lisp
65
27.646154
86
0.478535
mzgcz/cl_exercises
2
0
0
LGPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
d42245fb7532d70209daa39fcc4d83bb0cd3f6a0e255b6951fac66ce4ce651bb
20,636
[ -1 ]
20,637
24_game_slove.asd
mzgcz_cl_exercises/24_game_slove/24_game_slove.asd
;;;; 24_game_slove.asd (asdf:defsystem #:24_game_slove :serial t :description "24 Game Slove" :author "mzgcz <[email protected]>" :license "LGPL v3" :depends-on (#:alexandria) :components ((:file "package") (:file "24_game_slove")))
264
Common Lisp
.asd
9
25.111111
40
0.640316
mzgcz/cl_exercises
2
0
0
LGPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
de1f847b9817d599774bedb97fa3db4fb355a9347ce090f9a2cac139e2fea444
20,637
[ -1 ]
20,665
package.lisp
farzadbekran_cl-mud/package.lisp
;;;; package.lisp (defpackage #:cl-mud (:use #:cl #:usocket #:gtk #:gdk #:gdk-pixbuf #:gobject #:glib #:gio #:pango #:cairo #:chanl))
139
Common Lisp
.lisp
5
25.8
57
0.616541
farzadbekran/cl-mud
2
0
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
ca7fb88f4b4b2f61c4ad9c5596009135c1cb5e6a1ff98fadb9639f464352d3b9
20,665
[ -1 ]
20,666
cl-mud.lisp
farzadbekran_cl-mud/cl-mud.lisp
;;;; cl-mud.lisp (in-package #:cl-mud) (defvar host "bat.org") (defvar port 23) (defvar io) (defvar io-stream) (defconstant gdk-return-code #xff0d) (defstruct app main-window main-output main-input) (defvar main-app (make-app)) (defvar reader-thread nil) (defvar telnet-thread nil) (defvar telnet-channel (make-instance 'bounded-channel :size 1024)) ;;receives bytes (defvar ansi-thread nil) (defvar ansi-channel (make-instance 'bounded-channel :size 1024)) ;;receives chars (defvar line-splitter-thread nil) (defvar line-splitter-channel (make-instance 'bounded-channel :size 1024)) ;;receives lists or chars (defvar printer-thread nil) (defvar printer-channel (make-instance 'bounded-channel :size 1024)) ;;receives lists or strings (defun scroll-to-end (text-view) (let* ((buffer (gtk-text-view-buffer text-view)) (insert-mark (gtk-text-buffer-get-insert buffer))) (gtk-text-buffer-place-cursor buffer (gtk-text-buffer-get-end-iter buffer)) (gtk-text-view-scroll-to-mark text-view insert-mark))) (defun parse-byte (b) ;;(format t "~c" (code-char b)) ;;(force-output) (when (not (eql b (char-code #\newline))) (gdk:gdk-threads-enter) (gtk-text-buffer-insert (gtk-text-view-buffer (app-main-output main-app)) (string (code-char b))) (scroll-to-end (app-main-output main-app)) (gdk:gdk-threads-leave))) (defvar telnet-commands '(:IAC 255 ;;interpret as command :GA 249 ;;go ahead )) (defun start-telnet-thread () "Receives bytes from network. Parses telnet related parts before passing data to ansi channel." (if (and telnet-thread (task-thread telnet-thread)) (kill (task-thread telnet-thread))) (setf telnet-thread (pexec () (start-ansi-thread) (loop for b = (recv telnet-channel) do (cond ((eq b (getf telnet-commands :IAC)) (print "telnet: IAC") (cond ((eql (recv telnet-channel) (getf telnet-commands :GA)) (send ansi-channel #\newline)))) (t (send ansi-channel (code-char b)))))))) (defun receive-ansi-colors () (let (result part) (loop for c = (recv ansi-channel) while (not (eql c #\m)) do (if (eql c #\;) (progn (push (concatenate 'string (reverse part)) result) (setf part nil)) (progn (push c part)))) (push (concatenate 'string (reverse part)) result) (list :type :ansi-style :data (reverse result)))) (defun start-printer-thread () (if (and printer-thread (task-thread printer-thread)) (kill (task-thread printer-thread))) (setf printer-thread (pexec () (let (last-tags) (loop for line = (recv printer-channel) do (let ((buffer (gtk-text-view-buffer (app-main-output main-app)))) (print line) (gdk:gdk-threads-enter) (mapcar (lambda (item) (cond ((stringp item) (gtk-text-buffer-insert (gtk-text-view-buffer (app-main-output main-app)) item) (let* ((end (gtk-text-buffer-get-end-iter buffer)) (start (gtk-text-buffer-get-iter-at-offset buffer (- (length (gtk-text-buffer-text buffer)) (length item))))) (mapcar (lambda (tag-name) (if (stringp tag-name) (gtk-text-buffer-apply-tag-by-name buffer tag-name start end))) (getf last-tags :data)))) ((and (listp item) (eql (getf item :type) :ansi-style)) (setf last-tags item)))) line) (gtk-text-buffer-insert buffer (string #\newline)) (scroll-to-end (app-main-output main-app)) (gdk:gdk-threads-leave))))))) (defun start-line-splitter-thread () (if (and line-splitter-thread (task-thread line-splitter-thread)) (kill (task-thread line-splitter-thread))) (setf line-splitter-thread (pexec () (start-printer-thread) (let (line chars) (loop for c = (recv line-splitter-channel) for type = (type-of c) do (cond ((eql type 'standard-char) (cond ((eql c #\newline) (push (reverse (concatenate 'string chars)) line) (send printer-channel (reverse line)) (setf line nil) (setf chars nil)) (t (push c chars)))) ((eql type 'cons) (push (reverse (concatenate 'string chars)) line) (push c line) (setf chars nil)))))))) (defun start-ansi-thread () (if (and ansi-thread (task-thread ansi-thread)) (kill (task-thread ansi-thread))) (setf ansi-thread (pexec () (start-line-splitter-thread) (loop for c = (recv ansi-channel) do (if (eql c #\esc) (if (eql (recv ansi-channel) #\[) (send line-splitter-channel (receive-ansi-colors))) (send line-splitter-channel c)))))) (defun start-reader-loop () (if (and reader-thread (task-thread reader-thread)) (kill (task-thread reader-thread))) (setf reader-thread (pexec () (start-telnet-thread) (loop while t do (send telnet-channel (read-byte io-stream)))))) (defun setup-text-view-tags (text-view) (let ((tags (list (make-instance 'gtk-text-tag :name "0" :weight 100) (make-instance 'gtk-text-tag :name "1" :weight 800) (make-instance 'gtk-text-tag :name "30" :foreground "black") (make-instance 'gtk-text-tag :name "31" :foreground "red") (make-instance 'gtk-text-tag :name "32" :foreground "green") (make-instance 'gtk-text-tag :name "33" :foreground "yellow") (make-instance 'gtk-text-tag :name "34" :foreground "blue") (make-instance 'gtk-text-tag :name "35" :foreground "magenta") (make-instance 'gtk-text-tag :name "36" :foreground "cyan") (make-instance 'gtk-text-tag :name "37" :foreground "white") (make-instance 'gtk-text-tag :name "40" :background "black") (make-instance 'gtk-text-tag :name "41" :background "red") (make-instance 'gtk-text-tag :name "42" :background "green") (make-instance 'gtk-text-tag :name "43" :background "yellow") (make-instance 'gtk-text-tag :name "44" :background "blue") (make-instance 'gtk-text-tag :name "45" :background "magenta") (make-instance 'gtk-text-tag :name "46" :background "cyan") (make-instance 'gtk-text-tag :name "47" :background "white"))) (tag-table (gtk-text-buffer-get-tag-table (gtk-text-view-get-buffer text-view)))) (mapcar (lambda (tag) (gtk-text-tag-table-add tag-table tag)) tags))) (defun make-main-window () (connect host port) (format t "connected!~%") (start-reader-loop) (within-main-loop (let ((builder (make-instance 'gtk-builder))) (gtk-builder-add-from-file builder "main.glade") (loop for slot in (closer-mop:class-slots (class-of main-app)) for slot-name = (closer-mop:slot-definition-name slot) for name = (string-downcase (symbol-name slot-name)) for widget = (gtk-builder-get-object builder name) when widget do (setf (slot-value main-app slot-name) widget)) (setup-text-view-tags (app-main-output main-app)) (let ((quit (lambda (object) (declare (ignore object)) (leave-gtk-main)))) (g-signal-connect (app-main-window main-app) "destroy" quit)) (g-signal-connect (app-main-input main-app) "key-press-event" (lambda (self event) (declare (ignore self)) (if (eql (gdk-event-key-keyval event) gdk-return-code) (progn (send-string (gtk-entry-buffer-text (gtk-entry-buffer (app-main-input main-app)))) (setf (gtk-entry-buffer-text (gtk-entry-buffer (app-main-input main-app))) ""))))) (gtk-widget-show-all (app-main-window main-app))))) (defun connect (host port) (setf io (socket-connect host port :element-type '(unsigned-byte 8))) (setf io-stream (socket-stream io))) (defun send-string (s) (mapcar (lambda (c) (write-byte (char-code c) io-stream)) (coerce s 'list)) (write-byte (char-code #\newline) io-stream) (write-byte (char-code #\return) io-stream) (force-output io-stream)) ;; (setf tag (make-instance 'gtk-text-tag :foreground "blue" :background "black")) ;; (gtk-text-tag-table-add (gtk-text-buffer-get-tag-table buffer) tag) ;; (gtk-text-buffer-apply-tag ;; buffer tag ;; (gtk-text-buffer-get-iter-at-offset buffer 0) ;; (gtk-text-buffer-get-iter-at-offset buffer 10)) (defun main () (make-main-window) (join-gtk-main))
8,190
Common Lisp
.lisp
215
33.413953
97
0.662013
farzadbekran/cl-mud
2
0
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
b9d565f2382d2a109f489791810dbe8e2b779926e4341f7f293009026aefced4
20,666
[ -1 ]
20,667
cl-mud.asd
farzadbekran_cl-mud/cl-mud.asd
;;;; cl-mud.asd (asdf:defsystem #:cl-mud :description "Describe cl-mud here" :author "Your Name <[email protected]>" :license "Specify license here" :serial t :depends-on (#:usocket #:cl-cffi-gtk #:chanl) :components ((:file "package") (:file "cl-mud")))
302
Common Lisp
.asd
9
27.777778
49
0.611684
farzadbekran/cl-mud
2
0
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
f7c7f33666c1985f07e5c38814248ecc9942c2083732b8e3446a4f65ba88eca8
20,667
[ -1 ]
20,671
main.glade
farzadbekran_cl-mud/main.glade
<?xml version="1.0" encoding="UTF-8"?> <!-- Generated with glade 3.20.0 --> <interface> <requires lib="gtk+" version="3.20"/> <object class="GtkApplicationWindow" id="main-window"> <property name="can_focus">False</property> <property name="default_width">800</property> <property name="default_height">600</property> <property name="show_menubar">False</property> <child> <object class="GtkBox"> <property name="visible">True</property> <property name="can_focus">False</property> <property name="orientation">vertical</property> <child> <object class="GtkMenuBar"> <property name="visible">True</property> <property name="can_focus">False</property> <child> <object class="GtkMenuItem"> <property name="visible">True</property> <property name="can_focus">False</property> <property name="label" translatable="yes">_File</property> <property name="use_underline">True</property> <child type="submenu"> <object class="GtkMenu"> <property name="visible">True</property> <property name="can_focus">False</property> <child> <object class="GtkImageMenuItem"> <property name="label">gtk-new</property> <property name="visible">True</property> <property name="can_focus">False</property> <property name="use_underline">True</property> <property name="use_stock">True</property> </object> </child> <child> <object class="GtkImageMenuItem"> <property name="label">gtk-open</property> <property name="visible">True</property> <property name="can_focus">False</property> <property name="use_underline">True</property> <property name="use_stock">True</property> </object> </child> <child> <object class="GtkImageMenuItem"> <property name="label">gtk-save</property> <property name="visible">True</property> <property name="can_focus">False</property> <property name="use_underline">True</property> <property name="use_stock">True</property> </object> </child> <child> <object class="GtkImageMenuItem"> <property name="label">gtk-save-as</property> <property name="visible">True</property> <property name="can_focus">False</property> <property name="use_underline">True</property> <property name="use_stock">True</property> </object> </child> <child> <object class="GtkSeparatorMenuItem"> <property name="visible">True</property> <property name="can_focus">False</property> </object> </child> <child> <object class="GtkImageMenuItem"> <property name="label">gtk-quit</property> <property name="visible">True</property> <property name="can_focus">False</property> <property name="use_underline">True</property> <property name="use_stock">True</property> </object> </child> </object> </child> </object> </child> <child> <object class="GtkMenuItem"> <property name="visible">True</property> <property name="can_focus">False</property> <property name="label" translatable="yes">_Edit</property> <property name="use_underline">True</property> <child type="submenu"> <object class="GtkMenu"> <property name="visible">True</property> <property name="can_focus">False</property> <child> <object class="GtkImageMenuItem"> <property name="label">gtk-cut</property> <property name="visible">True</property> <property name="can_focus">False</property> <property name="use_underline">True</property> <property name="use_stock">True</property> </object> </child> <child> <object class="GtkImageMenuItem"> <property name="label">gtk-copy</property> <property name="visible">True</property> <property name="can_focus">False</property> <property name="use_underline">True</property> <property name="use_stock">True</property> </object> </child> <child> <object class="GtkImageMenuItem"> <property name="label">gtk-paste</property> <property name="visible">True</property> <property name="can_focus">False</property> <property name="use_underline">True</property> <property name="use_stock">True</property> </object> </child> <child> <object class="GtkImageMenuItem"> <property name="label">gtk-delete</property> <property name="visible">True</property> <property name="can_focus">False</property> <property name="use_underline">True</property> <property name="use_stock">True</property> </object> </child> </object> </child> </object> </child> <child> <object class="GtkMenuItem"> <property name="visible">True</property> <property name="can_focus">False</property> <property name="label" translatable="yes">_View</property> <property name="use_underline">True</property> </object> </child> <child> <object class="GtkMenuItem"> <property name="visible">True</property> <property name="can_focus">False</property> <property name="label" translatable="yes">_Help</property> <property name="use_underline">True</property> <child type="submenu"> <object class="GtkMenu"> <property name="visible">True</property> <property name="can_focus">False</property> <child> <object class="GtkImageMenuItem"> <property name="label">gtk-about</property> <property name="visible">True</property> <property name="can_focus">False</property> <property name="use_underline">True</property> <property name="use_stock">True</property> </object> </child> </object> </child> </object> </child> </object> <packing> <property name="expand">False</property> <property name="fill">True</property> <property name="position">0</property> </packing> </child> <child> <object class="GtkScrolledWindow"> <property name="visible">True</property> <property name="can_focus">True</property> <property name="shadow_type">in</property> <child> <object class="GtkTextView" id="main-output"> <property name="visible">True</property> <property name="can_focus">True</property> <property name="editable">False</property> <property name="monospace">True</property> </object> </child> </object> <packing> <property name="expand">True</property> <property name="fill">True</property> <property name="position">1</property> </packing> </child> <child> <object class="GtkEntry" id="main-input"> <property name="visible">True</property> <property name="can_focus">True</property> <property name="has_focus">True</property> <property name="has_default">True</property> </object> <packing> <property name="expand">False</property> <property name="fill">True</property> <property name="position">2</property> </packing> </child> </object> </child> <child type="titlebar"> <placeholder/> </child> </object> </interface>
9,779
Common Lisp
.l
211
28.56872
74
0.479202
farzadbekran/cl-mud
2
0
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
a7b7d5d09e390e4c6df3fa827496bbbe93c0288b9da088d9a005575e532e7e7a
20,671
[ -1 ]
20,687
package.lisp
rheaplex_microblog-bot/package.lisp
;; packages.lisp - The package definition(s) for microblog-bot. ;; Copyright (C) 2009, 2010 Rob Myers [email protected] ;; ;; This program is free software: you can redistribute it and/or modify ;; it under the terms of the GNU Affero General Public License as ;; published by the Free Software Foundation, either version 3 of the ;; License, or (at your option) any later version. ;; ;; This program is distributed in the hope that it will be useful, ;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;; GNU Affero General Public License for more details. ;; ;; You should have received a copy of the GNU Affero General Public License ;; along with this program. If not, see <http://www.gnu.org/licenses/>. (defpackage microblog-bot (:documentation "Microblog bot creation support.") ;; We have to import usocket, drakma, and cl+ssl to handle their exceptions (:use #:common-lisp #:cl-twit #:usocket #:drakma #:cl+ssl) (:export set-microblog-service set-debug set-live report-error microblog-user user-nickname user-password with-microblog-user microblog-bot filter-replies queue-update response-for-mention response-for-source-request response-for-post response-p constant-task-bot constant-task intermittent-task-bot intermittent-task daily-task-bot daily-task microblog-follower-bot filter-posts run-bot-once run-bot test-run-bot-once test-run-bot))
1,558
Common Lisp
.lisp
47
29.574468
77
0.737542
rheaplex/microblog-bot
2
0
0
AGPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
f4f80fdddd6677e9dda95534fe78c35e988acd57e26a4545e04d5716c6b4e9b3
20,687
[ -1 ]
20,688
daily-task-bot.lisp
rheaplex_microblog-bot/daily-task-bot.lisp
;; daily-task-bot.lisp - A bot that does something once a day. ;; Copyright (C) 2009 Rob Myers [email protected] ;; ;; This program is free software: you can redistribute it and/or modify ;; it under the terms of the GNU Affero General Public License as ;; published by the Free Software Foundation, either version 3 of the ;; License, or (at your option) any later version. ;; ;; This program is distributed in the hope that it will be useful, ;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;; GNU Affero General Public License for more details. ;; ;; You should have received a copy of the GNU Affero General Public License ;; along with this program. If not, see <http://www.gnu.org/licenses/>. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Package ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (in-package :microblog-bot) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; A bot that does a task once a day ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defconstant %default-daily-task-hour 0 "The default hour of the day for the daily task") (defconstant %default-previous-day 0 "The default day on which the daily task last ran") (defclass daily-task-bot (microblog-bot) ((daily-task-hour :accessor daily-task-hour :initarg :daily-task-hour :initform %default-daily-task-hour) (previous-day :accessor previous-day :initarg :previous-day :initform %default-previous-day))) (defmethod initialize-instance :after ((bot daily-task-bot) &key) "Set up the bot's state" (setf (previous-day bot) (floor (get-universal-time) %one-day)) (debug-msg "Initialized bot previous-day ~a " bot (previous-day bot))) (defmethod daily-task ((bot daily-task-bot)) "Performed every day at the appointed hour" nil) (defmethod manage-daily-task ((bot daily-task-bot)) "If it's a new day and after the appointed hour, perform the task" (multiple-value-bind (days seconds) (floor (get-universal-time) %one-day) (when (and (> days (previous-day bot)) (> seconds (* (daily-task-hour bot) %one-hour))) (debug-msg "Running daily task for bot ~a" bot ) (handler-case (progn (daily-task bot) ;; Only update if successful. Is this OK? (setf (previous-day bot) days)) (error (err) (report-error "manage-daily-task ~a - ~a~%" bot err)))))) (defmethod manage-task :after ((bot daily-task-bot)) "Do the bot's task once." (manage-daily-task bot))
2,653
Common Lisp
.lisp
57
43.578947
80
0.6294
rheaplex/microblog-bot
2
0
0
AGPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
a967e26b409c7b3eefd900abffa842dbda2323c0d7f9a24e5cbc67f835a7bfbd
20,688
[ -1 ]
20,689
microblog-user.lisp
rheaplex_microblog-bot/microblog-user.lisp
;; microblog-user.lisp - A microblog service user. ;; Copyright (C) 2009 Rob Myers [email protected] ;; ;; This program is free software: you can redistribute it and/or modify ;; it under the terms of the GNU Affero General Public License as ;; published by the Free Software Foundation, either version 3 of the ;; License, or (at your option) any later version. ;; ;; This program is distributed in the hope that it will be useful, ;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;; GNU Affero General Public License for more details. ;; ;; You should have received a copy of the GNU Affero General Public License ;; along with this program. If not, see <http://www.gnu.org/licenses/>. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Package ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (in-package :microblog-bot) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; microblog-user ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defclass microblog-user () ((user-nickname :accessor user-nickname :initarg :nickname) (user-password :accessor user-password :initarg :password))) (defun user-id-for-screen-name (name) ;; This is ambiguous [why?]. ;; It would be better to use screen_name when supported (let ((user (or (cl-twit:m-user-show :id name) (error "Can't get user info in user-id-for-screen-name")))) (assert user) (or (cl-twit::id user) (error "Can't get user id in user-id-for-screen-name")))) (defmacro with-microblog-user (mb-user &body body) "Log in, execture the body, log out" (let ((result (gensym))) `(progn (cl-twit:with-session ((user-nickname ,mb-user) (user-password ,mb-user) :authenticatep t) (debug-msg "With user ~a" ,mb-user) (let ((,result (progn ,@body))) (debug-msg "Finished with user ~a" ,mb-user) ;; with-session doesn't currently do this, remove if it ever does. (cl-twit:logout) ,result))))) (defmethod from-config-plist ((user microblog-user) (alist list)) "Set the user's configuration from a plist" (setf (user-nickname user) (car (assoc :user-nickname alist))) (setf (user-password user) (car (assoc :user-password alist))))
2,388
Common Lisp
.lisp
52
42.942308
80
0.611517
rheaplex/microblog-bot
2
0
0
AGPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
d2f7606b2b740346bc74ed114aaf7b0989e997817e6a31567c55099d9dcede1a
20,689
[ -1 ]
20,690
microblog-bot.lisp
rheaplex_microblog-bot/microblog-bot.lisp
;; microblog-bot.lisp - Basic bot for microblogging (Twitter, Laconica). ;; Copyright (C) 2009, 2010 Rob Myers [email protected] ;; ;; This program is free software: you can redistribute it and/or modify ;; it under the terms of the GNU Affero General Public License as ;; published by the Free Software Foundation, either version 3 of the ;; License, or (at your option) any later version. ;; ;; This program is distributed in the hope that it will be useful, ;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;; GNU Affero General Public License for more details. ;; ;; You should have received a copy of the GNU Affero General Public License ;; along with this program. If not, see <http://www.gnu.org/licenses/>. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Package ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (in-package :microblog-bot) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Basic bot ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defconstant %sleep-time 180 "How many seconds to wait between each run of the bot") (defconstant %default-source-url nil "The default source url for this code (or a derivative)") (defconstant %default-last-handled-reply 0 "The default last reply post id handled") (defconstant %default-ignore-replies-from '() "Usernames to ignore replies from") (defclass microblog-bot (microblog-user) ((source-url :accessor source-url :initarg :source-url :allocation :class :initform %default-source-url) (ignore-replies-from :accessor ignore-replies-from :initarg :ignore :initform %default-ignore-replies-from) (last-handled-reply :accessor last-handled-reply :initarg :last-handled-reply :initform %default-last-handled-reply) (updates-to-post :accessor updates-to-post :initform '()) (update-timespan :accessor update-timespan :initarg :update-timespan ;; Spread the responses over 20 minutes :initform (* 20 60)))) (defmethod last-handled-reply-id ((bot microblog-bot)) "Get the exclusive lower bound for replies to the user to check" (or (cl-twit::get-newest-id (cl-twit:m-user-timeline)) (cl-twit::get-newest-id (cl-twit:m-public-timeline)))) (defmethod initialize-instance :after ((bot microblog-bot) &key) "Set up the bot's state" (assert (source-url bot)) (handler-case (with-microblog-user bot (setf (last-handled-reply bot) (last-handled-reply-id bot))) (condition (the-condition) (format t "Error for ~a ~%" (user-nickname bot)) (invoke-debugger the-condition))) (debug-msg "Initialized bot ~a most-recent-reply ~a" bot (last-handled-reply bot))) (defmethod response-for-source-request ((bot microblog-bot) reply) "Response for the source request" (format nil "@~a Hi! You can get my source here: ~a" (cl-twit:user-screen-name (cl-twit:status-user reply)) (source-url bot))) (defmethod response-for-reply ((bot microblog-bot) reply) "Response for the reply object" (format nil "@~a Hi!" (cl-twit:user-screen-name (cl-twit:status-user reply)))) (defmethod response-p ((bot microblog-bot) post) "Check whether our post is a response." (search "Hi!" (cl-twit:status-text post))) (defmethod filter-replies ((bot microblog-bot) replies) "Make sure only one reply from each user is listed" (remove-duplicates replies :test #'(lambda (a b) (string= (cl-twit:user-screen-name (cl-twit:status-user a)) (cl-twit:user-screen-name (cl-twit:status-user b)))))) (defmethod should-ignore ((bot microblog-bot) message &optional (default t)) "Check whether the bot should ignore the message" (handler-case (find (cl-twit:user-screen-name (cl-twit:status-user message)) (ignore-replies-from bot) :test #'string=) (condition (the-condition) (report-error "should-ignore ~a ~a - ~a~%" (user-nickname bot) bot the-condition) default))) (defmethod new-replies ((bot microblog-bot)) "Get any new replies for the bot's account, or nil" (debug-msg "new-replies after ~a" (last-handled-reply bot)) (handler-case (sort (cl-twit:m-replies :since-id (last-handled-reply bot)) #'string< :key #'cl-twit::id) (condition (the-condition) (report-error "new-replies ~a ~a - ~a~%" (user-nickname bot) bot the-condition) nil))) (defun source-request-p (reply) "Is the message a source request?" (search "!source" (cl-twit:status-text reply))) (defmethod respond-to-replies ((bot microblog-bot)) "Respond to new replies since replies were last processed" ;; If we've ended up with a null last-handled-reply, try to recover (when (not (last-handled-reply bot)) (setf (last-handled-reply bot) (last-handled-reply-id bot))) ;; If it's still null the server is probably sad, don't respond this time (when (last-handled-reply bot) (let ((replies (filter-replies bot (new-replies bot)))) (when replies (dolist (reply replies) (when (not (should-ignore bot reply t)) (handler-case (let ((response (if (source-request-p reply) (response-for-source-request bot reply) (response-for-reply bot reply)))) (when response (queue-update bot response :in-reply-to (cl-twit::status-id reply)))) (condition (the-condition) (report-error "respond-to-replies ~a ~a - ~a~%" (user-nickname bot) bot the-condition))))) ;; If any responses failed, they will be skipped ;; This will set to null if replies are null, so ensure it's in a when (setf (last-handled-reply bot) (cl-twit::get-newest-id replies)))))) (defmethod manage-task ((bot microblog-bot)) "Do the bot's task once." (respond-to-replies bot)) (defmethod queue-update ((bot microblog-bot) (update string) &key (in-reply-to nil)) "Queue the update to be posted as soon as possible." ;; Store as (message . in-reply-to-message-id), the latter probably nil (setf (updates-to-post bot) (append (updates-to-post bot) (list (cons update in-reply-to))))) (defmethod post-updates ((bot microblog-bot)) "Post the updates" (let* ((updates-count (length (updates-to-post bot))) (time-between-updates (floor (/ (update-timespan bot) (max updates-count 1))))) ;; Loop, taking updates from the list (loop for update = (pop (updates-to-post bot)) then (pop (updates-to-post bot)) while update ;; Posting them ;; This is the one place in the code we actually want to use (post) do (handler-case (progn (post (car update) :in-reply-to-status-id (cdr update)) ;; More to post? Sleep before doing so (if (updates-to-post bot) (sleep time-between-updates))) (cl-twit:http-error (the-error) (format t "Error for ~a ~a update \"~a\" - ~a ~%" (user-nickname bot) bot update the-error) ;;FIXME: check (cl-twit:http-status-code the-error) ;; and die on 4xx errors ;; Restore the failed update (push update (updates-to-post bot)) ;; And don't try any more for now, wait for the next run ;; Which may not add any more messages, but will try to post these (return)) ;; Other errors that we know about ((or usocket:socket-condition usocket:ns-condition drakma:drakma-condition cl+ssl::ssl-error) (the-error) (format t "Error for ~a ~a update \"~a\" - ~a ~%" (user-nickname bot) bot update the-error) ;; Restore the failed update (push update (updates-to-post bot)) ;; And don't try any more for now, wait for the next run ;; Which may not add any more messages, but will try to post these (return)))))) (defmethod run-bot-once ((bot microblog-bot)) (debug-msg "Running bot once ~a" bot) (handler-case (with-microblog-user bot ;; The use of :after methods ensures that this handles all subclasses (manage-task bot) ;; This will try to post all the updates in the queue (post-updates bot)) (condition (the-condition) (format t "Error for ~a ~a - ~a ~%" (user-nickname bot) bot the-condition) ;; If the error wasn't handled it's unexpected, so quit here (invoke-debugger the-condition)))) (defmethod run-bot ((bot microblog-bot)) "Loop forever responding to replies & occasionaly performing periodic-task" (loop (run-bot-once bot) (sleep %sleep-time)))
8,646
Common Lisp
.lisp
201
38.293532
80
0.658751
rheaplex/microblog-bot
2
0
0
AGPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
e9a3efef4a77456c89d605d8d5508086c6c8f6780846bb140daa857f5e7ddd5e
20,690
[ -1 ]
20,691
utilities.lisp
rheaplex_microblog-bot/utilities.lisp
;; utilities.lisp - Basic utilities for the microblogging package. ;; Copyright (C) 2009 Rob Myers [email protected] ;; ;; This program is free software: you can redistribute it and/or modify ;; it under the terms of the GNU Affero General Public License as ;; published by the Free Software Foundation, either version 3 of the ;; License, or (at your option) any later version. ;; ;; This program is distributed in the hope that it will be useful, ;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;; GNU Affero General Public License for more details. ;; ;; You should have received a copy of the GNU Affero General Public License ;; along with this program. If not, see <http://www.gnu.org/licenses/>. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Package ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (in-package :microblog-bot) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Useful constants ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defconstant %one-hour (* 60 60) "One hour in seconds") (defconstant %one-day (* 24 %one-hour) "One day in seconds") ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Error handling and testing ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defvar *print-debug-messages* nil "Whether debug messages should be printed to stdout or ignored") (defvar *post-to-server* t "Whether posts should be sent to the server or just printed locally") (defun time-string () "Format a human-readable time" (multiple-value-bind (second minute hour date month year) (get-decoded-time) (format nil "~a-~a-~a ~a:~a:~a" year month date hour minute second))) (defun debug-msg (&rest args) "Print to stdout if debugging, or ignore if not debugging" (if *print-debug-messages* (apply #'format t (concatenate 'string "~a - " (car args) "~%") (time-string) (cdr args)))) (defmethod set-debug (&key (post nil) (msgs t)) "Set the state of the library to debugging, with posting set by the keyword" (setf *print-debug-messages* msgs) (setf *post-to-server* post)) (defun set-live () "Set the state of the library to live" (setf *print-debug-messages* nil) (setf *post-to-server* t)) (defun report-error (&rest args) "Print the error to stdout" (apply #'format t args)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Microblog service and state utilities ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun set-microblog-service (server-url from-source) "Set the server and the 'from..' string displayed on messages to that server" (debug-msg "Setting server for ~a to ~a" from-source server-url) (setf twit::*source* from-source) (setf twit::*base-url* server-url)) (defmethod post (message &key (in-reply-to-status-id nil)) "Post to the server if live, or just print if not" (when *print-debug-messages* (format t "~a - ~a~%" (time-string) message)) (when *post-to-server* (cl-twit:m-update message :in-reply-to-status-id in-reply-to-status-id)))
3,331
Common Lisp
.lisp
68
46.514706
80
0.581431
rheaplex/microblog-bot
2
0
0
AGPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
55c97f4605db19541c0efa10ae8aff46a334d05ec5426b20508bb9551d4d5b5f
20,691
[ -1 ]
20,692
install.lisp
rheaplex_microblog-bot/install.lisp
;; install.lisp - Run once to install support libraries for building. ;; Copyright (C) 2009 Rob Myers [email protected] ;; ;; This program is free software: you can redistribute it and/or modify ;; it under the terms of the GNU Affero General Public License as ;; published by the Free Software Foundation, either version 3 of the ;; License, or (at your option) any later version. ;; ;; This program is distributed in the hope that it will be useful, ;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;; GNU Affero General Public License for more details. ;; ;; You should have received a copy of the GNU Affero General Public License ;; along with this program. If not, see <http://www.gnu.org/licenses/>. (require 'asdf) (require 'asdf-install) (asdf-install:install 'cxml-stp) (asdf-install:install 'drakma) (when (not (file-probe "./cl-twit.asd")) (sb-posix:symlink "./cl-twit/cl-twit.asd" "./cl-twit.asd"))
1,000
Common Lisp
.lisp
21
46.428571
75
0.752303
rheaplex/microblog-bot
2
0
0
AGPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
8ab516709defb36f34707ec1861577161300de89c5594aef2f60e4b440f9bbff
20,692
[ -1 ]
20,693
testing.lisp
rheaplex_microblog-bot/testing.lisp
;; testing.lisp - Test the bots. ;; Copyright (C) 2009 Rob Myers [email protected] ;; ;; This program is free software: you can redistribute it and/or modify ;; it under the terms of the GNU Affero General Public License as ;; published by the Free Software Foundation, either version 3 of the ;; License, or (at your option) any later version. ;; ;; This program is distributed in the hope that it will be useful, ;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;; GNU Affero General Public License for more details. ;; ;; You should have received a copy of the GNU Affero General Public License ;; along with this program. If not, see <http://www.gnu.org/licenses/>. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Package ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (in-package :microblog-bot) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Testing ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmethod test-run-task-once ((bot microblog-bot) i &key (fun nil) &allow-other-keys) (when fun (apply fun bot i))) (defmethod test-run-task-once :after ((bot daily-task-bot) i &key (daily 3) &allow-other-keys) ;; Run the daily task every daily iterations (when (= (mod i daily) 0) (setf (previous-day bot) 0))) (defmethod test-run-task-once :after ((bot intermittent-task-bot) i &key (periodic 2) &allow-other-keys) ;; Run the periodic task every periodic iterations (when (= (mod i periodic) 0) (setf (wait-remaining bot) 0))) (defmethod test-run-bot-once ((bot microblog-bot) &key (i 0) (post nil) (daily 3) (periodic 2) (fun nil) (msgs t)) (assert (and (not (search "identi.ca" twit::*base-url*)) (not (search "twitter.com" twit::*base-url*)))) (set-debug :post post :msgs msgs) (with-microblog-user bot (test-run-task-once bot i :post post :daily daily :periodic periodic :fun fun) (run-bot-once bot))) (defmethod test-run-bot ((bot microblog-bot) iterations &key (post nil) (daily 3) (periodic 2) (fun nil) (msgs t)) "Run the bot the given number of times, running daily & priodic tasks as set" (setf (daily-task-hour bot) 0) (dotimes (i iterations) (test-run-bot-once bot i :post post :daily daily :periodic periodic :fun fun :msgs msgs)))
2,528
Common Lisp
.lisp
56
41.410714
80
0.599106
rheaplex/microblog-bot
2
0
0
AGPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
71916ba0308db71882e1e4a34fe0c00c450eae0ac98c07f2719ee6ebf211690d
20,693
[ -1 ]
20,694
microblog-follower-bot.lisp
rheaplex_microblog-bot/microblog-follower-bot.lisp
;; follower-bot.lisp - A bot that follows another user's posts. ;; Copyright (C) 2009 Rob Myers [email protected] ;; ;; This program is free software: you can redistribute it and/or modify ;; it under the terms of the GNU Affero General Public License as ;; published by the Free Software Foundation, either version 3 of the ;; License, or (at your option) any later version. ;; ;; This program is distributed in the hope that it will be useful, ;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;; GNU Affero General Public License for more details. ;; ;; You should have received a copy of the GNU Affero General Public License ;; along with this program. If not, see <http://www.gnu.org/licenses/>. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Package ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (in-package :microblog-bot) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; User-following bot ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defconstant %default-last-handled-post 0) (defconstant %default-follow-id nil) (defclass microblog-follower-bot (microblog-bot) ((last-handled-post :accessor last-handled-post :initarg :last-handled-post :initform 0) (follow-id :accessor follow-id))) (defmethod current-user-posts-after-id ((bot microblog-follower-bot)) "Get the exclusive lower bound for replies to the user to check" (or (cl-twit::get-newest-id (cl-twit:m-user-timeline)) (cl-twit::get-newest-id (cl-twit:m-public-timeline)))) (defmethod initialize-instance :after ((bot microblog-follower-bot) &key (follow-screen-name nil)) "Set up the bot's state" (when follow-screen-name (setf (follow-id bot) (user-id-for-screen-name follow-screen-name))) (with-microblog-user bot (setf (last-handled-post bot) (current-user-posts-after-id bot))) (debug-msg "Initialized bot ~a most-recent-reply-update ~a" bot (last-handled-post bot))) (defmethod response-for-post ((bot microblog-follower-bot) post) "Response for the post object, or nil not to respond" nil) (defmethod respond-to-post ((bot microblog-follower-bot) post) "Respond to the post object in some way" (debug-msg "Responding to post ~a" post) (let ((response (response-for-post bot post))) (when response (queue-update bot response)))) (defmethod filter-posts ((bot microblog-follower-bot) posts) "Make sure only one post from each user is listed" posts) (defmethod new-posts ((bot microblog-follower-bot)) "Get posts from followed user since last checked" (handler-case (sort (cl-twit:m-user-timeline :id (follow-id bot) :since-id (last-handled-post bot)) #'string< :key #'cl-twit::id) (condition (err) (report-error "new-posts ~a - ~a~%" bot err) nil))) (defmethod respond-to-posts ((bot microblog-follower-bot)) "Respond to new posts since posts were last processed" (debug-msg "Responding to posts") ;; If we've ended up with a null last-handled-post, try to recover (when (not (last-handled-post bot)) (setf (last-handled-post bot) (current-user-posts-after-id bot))) ;; If it's still null the server is probably sad, don't respond this time (when (last-handled-post bot) (let ((posts (new-posts bot))) (when posts (debug-msg "Posts to respond to ~a" posts) (dolist (post (filter-posts bot posts)) (respond-to-post bot post)) ;; If any posts weren't processed, they will be skipped ;; This will set to null if posts are null, so make sure it's in a when (setf (last-handled-post bot) (cl-twit::get-newest-id posts)))) (debug-msg "Most recent post after ~a" (last-handled-post bot)))) (defmethod manage-task :after ((bot microblog-follower-bot)) "Do the bot's task once." (respond-to-posts bot))
4,004
Common Lisp
.lisp
87
42.574713
80
0.657611
rheaplex/microblog-bot
2
0
0
AGPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
2999d69159b3c410d0adae275b44d3a71d54afc6e688be99a57977327297485a
20,694
[ -1 ]
20,695
intermittent-task-bot.lisp
rheaplex_microblog-bot/intermittent-task-bot.lisp
;; intermittent-task-bot.lisp - Bot that runs a task every so often. ;; Copyright (C) 2009 Rob Myers [email protected] ;; ;; This program is free software: you can redistribute it and/or modify ;; it under the terms of the GNU Affero General Public License as ;; published by the Free Software Foundation, either version 3 of the ;; License, or (at your option) any later version. ;; ;; This program is distributed in the hope that it will be useful, ;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;; GNU Affero General Public License for more details. ;; ;; You should have received a copy of the GNU Affero General Public License ;; along with this program. If not, see <http://www.gnu.org/licenses/>. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Package ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (in-package :microblog-bot) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Basic bot ;; TODO Split out into constant and intermittent bots, or tasks for a bot? ;; Tasks are probably best ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defconstant %default-min-wait %one-hour "The default minimum time in seconds between posts") (defconstant %default-max-wait (* %one-hour 3) "The default maximum time in seconds between posts") (defconstant %default-wait-remaining 0 "The default delay until the next post") (defclass intermittent-task-bot (microblog-bot) ((min-wait :accessor min-wait :initarg :min-wait :initform %default-min-wait) (max-wait :accessor max-wait :initarg :max-wait :initform %default-max-wait) (wait-remaining :accessor wait-remaining :initarg :wait-remaining :initform %default-wait-remaining))) (defmethod set-next-wait ((bot intermittent-task-bot)) "Set the time until next execution to between min-wait..max-wait" (setf (wait-remaining bot) (+ (min-wait bot) (random (- (max-wait bot) (min-wait bot))))) (debug-msg "Resetting wait period for ~a to ~a" bot (wait-remaining bot))) (defmethod intermittent-task ((bot intermittent-task-bot)) "Perform some intermittent task" nil) (defmethod manage-intermittent-task ((bot intermittent-task-bot)) "Run the task or update the wait time" (debug-msg "Wait remaining for bot ~a is ~a" bot (wait-remaining bot)) (if (<= (wait-remaining bot) 0) (handler-case (progn (intermittent-task bot) (set-next-wait bot)) (error (err) (report-error "manage-intermittent-task ~a - ~a~%" bot err))) (setf (wait-remaining bot) (- (wait-remaining bot) %sleep-time)))) (defmethod manage-task :after ((bot intermittent-task-bot)) "Do the bot's task once." (manage-intermittent-task bot))
2,902
Common Lisp
.lisp
66
40.878788
80
0.642124
rheaplex/microblog-bot
2
0
0
AGPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
8a9d3005e140d6d38aeaa9bd3561dec7c5dde7ca16190feb908ac24fb79b9942
20,695
[ -1 ]
20,696
constant-task-bot.lisp
rheaplex_microblog-bot/constant-task-bot.lisp
;; constant-task-bot.lisp - A bot that does something every time it's run. ;; Copyright (C) 2009 Rob Myers [email protected] ;; ;; This program is free software: you can redistribute it and/or modify ;; it under the terms of the GNU Affero General Public License as ;; published by the Free Software Foundation, either version 3 of the ;; License, or (at your option) any later version. ;; ;; This program is distributed in the hope that it will be useful, ;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;; GNU Affero General Public License for more details. ;; ;; You should have received a copy of the GNU Affero General Public License ;; along with this program. If not, see <http://www.gnu.org/licenses/>. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Package ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (in-package :microblog-bot) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Constant task bot ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defclass constant-task-bot (microblog-bot) ()) (defmethod constant-task ((bot microblog-bot)) "Performed every time the bot wakes up" nil) (defmethod manage-task :after ((bot constant-task-bot)) "Do the bot's task once." (constant-task bot))
1,440
Common Lisp
.lisp
30
46.4
80
0.582739
rheaplex/microblog-bot
2
0
0
AGPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
18c90d03f10a28b25c3a325d0ae6c4d7d14d6a06cd7afeb6d0539e355c285ec6
20,696
[ -1 ]
20,697
classes.lisp
rheaplex_microblog-bot/cl-twit/classes.lisp
;;; -*- Mode: LISP; Syntax: COMMON-LISP; Package: CL-USER; Base: 10 -*- ;;; classes.lisp ;;; Copyright (c) 2009, Chaitanya Gupta. ;;; All rights reserved. ;;; ;;; Redistribution and use in source and binary forms, with or without ;;; modification, are permitted provided that the following conditions ;;; are met: ;;; 1. Redistributions of source code must retain the above copyright ;;; notice, this list of conditions and the following disclaimer. ;;; 2. Redistributions in binary form must reproduce the above copyright ;;; notice, this list of conditions and the following disclaimer in the ;;; documentation and/or other materials provided with the distribution. ;;; 3. The name of the author may not be used to endorse or promote products ;;; derived from this software without specific prior written permission. ;;; ;;; THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR ;;; IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES ;;; OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. ;;; IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, ;;; INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT ;;; NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ;;; DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ;;; THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ;;; (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF ;;; THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. (cl:in-package #:cl-twit) ;;; Our objects (defstruct status created-at id text source truncated in-reply-to-status-id in-reply-to-user-id favorited user) (defmethod print-object ((x status) stream) (print-unreadable-object (x stream :type t :identity t) (format stream "~A (~A) " (status-id x) (and (status-user x) (user-screen-name (status-user x)))) (let ((text (status-text x))) (format stream "~S" (if (< (length text) 10) text (concatenate 'string (subseq text 0 10) " ...")))))) (defstruct user id name screen-name location description profile-image-url url protected followers-count) (defmethod print-object ((x user) stream) (print-unreadable-object (x stream :type t :identity t) (format stream "~A (~A)" (user-name x) (user-screen-name x)))) (defstruct (extended-user (:include user) (:conc-name "USER-")) profile-background-color profile-text-color profile-link-color profile-sidebar-fill-color profile-sidebar-border-color friends-count created-at favourites-count utc-offset time-zone profile-background-image-url profile-background-tile following notifications statuses-count) (defstruct message id sender-id text recipient-id created-at sender-screen-name recipient-screen-name sender recipient) (defmethod print-object ((x message) stream) (print-unreadable-object (x stream :type t :identity t) (format stream "~A-->~A " (message-sender-screen-name x) (message-recipient-screen-name x)) (let ((text (message-text x))) (format stream "~S" (if (< (length text) 10) text (concatenate 'string (subseq text 0 10) " ...")))))) (defstruct rate-limit reset-time reset-time-seconds remaining-hits hourly-limit) ;;; Conditions (define-condition twitter-error (error) ()) (define-condition twitter-simple-error (twitter-error simple-error) ()) (define-condition http-error (twitter-error) ((status-code :reader http-status-code :initarg :status-code) (url :reader http-url :initarg :url) (body :reader http-body :initarg :body))) (defmethod print-object ((x http-error) stream) (if (null *print-escape*) (format stream "~A returned by ~A~%Body: ~A" (http-status-code x) (http-url x) (http-body x)) (call-next-method))) (define-condition xml-error (twitter-error) ((reason :reader xml-error-reason :initarg :reason) (deadline :reader xml-error-deadline :initarg :deadline) (text :reader xml-error-text :initarg :text))) (defmethod print-object ((x xml-error) stream) (if (null *print-escape*) (format stream "Reason: ~A~%Deadline: ~A~%Text: ~A" (xml-error-reason x) (xml-error-deadline x) (xml-error-text x)) (call-next-method))) ;;; An 'id' method for our objects (defgeneric id (x) (:method ((x status)) (status-id x)) (:method ((x user)) (user-id x)) (:method ((x message)) (message-id x)))
4,826
Common Lisp
.lisp
143
28.916084
77
0.673745
rheaplex/microblog-bot
2
0
0
AGPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
bcf9937af54aa6e840faf119440887bda4f51009944b2612134899ca83083ad2
20,697
[ 204742 ]
20,698
cl-twit.lisp
rheaplex_microblog-bot/cl-twit/cl-twit.lisp
;;; -*- Mode: LISP; Syntax: COMMON-LISP; Package: CL-USER; Base: 10 -*- ;;; cl-twit.lisp ;;; Copyright (c) 2009, Chaitanya Gupta. ;;; All rights reserved. ;;; ;;; Redistribution and use in source and binary forms, with or without ;;; modification, are permitted provided that the following conditions ;;; are met: ;;; 1. Redistributions of source code must retain the above copyright ;;; notice, this list of conditions and the following disclaimer. ;;; 2. Redistributions in binary form must reproduce the above copyright ;;; notice, this list of conditions and the following disclaimer in the ;;; documentation and/or other materials provided with the distribution. ;;; 3. The name of the author may not be used to endorse or promote products ;;; derived from this software without specific prior written permission. ;;; ;;; THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR ;;; IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES ;;; OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. ;;; IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, ;;; INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT ;;; NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ;;; DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ;;; THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ;;; (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF ;;; THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. (cl:in-package #:cl-twit) ;; Hideous hack to fix problem with cxml not liking the new statusnet namespace (let ((cxml::*namespace-bindings* (acons #"statusnet" #"http://status.net/schema/api/1/" cxml::*namespace-bindings*)))) ;;; TODOs: ;;;; TODO: Methods to be tested: update- (?) ;;;; TODO: Easily switch context between profiles (?) ;;;; TODO: Should we parse-status for the user (?) ;;;; TODO: Epoch for twitter's Unix time (?) ;;; Utils (defmacro when-let ((var test) &body body) `(let ((,var ,test)) (when ,var ,@body))) (defun compose (fn1 &rest fns) (if fns (lambda (x) (funcall fn1 (funcall (apply #'compose fns) x))) fn1)) ;;; Parse XML (defun xml-root (raw-xml) (stp:document-element (cxml:parse raw-xml (stp:make-builder)))) (defun child-value (node child-name) (stp:string-value (stp:find-child-if (stp:of-name child-name) node))) (defun boolify (string) (string-equal string "true")) (defun parse-xml-error (node) (make-condition 'xml-error :reason (stp:attribute-value node "reason") :deadline (stp:attribute-value node "deadline") :text (stp:string-value node))) (defun safe-xml-root (raw-xml) (let ((node (xml-root raw-xml))) (if (string-equal (stp:local-name node) "error") (error (parse-xml-error node)) node))) (defun parse-status (status-node) (flet ((!child-value (name) (child-value status-node name))) (make-status :created-at (!child-value "created_at") :id (!child-value "id") :text (!child-value "text") :source (!child-value "source") :truncated (boolify (!child-value "source")) :in-reply-to-status-id (!child-value "in_reply_to_status_id") :in-reply-to-user-id (!child-value "in_reply_to_user_id") :favorited (boolify (!child-value "favorited")) :user (when-let (user-node (stp:find-child-if (stp:of-name "user") status-node)) (parse-user user-node))))) (defun parse-statuses (node) (map 'list #'parse-status (stp:filter-children (stp:of-name "status") node))) (defun parse-user (user-node) (flet ((!child-value (name) (child-value user-node name))) (make-user :id (!child-value "id") :name (!child-value "name") :screen-name (!child-value "screen_name") :location (!child-value "location") :description (!child-value "description") :profile-image-url (!child-value "profile_image_url") :url (!child-value "url") :protected (boolify (!child-value "protected")) :followers-count (parse-integer (!child-value "followers_count"))))) (defun parse-users (node) (mapcar #'parse-user (stp:filter-children (stp:of-name "user") node))) (defun parse-extended-user (user-node) (flet ((!child-value (name) (child-value user-node name))) (make-extended-user :id (!child-value "id") :name (!child-value "name") :screen-name (!child-value "screen_name") :location (!child-value "location") :description (!child-value "description") :profile-image-url (!child-value "profile_image_url") :url (!child-value "url") :protected (boolify (!child-value "protected")) :followers-count (parse-integer (!child-value "followers_count")) :profile-background-color (!child-value "profile_background_color") :profile-text-color (!child-value "profile_text_color") :profile-link-color (!child-value "profile_link_color") :profile-sidebar-fill-color (!child-value "profile_sidebar_fill_color") :profile-sidebar-border-color (!child-value "profile_sidebar_border_color") :friends-count (parse-integer (!child-value "friends_count")) :created-at (!child-value "created_at") :favourites-count (parse-integer (!child-value "favourites_count")) :utc-offset (parse-integer (!child-value "utc_offset") :junk-allowed t) :time-zone (!child-value "time_zone") :profile-background-image-url (!child-value "profile_background_image_url") :profile-background-tile (boolify (!child-value "profile_background_tile")) :following (boolify (!child-value "following")) :notifications (boolify (!child-value "notifications")) :statuses-count (parse-integer (!child-value "statuses_count"))))) (defun parse-message (message-node) (flet ((!child-value (name) (child-value message-node name))) (make-message :id (!child-value "id") :sender-id (!child-value "sender_id") :text (!child-value "text") :recipient-id (!child-value "recipient_id") :created-at (!child-value "created_at") :sender-screen-name (!child-value "sender_screen_name") :recipient-screen-name (!child-value "recipient_screen_name") :sender (when-let (user-node (stp:find-child-if (stp:of-name "sender") message-node)) (parse-user user-node)) :recipient (when-let (user-node (stp:find-child-if (stp:of-name "recipient") message-node)) (parse-user user-node))))) (defun parse-messages (node) (mapcar #'parse-message (stp:filter-children (stp:of-name "direct_message") node))) (defun parse-ids (node) (mapcar #'stp:string-value (stp:filter-children (stp:of-name "id") node))) (defun parse-rate-limit (node) (flet ((!child-value (name) (child-value node name))) (make-rate-limit :reset-time (!child-value "reset-time") :reset-time-seconds (parse-integer (!child-value "reset-time-in-seconds")) :remaining-hits (parse-integer (!child-value "remaining-hits")) :hourly-limit (parse-integer (!child-value "hourly-limit"))))) ;;; Methods base (defparameter *base-url* "https://identi.ca/api") (defparameter *source* "cltwit") (defvar *username* nil "The user's account username") (defvar *password* nil "The user's account password") (defconstant +http-ok+ 200) (defvar *twitter-parameters* nil) (defvar *twitter-external-format* :utf-8 "The external format to be used for HTTP requests.") (defun twitter-request (path &rest args) (let ((url (concatenate 'string *base-url* path))) (multiple-value-bind (body status-code) (let ((drakma:*drakma-default-external-format* *twitter-external-format*)) (apply #'drakma:http-request url (append (and *username* *password* (list :basic-authorization (list *username* *password*))) (unless (getf args :parameters) (list :parameters *twitter-parameters*)) args))) (if (= status-code +http-ok+) body (error 'http-error :status-code status-code :url url #+sbcl :body (sb-ext:octets-to-string body) #-sbcl :body body))))) (defparameter *max-text-length* 140) ;;; Methods (defun params-list (&rest pairs) (remove nil pairs)) (defun pair-when (name value) (and value (cons name (format nil "~A" value)))) (defun optional-id-path (id prefix) (format nil "~A~@[/~A~].xml" prefix id)) ;;; Macro for defining twitter methods (eval-when (:compile-toplevel :load-toplevel :execute) (defun parameter-string (symbol) (let ((string (string-downcase (string symbol)))) (substitute #\_ #\- string)))) (defmacro def-twitter-method (name args &body body) (let ((arglist nil) (params nil) (doc-string nil)) (dolist (arg args) (cond ((member arg '(&optional &key &rest &aux)) (push arg arglist)) ((atom arg) (push arg arglist) (push `(pair-when ,(parameter-string arg) ,arg) params)) ((listp arg) (destructuring-bind (arg-name &key default (parameter nil parameterp)) arg (if default (push (list (first arg) default) arglist) (push (first arg) arglist)) (cond ((null parameterp) (push `(pair-when ,(parameter-string parameter) ,arg-name) params)) ((null parameter) t) ((stringp parameter) (push `(pair-when ,parameter ,arg-name) params)) (t (error "DEF-TWITTER-METHOD arg parser: bad user of :PARAMETER.~%~A" args))))) (t (error "DEF-TWITTER-METHOD arg parser: Can't handle this case.~%~A" args)))) (setf arglist (nreverse arglist) params (cons 'params-list params)) (when (stringp (first body)) (setf doc-string (first body) body (rest body))) `(defun ,name ,arglist ,@(when doc-string (list doc-string)) (let ((*twitter-parameters* ,params)) ,@body)))) ;;; Status methods (def-twitter-method m-public-timeline () (let* ((body (twitter-request "/statuses/public_timeline.xml"))) (parse-statuses (safe-xml-root body)))) (def-twitter-method m-friends-timeline (&key since-id count page) (let* ((body (twitter-request "/statuses/friends_timeline.xml"))) (parse-statuses (safe-xml-root body)))) (def-twitter-method m-user-timeline (&key (id :parameter nil) since-id count page) (let* ((body (twitter-request (optional-id-path id "/statuses/user_timeline")))) (parse-statuses (safe-xml-root body)))) (def-twitter-method m-show ((id :parameter nil)) (let ((body (twitter-request (format nil "/statuses/show/~A.xml" id)))) (parse-status (safe-xml-root body)))) (def-twitter-method m-update (status &key in-reply-to-status-id) (assert (and (not (null status)) (<= (length status) *max-text-length*)) nil "STATUS must be non-NIL and its length must not be greater than ~A. Current length: ~A" *max-text-length* (length status)) (let* ((body (twitter-request "/statuses/update.xml" :method :post :parameters (cons (cons "source" *source*) *twitter-parameters*)))) (parse-status (safe-xml-root body)))) (def-twitter-method m-replies (&key since-id page) (let* ((body (twitter-request "/statuses/replies.xml"))) (parse-statuses (safe-xml-root body)))) (def-twitter-method m-destroy ((id :parameter nil)) (let ((body (twitter-request (format nil "/statuses/destroy/~A.xml" id) :method :delete))) (parse-status (safe-xml-root body)))) ;;; User methods (def-twitter-method m-friends (&key (id :parameter nil) page) (let ((body (twitter-request (optional-id-path id "/statuses/friends")))) (parse-users (safe-xml-root body)))) (def-twitter-method m-followers (&key (id :parameter nil) page) (parse-users (safe-xml-root (twitter-request (optional-id-path id "/statuses/followers"))))) (def-twitter-method m-user-show (&key (id :parameter nil) email) (assert (or id email) nil "Provide atleast one of id or email.") (parse-extended-user (safe-xml-root (twitter-request (optional-id-path id "/users/show"))))) ;;; Direct message methods (def-twitter-method m-messages (&key since-id page) (parse-messages (safe-xml-root (twitter-request "/direct_messages.xml")))) (def-twitter-method m-messages-sent (&key since-id page) (parse-messages (safe-xml-root (twitter-request "/direct_messages/sent.xml")))) (def-twitter-method m-messages-new (user text) (assert (and (not (null text)) (<= (length text) *max-text-length*)) nil "TEXT must be non-NIL and its length must not be greater than ~A. Current length: ~A" *max-text-length* (length text)) (parse-message (safe-xml-root (twitter-request "/direct_messages/new.xml" :method :post)))) (def-twitter-method m-messages-destroy ((id :parameter nil)) (parse-message (safe-xml-root (twitter-request (format nil "/direct_messages/destroy/~A.xml" id) :method :delete)))) ;;; Friendship methods (def-twitter-method m-friendship-create ((id :parameter nil) &key follow) (parse-user (safe-xml-root (twitter-request (format nil "/friendships/create/~A.xml" id) :method :post)))) (def-twitter-method m-friendship-destroy ((id :parameter nil)) (parse-user (safe-xml-root (twitter-request (format nil "/friendships/destroy/~A.xml" id) :method :delete)))) (def-twitter-method m-friendship-exists (user-a user-b) (boolify (stp:string-value (safe-xml-root (twitter-request "/friendships/exists.xml"))))) ;;; Social graph methods (def-twitter-method m-graph-friends (&key (id :parameter nil)) (parse-ids (safe-xml-root (twitter-request (optional-id-path id "/friends/ids"))))) (def-twitter-method m-graph-followers (&key (id :parameter nil)) (parse-ids (safe-xml-root (twitter-request (optional-id-path id "/followers/ids"))))) ;;; Account methods (def-twitter-method m-verify-credentials () (parse-user (safe-xml-root (twitter-request "/account/verify_credentials.xml")))) (def-twitter-method m-end-session () (twitter-request "/account/end_session.xml" :method :post)) (def-twitter-method m-update-delivery-device (device) (assert (member device (list "sms" "im" "none") :test #'equal)) (parse-user (safe-xml-root (twitter-request "/account/update_delivery_device.xml" :method :post)))) (def-twitter-method m-update-profile-colors (&key profile-background-color profile-text-color profile-link-color profile-sidebar-fill-color profile-sidebar-border-color) (parse-extended-user (safe-xml-root (twitter-request "/account/update_profile_colors.xml" :method :post)))) (def-twitter-method m-update-profile-image (image) (parse-extended-user (safe-xml-root (twitter-request "/account/update_profile_image.xml" :method :post)))) (def-twitter-method m-update-profile-background-image (image) (parse-extended-user (safe-xml-root (twitter-request "/account/update_profile_background_image.xml" :method :post)))) (def-twitter-method m-rate-limit-status () (parse-rate-limit (safe-xml-root (twitter-request "/account/rate_limit_status.xml")))) (def-twitter-method m-update-profile (&key name email url location description) (parse-extended-user (safe-xml-root (twitter-request "/account/update_profile.xml" :method :post)))) ;;; Favorite methods (def-twitter-method m-favorites (&key (id :parameter nil) page) (parse-statuses (safe-xml-root (twitter-request (optional-id-path id "/favorites"))))) (def-twitter-method m-favorites-create ((id :parameter nil)) (parse-status (safe-xml-root (twitter-request (format nil "/favorites/create/~A.xml" id) :method :post)))) (def-twitter-method m-favorites-destroy ((id :parameter nil)) (parse-status (safe-xml-root (twitter-request (format nil "/favorites/destroy/~A.xml" id) :method :delete)))) ;;; Notification methods (def-twitter-method m-follow ((id :parameter nil)) (parse-user (safe-xml-root (twitter-request (format nil "/notifications/follow/~A.xml" id) :method :post)))) (def-twitter-method m-leave ((id :parameter nil)) (parse-user (safe-xml-root (twitter-request (format nil "/notifications/leave/~A.xml" id) :method :post)))) ;;; Block methods (def-twitter-method m-block-create ((id :parameter nil)) (parse-user (safe-xml-root (twitter-request (format nil "/blocks/create/~A.xml" id) :method :post)))) (def-twitter-method m-block-destroy ((id :parameter nil)) (parse-user (safe-xml-root (twitter-request (format nil "/blocks/destroy/~A.xml" id) :method :post)))) ;;; Help methods (def-twitter-method m-test () (twitter-request "/help/test.xml") t) ;;; Account and session helpers (defvar *state*) (defstruct (session-state (:conc-name nil)) (friends-timeline-id nil) (user-timeline-ids (make-hash-table :test #'equalp)) (replies-id nil) (messages-id nil) (sent-messages-id nil) (session-statuses (make-hash-table :test #'equalp)) (session-messages (make-hash-table :test #'equalp)) (session-last-displayed-statuses nil)) (defun login (authenticatep &optional (username *username*) (password *password*)) "Sets the *USERNAME* and *PASSWORD* to USERNAME and PASSWORD respectively. Also authenticate the given USERNAME and PASSWORD using the verify_credentials service if AUTHENTICATEP is non-NIL. Also clears any existing session state." (setf *username* username *password* password *state* (make-session-state)) (when authenticatep (m-verify-credentials))) (defun logout () "Clear user information and session state." (setf *username* nil *password* nil *state* nil)) (defun forget-state () "Just clear the existing session state. Don't clear user authentication information." (setf *state* (make-session-state))) (defmacro with-session ((username password &key (authenticatep t)) &body body) "Authenticate the USERNAME and PASSWORD, and set up a fresh session state for this user. If AUTHENTICATEP is NIL, then don't automatically authenticate the credentials on twitter." `(let ((*username*) (*password*) (*state*)) , `(login ,authenticatep ,username ,password) ,@body)) (defun store-status (status) (setf (gethash (status-id status) (session-statuses *state*)) status)) (defun store-statuses (statuses) (dolist (status statuses statuses) (store-status status))) (defun store-message (message) (setf (gethash (message-id message) (session-messages *state*)) message)) (defun store-messages (messages) (dolist (message messages messages) (store-message message))) ;;; Status management helpers (defun get-newest-id (items) (when items (apply #'max (mapcar (compose #'parse-integer #'id) items)))) (defvar *default-page-size* 5 "Number of entries to show per page when displaying items.") (defvar *reverse-display-items-p* t "Default value for REVERSEP option to DISPLAY-ITEMS.") (defgeneric display-item (x stream n initialp finalp) (:documentation "Generic display function for cl-twit objects. X is the object to be displayed. STREAM is the output stream. N is the zero-indexed number of the item a list, if any. INITIALP indicates that X is the first item of the list. FINALP indicates that X is the last item of the list. Must be specialized for NULL, STATUS and MESSAGE.")) (defmethod display-item ((x null) stream n initialp finalp) (format stream "~&No items to display.~%")) (defmethod display-item ((status status) stream n initialp finalp) (when initialp (format stream "~&Status stream starts: ~%~%")) (format stream "~&#~A ~A (~A): ~A~%" n (user-name (status-user status)) (user-screen-name (status-user status)) (status-text status)) (format stream "~&~A~:[~; (truncated)~] at ~A from ~A~%~%" (status-id status) (status-truncated status) (status-created-at status) (status-source status)) (when finalp (format stream "~&Status stream ends.~%"))) (defmethod display-item ((message message) stream n initialp finalp) (when initialp (format stream "~&Message stream starts: ~%~%")) (format stream "~&~A to ~A: ~A~%" (message-sender-screen-name message) (message-recipient-screen-name message) (message-text message)) (format stream "~&~A at ~A~%~%" (message-id message) (message-created-at message)) (when finalp (format stream "~&Message stream ends.~%"))) (defun display-items (items stream &key (page *default-page-size*) (reversep *reverse-display-items-p*) &aux (n -1) (length (length items))) "Displays a list of ITEMS using DISPLAY-ITEM to output STREAM. PAGE, if non-NIL, should be the number of items to display per page. Its default value is *DEFAULT-PAGE-SIZE*. If REVERSEP is non-NIL, reverse the order of the items before displaying them. Its default value is *REVERSE-DISPLAY-ITEMS-P*." (when reversep (setf items (reverse items))) (labels ((!display-items (items &optional (initialp t)) (cond ((null items) (display-item nil stream 0 t t)) ((rest items) (display-item (first items) stream (incf n) initialp nil) (when (and page (/= n -1) (zerop (mod (1+ n) page))) (unless (y-or-n-p "~&Continue? --~A/~A--" (1+ n) length) (return-from display-items items))) (!display-items (rest items) nil)) (t (display-item (first items) stream (incf n) initialp t))))) (!display-items items) items)) (defun display-statuses (statuses stream) (display-items statuses stream) (setf (session-last-displayed-statuses *state*) (if *reverse-display-items-p* (reverse statuses) statuses))) (defun last-displayed-statuses () "Return the last status items displayed in this session." (session-last-displayed-statuses *state*)) (defun update (fmt &rest args) "Update your status. FMT is a FORMAT string, and ARGS are its corresponding arguments." (store-status (m-update (apply #'format nil fmt args)))) (defun find-status (id) "Find a particular status. If ID is a NUMBER, the (zero-based) index with for this position is checked for in the last displayed statuses, and if present, that status is returned. If no status is found at this position, an error is signalled. If ID is a string, a status with the same status-id as ID is searcehd for in the local cache. If it is not present locally, a CERROR is signalled. If the user chooses to continue, get the status from twitter." (etypecase id (number (or (nth id (session-last-displayed-statuses *state*)) (error 'twitter-simple-error :format-control "Can't find status #~A in last displayed statuses." :format-arguments (list id)))) (string (or (gethash id (session-statuses *state*)) (progn (cerror "Couldn't find status with ID locally. Ask twitter?" 'twitter-error) (store-status (ignore-errors (m-show id)))))))) (defun reply-to (id fmt &rest args) "Send a reply to a particular status with STATUS-ID. FMT and ARGS are the format-control string and args." (store-status (m-update (apply #'format nil fmt args) :in-reply-to-status-id (etypecase id (number (status-id (find-status id))) (string id))))) (defun @reply-to (id fmt &rest args) "Send a reply to a particular status with STATUS-ID. FMT and ARGS are the format-control string and args. This function prepends the @username of the status's sender to the final text." (let ((fmt (format nil "@~A ~A" (user-screen-name (status-user (find-status id))) fmt))) (reply-to id (apply #'format nil fmt args)))) (defun send-message (user fmt &rest args) "Send a direct message to USER (screenname or id) with format-controlled string FMT and ARGS." (m-messages-new user (apply #'format nil fmt args))) (defmacro update-newest-id (statuses place) ;; FIXME: We are broke if the ids don't remain numeric. ;; Shouldn't we use the created_at date instead? (let ((request-newest-id (gensym)) (place-id (gensym))) `(let* ((,request-newest-id (get-newest-id ,statuses)) (,place-id ,place)) (when (and ,request-newest-id (or (null ,place-id) (> ,request-newest-id ,place-id))) (setf ,place ,request-newest-id))))) (defun timeline (&key (since-id (friends-timeline-id *state*)) count page (stream *standard-output*)) "Retrieve the authenticating user's home timeline. Equivalent of /home on twitter. SINCE-ID should be the id of a status. COUNT (must be < 200) is the number of statuses to retrieve. PAGE is the page number to retrieve. STREAM should be the output stream (default *STANDARD-OUTPUT*). SINCE-ID is not checked when PAGE is non-NIL." (let ((statuses (m-friends-timeline :since-id (unless page since-id) :count count :page page))) (update-newest-id statuses (friends-timeline-id *state*)) (display-statuses statuses stream) (store-statuses statuses))) (defun user-timeline (user &key (since-id (gethash user (user-timeline-ids *state*))) count page (stream *standard-output*)) "Retrieve the USER's timeline. Equivalent to /username on twitter. If USER eql's :ME, get the timeline for authenticating user. SINCE-ID should be the id of a status. COUNT (must be < 200) is the number of statuses to retrieve. PAGE is the page number to retrieve. STREAM should be the output stream (default *STANDARD-OUTPUT*). SINCE-ID is not checked when PAGE is non-NIL." (let ((statuses (m-user-timeline :id (if (eql user :me) *username* user) :since-id (unless page since-id) :count count :page page))) (update-newest-id statuses (gethash user (user-timeline-ids *state*))) (display-statuses statuses stream) (store-statuses statuses))) (defun @replies (&key (since-id (replies-id *state*)) page (stream *standard-output*)) "Retrieve any @REPLIES for the authenticating user. SINCE-ID should be the id of a status. COUNT (must be < 200) is the number of statuses to retrieve. STREAM should be the output stream (default *STANDARD-OUTPUT*). SINCE-ID is not checked when PAGE is non-NIL." (let ((statuses (m-replies :since-id (unless page since-id) :page page))) (update-newest-id statuses (replies-id *state*)) (display-statuses statuses stream) (store-statuses statuses))) (defun messages (&key (since-id (messages-id *state*)) page (stream *standard-output*)) "Retrieve direct messages sent to the authenticating user. SINCE-ID should be the id of a status. PAGE is the page number to retrieve. STREAM should be the output stream (default *STANDARD-OUTPUT*). SINCE-ID is not checked when PAGE is non-NIL." (let ((messages (m-messages :since-id (unless page since-id) :page page))) (update-newest-id messages (messages-id *state*)) (display-items messages stream) (store-messages messages))) (defun sent-messages (&key (since-id (sent-messages-id *state*)) page (stream *standard-output*)) "Retrieves the direct messages sent by the authenticating user. SINCE-ID should be the id of a status. PAGE is the page number to retrieve. STREAM should be the output stream (default *STANDARD-OUTPUT*). SINCE-ID is not checked when PAGE is non-NIL." (let ((messages (m-messages-sent :since-id (unless page since-id) :page page))) (update-newest-id messages (sent-messages-id *state*)) (display-items messages stream) (store-messages messages))) ;;; TinyURL-ize ;;; Using the very simple TinyURL API (defparameter *tinyurl-url* "http://tinyurl.com/api-create.php") (defun get-tinyurl (url) "Get a TinyURL for the given URL. Uses the TinyURL API service." (multiple-value-bind (body status-code) (drakma:http-request *tinyurl-url* :parameters `(("url" . ,url))) (if (= status-code +http-ok+) body (error 'http-error :status-code status-code :url url :body body)))) ;;; Load customizations, if any ;;; Code thanks to asdf-install (eval-when (:load-toplevel :execute) (let* ((file (probe-file (merge-pathnames (make-pathname :name ".cl-twit.lisp") (truename (user-homedir-pathname)))))) (when file (load file))))
30,802
Common Lisp
.lisp
736
34.574728
97
0.636838
rheaplex/microblog-bot
2
0
0
AGPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
f39f360d08a230c0cf592aa830ef4171f0f8cc95fcd3067a9c219d3753cf1bf8
20,698
[ -1 ]
20,699
packages.lisp
rheaplex_microblog-bot/cl-twit/packages.lisp
;;; -*- Mode: LISP; Syntax: COMMON-LISP; Package: CL-USER; Base: 10 -*- ;;; packages.lisp ;;; Copyright (c) 2009, Chaitanya Gupta. ;;; All rights reserved. ;;; ;;; Redistribution and use in source and binary forms, with or without ;;; modification, are permitted provided that the following conditions ;;; are met: ;;; 1. Redistributions of source code must retain the above copyright ;;; notice, this list of conditions and the following disclaimer. ;;; 2. Redistributions in binary form must reproduce the above copyright ;;; notice, this list of conditions and the following disclaimer in the ;;; documentation and/or other materials provided with the distribution. ;;; 3. The name of the author may not be used to endorse or promote products ;;; derived from this software without specific prior written permission. ;;; ;;; THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR ;;; IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES ;;; OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. ;;; IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, ;;; INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT ;;; NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ;;; DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ;;; THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ;;; (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF ;;; THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. (cl:defpackage #:cl-twit (:use #:cl) (:nicknames #:twit) (:export ;; STATUS #:status #:status-created-at #:status-id #:status-text #:status-source #:status-truncated #:status-in-reply-to-status-id #:status-in-reply-to-user-id #:status-favorited #:status-user ;; USER #:user #:user-id #:user-name #:user-screen-name #:user-location #:user-description #:user-profile-image-url #:user-url #:user-protected #:user-followers-count ;; EXTENDED-USER #:extended-user #:user-profile-background-color #:user-profile-text-color #:user-profile-link-color #:user-profile-sidebar-fill-color #:user-profile-sidebar-border-color #:user-friends-count #:user-created-at #:user-favourites-count #:user-utc-offset #:user-time-zone #:user-profile-background-image-url #:user-profile-background-tile #:user-following #:user-notifications #:user-statuses-count ;; (Direct) MESSAGE #:message #:message-id #:message-sender-id #:message-text #:message-recipient-id #:message-created-at #:message-sender-screen-name #:message-recipient-screen-name #:message-sender #:message-recipient ;; RATE-LIMIT #:rate-limit #:rate-limit-reset-time #:rate-limit-reset-time-seconds #:rate-limit-remaining-hits #:rate-limit-hourly-limit ;; Errors #:twitter-error #:twitter-simple-error #:http-error #:http-status-code #:http-url #:http-body #:xml-error #:xml-error-reason #:xml-error-deadline #:xml-error-text ;; Twitter API methods #:m-public-timeline #:m-friends-timeline #:m-user-timeline #:m-show #:m-update #:m-replies #:m-destroy #:m-friends #:m-followers #:m-user-show #:m-messages #:m-messages-sent #:m-messages-new #:m-messages-destroy #:m-friendship-create #:m-friendship-destroy #:m-friendship-exists #:m-graph-friends #:m-graph-followers #:m-verify-credentials #:m-end-session #:m-update-delivery-device #:m-update-profile-colors #:m-update-profile-image #:m-update-profile-background-image #:m-rate-limit-status #:m-update-profile #:m-favorites #:m-favorites-create #:m-favorites-destroy #:m-follow #:m-leave #:m-block-create #:m-block-destroy #:m-test ;; Our convenience operators for interactive use #:*username* #:*password* #:login #:logout #:forget-state #:with-session #:update #:find-status #:reply-to #:@reply-to #:send-message #:*default-page-size* #:*reverse-display-items-p* #:display-item #:display-items #:last-displayed-statuses #:timeline #:user-timeline #:@replies #:messages #:sent-messages ;; TinyURL API client #:get-tinyurl))
4,389
Common Lisp
.lisp
157
24.458599
77
0.699929
rheaplex/microblog-bot
2
0
0
AGPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
bb560f61fb480e7ca2997ce4b956015158946e75897f12a5ed992c92beced2e7
20,699
[ 330702 ]
20,700
microblog-bot.asd
rheaplex_microblog-bot/microblog-bot.asd
;; microblog-bot.asd - The system definition(s) for microblog-bot. ;; Copyright (C) 2009 Rob Myers [email protected] ;; ;; This program is free software: you can redistribute it and/or modify ;; it under the terms of the GNU Affero General Public License as ;; published by the Free Software Foundation, either version 3 of the ;; License, or (at your option) any later version. ;; ;; This program is distributed in the hope that it will be useful, ;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;; GNU Affero General Public License for more details. ;; ;; You should have received a copy of the GNU Affero General Public License ;; along with this program. If not, see <http://www.gnu.org/licenses/>. (defpackage microblog-bot-system (:use #:cl #:asdf)) (in-package :microblog-bot-system) (defsystem "microblog-bot" :depends-on (#:cl-twit) :serial t :components ((:file "package") (:file "utilities") (:file "microblog-user") (:file "microblog-bot") (:file "microblog-follower-bot") (:file "daily-task-bot") (:file "intermittent-task-bot") (:file "constant-task-bot") (:file "testing")))
1,247
Common Lisp
.asd
29
39.517241
75
0.70477
rheaplex/microblog-bot
2
0
0
AGPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
a2fc712b3b77765f4a22f1518f2518baf5b003dec904e6a083af32c38be502ef
20,700
[ -1 ]
20,701
cl-twit.asd
rheaplex_microblog-bot/cl-twit/cl-twit.asd
;;; -*- Mode: LISP; Syntax: COMMON-LISP; Package: CL-USER; Base: 10 -*- ;;; cl-twit.asd ;;; Copyright (c) 2009, Chaitanya Gupta. ;;; All rights reserved. ;;; ;;; Redistribution and use in source and binary forms, with or without ;;; modification, are permitted provided that the following conditions ;;; are met: ;;; 1. Redistributions of source code must retain the above copyright ;;; notice, this list of conditions and the following disclaimer. ;;; 2. Redistributions in binary form must reproduce the above copyright ;;; notice, this list of conditions and the following disclaimer in the ;;; documentation and/or other materials provided with the distribution. ;;; 3. The name of the author may not be used to endorse or promote products ;;; derived from this software without specific prior written permission. ;;; ;;; THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR ;;; IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES ;;; OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. ;;; IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, ;;; INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT ;;; NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ;;; DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ;;; THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ;;; (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF ;;; THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. (asdf:defsystem #:cl-twit :depends-on (:cxml-stp :drakma) :serial t :components ((:file "packages") (:file "classes") (:file "cl-twit")))
1,755
Common Lisp
.asd
32
52.625
77
0.736934
rheaplex/microblog-bot
2
0
0
AGPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
40a19894694ca6a57fc3531acea05a315b97cce54bf3fdedc241a78efc7d8485
20,701
[ 285126 ]
20,718
cl-twit.texinfo
rheaplex_microblog-bot/cl-twit/doc/cl-twit.texinfo
\input texinfo @c -*-texinfo-*- @c %**start of header @setfilename cl-twit.info @settitle cl-twit @c %**end of header @copying Copyright @copyright{} 2009 Chaitanya Gupta @end copying @titlepage @title cl-twit @author Chaitanya Gupta @end titlepage @ifnottex @node Top @top Introduction @end ifnottex @insertcopying cl-twit is meant for that small bunch of Common Lisp programmers with lots and lots of free time on their hands who also use Twitter. It implements wrappers for nearly all the methods provided by Twitter's @uref{http://apiwiki.twitter.com/REST+API+Documentation,REST API}, but is particularly focussed towards those tasks which a Twitter user would encounter in his daily usage (get latest tweets, send update, reply to a particular tweet, etc.). It comes with a @uref{http://www.opensource.org/licenses/bsd-license.php,BSD-style license}. If you want to send feedback or comments, send an email to @code{mail at chaitanyagupta.com}, or ping @code{@@chaitanya_gupta} on Twitter. @menu * Download and installation:: * .cl-twit.lisp:: * Authentication and state:: * Status messages:: * Direct messages:: * Tiny URLs:: * Further documentation:: * The future:: @end menu @node Download and installation @chapter Download and installation cl-twit depends on the following two libraries: @itemize @item @uref{http://weitz.de/drakma,Drakma} --- An HTTP client @c TODO: Fix the URL below: @item @uref{http://www.lichteblau.com/cxml-stp/,cxml-stp} --- An XML parser @end itemize Download the source from git: @example git clone git://github.com/chaitanyagupta/cl-twit.git @end example Or, you can grab a tarball from the following URL (click on ``download''): @uref{http://github.com/chaitanyagupta/cl-twit/tree/master} After the download, symlink cl-twit.asd into your @code{ASDF:*CENTRAL-REGISTRY*} (or use whatever custom ASD loading mechanism you use) and you should be ready to go: @lisp (asdf:oos 'asdf:load-op :cl-twit) @end lisp @node .cl-twit.lisp @chapter .cl-twit.lisp The contents of the file ~/.cl-twit.lisp, if it exists, are @code{READ} after cl-twit has been loaded. I usually use it to set my twitter username and password. @lisp (setf twit:*username* "chaitanya_gupta") (setf twit:*password* "password") @end lisp @node Authentication and state @chapter Authentication and state Before you can use any other API functions, you need to login: @lisp ;; If the first argument is non-NIL, a verify_credentials call is made ;; to twitter. The username and password are assumed to be ;; twit:*username* and twit:*password* by default. (twit:login t) ;; You can also explicitly specify the username and password using ;; twit:login (twit:login t "username" "password") @end lisp Use @code{(twit:forget-state)} to forget the current session state. This will clear the last noticed status/message ids for functions like @code{timeline}, @code{messages}, etc. @code{(twit:logout)} will also clear the username and password. @code{(twit:m-rate-limit-status)} returns a rate-limit object which gives the number of hits remaining this hour, the reset time for the rate limit counter, etc. @node Status messages @chapter Status messages To see your latest updates (equivalent to /home on twitter), enter @lisp (twit:timeline) ;; See just the five latest updates (twit:timeline :count 5) @end lisp To see a user's timeline (equivalent to a user's profile page), @lisp (twit:user-timeline "username") @end lisp To create a new update, @lisp (twit:update "My latest tweet!") @end lisp To see the latest @@replies sent to you, @lisp (twit:@@replies) @end lisp @code{(twit:last-displayed-statuses)} displays the list of statuses returned by the last call to either @code{twit:timeline}, @code{twit:user-timeline} or @code{twit:@@replies}. To reply to a particular status, use reply-to or @@reply-to. Note that the message string is used as a @code{format} control string. The corresponding @code{format} args can be passed as the rest args to these functions. @lisp ;; reply to the 3rd status from the last displayed list of statuses (twit:reply-to 2 "@@username Here, have your reply!") ;; reply to the status with status-id "123456789" (twit:reply-to "123456789" "@@username Here, have your reply!") ;; @@reply-to automatically determines the screenname of the sender of ;; the status being replied to, and prepends it to the text ;; When using @@reply-to, the status text below is transformed to ;; "@@username Here, have your reply!" (twit:@@reply-to "123456789" "Here, have your reply!") @end lisp @node Direct messages @chapter Direct messages To see the latest direct (private) messages sent to you, @lisp (twit:messages) @end lisp To see the latest direct messages sent by you, @lisp (twit:sent-messages) @end lisp To send a direct message to a user who is your ``friend'', @lisp (twit:send-message "username" "Some message.") @end lisp @node Tiny URLs @chapter Tiny URLs To get the @uref{http://tinyurl.com,TinyURL} of a URL, use @code{get-tinyurl}. This can be used with @code{update}, @code{reply-to}, @code{@@reply-to}, or @code{send-message}. All these functions actually take a @code{format} controlled string as the last required argument, and its corresponding args as the rest args to this string. @lisp ;; Returns a string containing the TinyURL of the given URL. (twit:get-tinyurl "http://chaitanyagupta.com") ;; Using get-tinyurl with update (twit:update "This is a cool place: ~A" (twit:get-tinyurl "http://common-lisp.net")) @end lisp @node Further documentation @chapter Further documentation The package @code{cl-twit} (nickname @code{twit}) exports a lot of symbols. Here's a brief summary: @itemize @item @code{*username*} and @code{*password*} are bound to the username and password for the current user. @item All the @code{status-*, user-*, message-*, rate-limit-*} are our object accessors. @item @code{twitter-error, twitter-simple-error, http-error, xml-error} are our error conditions. @item @code{*default-page-size*} is the number of items to display per page. It can also be @code{NIL}. @item @code{*reverse-display-items-p*}, if non-NIL (default @code{T}), reverses the items from the order in which they were received from Twitter, before displaying them. This makes it easier to view the items in ``converstation-style'', so that replies show up after the original status. @item All the @code{m-*} functions are the wrappers over actual API calls to twitter. You can directly use these functions if none of the 'convenience' functions provide what you need. @item The rest are convenience functions to ease with using the Twitter API in the REPL. Check out their docstrings for more info. @end itemize @node The future @chapter The future If the author has enough time on his hands, and provided he still finds cl-twit useful, it might get a persistent backend (using clsql). Minor changes to cl-twit based on the author's usage patterns should keep coming in. @bye
6,982
Common Lisp
.l
158
42.753165
539
0.774981
rheaplex/microblog-bot
2
0
0
AGPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
a3f2d761d26e29c0085c6b9a3aed358d31524d8df4247c06ab8dbe59c22440d6
20,718
[ -1 ]
20,719
Makefile
rheaplex_microblog-bot/cl-twit/doc/Makefile
all: cl-twit.info manual cl-twit.info: cl-twit.texinfo makeinfo cl-twit.texinfo manual: cl-twit.texinfo makeinfo --html -o manual cl-twit.texinfo
149
Common Lisp
.l
5
28.2
42
0.797203
rheaplex/microblog-bot
2
0
0
AGPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
201a22c5046472f0959364c86a1323f04fe8a7565bead182189cf6aca9cbb8d1
20,719
[ -1 ]
20,734
clcv.lisp
sparkecho_clcv/clcv.lisp
;;;; clcv.lisp (uiop/package:define-package :clcv/clcv (:nicknames :clcv) (:use :common-lisp) (:export #:clcv) (:use-reexport :clcv/core/all :clcv/matrix/all :clcv/dip/all :clcv/gui/all :clcv/io/all :clcv/ml/all :clcv/graphics/all)) (in-package #:clcv) (defun clcv () (format t "CLCV~%")) (provide "clcv") (provide "CLCV")
443
Common Lisp
.lisp
17
18
39
0.521429
sparkecho/clcv
2
0
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
51e18cff3763484fc320eee9fb00f46554289178d1dd370bfba8685bfb58b157
20,734
[ -1 ]
20,735
hello.lisp
sparkecho_clcv/test/hello.lisp
(uiop/package:define-package :clcv/test/hello (:use :common-lisp) (:export #:hello)) (in-package :clcv/test/hello) (defun hello () "Hello from clcv/test/hello")
170
Common Lisp
.lisp
6
25.833333
45
0.714286
sparkecho/clcv
2
0
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
4ba5596f65ad90bd2ba6ce3e51b959099bdc262e4078de999f5b5b3464be7d2f
20,735
[ -1 ]
20,736
all.lisp
sparkecho_clcv/test/all.lisp
(uiop/package:define-package :clcv/test/all (:nicknames :clcv-test) (:use :common-lisp) (:use-reexport :clcv/test/hello)) (provide "clcv-test") (provide "CLCV-TEST")
176
Common Lisp
.lisp
6
26.666667
43
0.708333
sparkecho/clcv
2
0
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
70c7df6bfe5b86c065962b9066c494edd011eba6ed11ed6983caecf7c27bfe90
20,736
[ -1 ]
20,737
imageops.lisp
sparkecho_clcv/dip/imageops.lisp
(uiop/package:define-package :clcv/dip/imageops (:use :common-lisp :clcv/core/all) (:import-from :opticl-core #:with-image-bounds #:pixel #:pixel* #:do-pixels #:set-region-pixels) (:export #:imadd #:imsub)) (in-package :clcv/dip/imageops) (declaim (inline bound+ bound-)) (defun bound+ (number1 number2 &optional (max-val 255)) (min (+ number1 number2) max-val)) (defun bound- (number1 number2 &optional (min-val 0)) (max (- number1 number2) min-val)) ;; (defgeneric imadd (object1 object2) ;; (:documentation "Add up two images or add a constant to an image.")) ;; (defmethod imadd ((object1 array) (object2 array)) ;; (defun imadd (object1 object2) ;; (with-image-bounds (height1 width1 channels1) ;; object1 ;; (with-image-bounds (height2 width2 channels2) ;; object2 ;; (assert (and (= height1 height2) (= width1 width2) ;; (eql channels1 channels2)) ;; nil "Atempt to add two images with different size") ;; (let ((image (make-image height1 width1 (image-type object1)))) ;; (do-pixels (i j) ;; image ;; (setf (pixel* image i j) (mapcar #'bound+ ;; (pixel* object1 i j) ;; (pixel* object2 i j)))) ;; image)))) (defun imadd (image1 image2) (with-image-bounds (height1 width1 channels1) image1 (with-image-bounds (height2 width2 channels2) image2 (assert (and (= height1 height2) (= width1 width2) (eql channels1 channels2)) nil "Atempt to add two images with different size") (let ((image (make-image height1 width1 (image-type image1)))) (do-pixels (i j) image (setf (pixel* image i j) (mapcar #'bound+ (pixel* image1 i j) (pixel* image2 i j)))) image)))) (defun imsub (image1 image2) (with-image-bounds (height1 width1 channels1) image1 (with-image-bounds (height2 width2 channels2) image2 (assert (and (= height1 height2) (= width1 width2) (eql channels1 channels2)) nil "Atempt to add two images with different size") (let ((image (make-image height1 width1 (image-type image1)))) (do-pixels (i j) image (setf (pixel* image i j) (mapcar #'bound- (pixel* image1 i j) (pixel* image2 i j)))) image))))
2,702
Common Lisp
.lisp
65
32.815385
73
0.537348
sparkecho/clcv
2
0
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
d254db6f90cb94db0411b7cb22f51ff2c1dabc5e882d48b71de5526be6cbe64d
20,737
[ -1 ]
20,738
color.lisp
sparkecho_clcv/dip/color.lisp
(uiop/package:define-package :clcv/dip/color (:use :common-lisp :clcv/core/all) (:import-from :opticl-core #:with-image-bounds #:pixel #:do-pixels) (:export #:convert-color)) (in-package :clcv/dip/color) (defgeneric convert-color (image flag) (:documentation "Convert image from a color space to another color space.")) ;;; Convert a RGB image to a grayscale image. (defmethod convert-color (image (flag (eql :rgb2gray))) (with-image-bounds (height width) image (let ((gray-image (make-image height width '8uc1))) (declare (type 8uc1 gray-image) (type 8uc3 image)) (do-pixels (i j) image (multiple-value-bind (r g b) (pixel image i j) (setf (pixel gray-image i j) (round (+ (* r 0.2989) (* g 0.5870) (* b 0.1140)))))) gray-image))) ;;; Convert a grayscale image to rgb image. (defmethod convert-color (image (flag (eql :gray2rgb))) (with-image-bounds (height width) image (let ((rgb-image (make-image height width '8uc3))) (declare (type 8uc1 image) (type 8uc3 rgb-image)) (do-pixels (i j) image (let ((grayscale (pixel image i j))) (setf (pixel rgb-image i j) (values grayscale grayscale grayscale)))) rgb-image))) (defmethod convert-color (image (flag (eql :rgb2ycbcr))) (with-image-bounds (height width) image (let ((ycbcr-image (make-image height width '8uc3)) (delta 128)) (declare (type 8uc3 ycbcr-image) (type 8uc3 image)) (flet ((to-ycbcr (r g b delta) (let ((y (round (+ (* r 0.299) (* g 0.587) (* b 0.114))))) (values y (round (+ (* (- b y) 0.564) delta)) (round (+ (* (- r y) 0.713) delta)))))) (do-pixels (i j) image (multiple-value-bind (r g b) (pixel image i j) (setf (pixel ycbcr-image i j) (to-ycbcr r g b delta))))) ycbcr-image))) (defmethod convert-color (image (flag (eql :ycbcr2rgb))) (with-image-bounds (height width) image (let ((rgb-image (make-image height width '8uc3)) (delta 128)) (declare (type 8uc3 image) (type 8uc3 rgb-image)) (labels ((normalize (val) (if (> val 255) 255 val)) (to-rgb (y cb cr delta) (let ((cb-delta (- cb delta)) (cr-delta (- cr delta))) (let ((r (round (+ y (* 1.403 cr-delta)))) (g (round (- y (* 0.714 cr-delta) (* 0.344 cb-delta)))) (b (round (+ y (* 1.773 cb-delta))))) (values (normalize r) (normalize g) (normalize b)))))) (do-pixels (i j) image (multiple-value-bind (y cb cr) (pixel image i j) (setf (pixel rgb-image i j) (to-rgb y cb cr delta))))) rgb-image)))
3,312
Common Lisp
.lisp
88
25.375
80
0.480548
sparkecho/clcv
2
0
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
22840b79f056a3cf9e18988b80889cab9e267cdf602143408c1fa319e1b0f4da
20,738
[ -1 ]
20,739
arrayops.lisp
sparkecho_clcv/dip/arrayops.lisp
(uiop/package:define-package :clcv/dip/arrayops (:use :common-lisp) (:import-from :opticl-core #:with-image-bounds #:copy-array) (:export #:split-image #:extract-channel #:merge-channels #:merge-channel-list)) (in-package :clcv/dip/arrayops) ;;; Split each channel of an image into an 2d array (defun split-image (image) (with-image-bounds (height width channels) image (declare (ignore height width)) (if channels (loop for i from 0 below channels collect (extract-channel image i)) (list (copy-array image))))) ;;; Extract a specific channel from image (defun extract-channel (image channel-index) (with-image-bounds (height width) image (let ((channel (make-array (list height width) :element-type (array-element-type image)))) (dotimes (i height) (dotimes (j width) (setf (aref channel i j) (aref image i j channel-index)))) channel))) ;;; Merge several channels into an image (defun merge-channels (channel &rest channels) (merge-channel-list (cons channel channels))) (defun merge-channel-list (channels) (let ((num (length channels))) (if (= num 1) (copy-array channels) (with-image-bounds (height width) (car channels) (let ((image (make-array (list height width num) :element-type (array-element-type (car channels))))) (loop for e in channels for k = 0 then (+ k 1) do (dotimes (i height) (dotimes (j width) (setf (aref image i j k) (aref e i j))))) image)))))
1,752
Common Lisp
.lisp
46
28.804348
87
0.583972
sparkecho/clcv
2
0
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
9bc53d93293681e2ce747d8681a85df6be4a786fc4c12a605154027e061ad4f1
20,739
[ -1 ]
20,740
all.lisp
sparkecho_clcv/dip/all.lisp
(uiop/package:define-package :clcv/dip/all (:nicknames :clcv-dip) (:use :common-lisp) (:use-reexport :clcv/dip/arrayops :clcv/dip/imageops :clcv/dip/geometry :clcv/dip/color)) (provide "clcv-dip") (provide "CLCV-DIP")
279
Common Lisp
.lisp
9
23.222222
42
0.593284
sparkecho/clcv
2
0
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
7b26ff49012da066ba4bce0195bd3e7985a96c6afdfb2c66f658b86b40b74dc0
20,740
[ -1 ]
20,741
geometry.lisp
sparkecho_clcv/dip/geometry.lisp
(uiop/package:define-package :clcv/dip/geometry (:use :common-lisp :clcv/core/all) (:import-from :opticl-core #:with-image-bounds #:pixel #:do-pixels #:set-region-pixels) (:export #:crop #:copyf)) (in-package :clcv/dip/geometry) (defun crop (image y1 x1 y2 x2) (with-image-bounds (height width channels) image (declare (ignore height width)) (let ((new-rows (- y2 y1)) (new-cols (- x2 x1))) (let ((new-image (make-array (cons new-rows (cons new-cols (when channels (list channels)))) :element-type (array-element-type image)))) (loop for i-src from y1 below y2 for i-dest below new-rows do (loop for j-src from x1 below x2 for j-dest below new-cols do (setf (pixel new-image i-dest j-dest) (pixel image i-src j-src)))) new-image)))) ;;; Repeat `value' `number' times, to from a multiple value (defun repeat (value number) (values-list (loop for i fixnum from 0 below number collect value))) (defun copyf (src-image dst-image &key (y 0) (x 0) point) (flet ((copy-to% (src-image dst-image y x) (with-image-bounds (src-h src-w src-c) src-image (with-image-bounds (dst-h dst-w dst-c) dst-image (cond ((= src-c dst-c) (set-region-pixels (i j y x (min (+ src-h y) dst-h) (min (+ src-w x) dst-w)) dst-image (pixel src-image (- i y) (- j x)))) (t (cond ((= src-c 1) (set-region-pixels (i j y x (min (+ src-h y) dst-h) (min (+ src-w x) dst-w)) dst-image (repeat (pixel src-image (- i y) (- j x)) dst-c))) (t (dotimes (k (min src-c dst-c)) (loop for i fixnum from y below (min (+ src-h y) dst-h) do (loop for j fixnum from x below (min (+ src-w x) dst-w) do (setf (aref dst-image i j k) (aref src-image (- i y) (- j x) k))))))))))))) (cond ((null point) (copy-to% src-image dst-image y x)) (t (copy-to% src-image dst-image (point-x point) (point-y point))))))
2,751
Common Lisp
.lisp
55
30.818182
99
0.428094
sparkecho/clcv
2
0
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
001fdc9c4eacf8612392a8cbcb8829d20b08004ed5aa0142854f6e8b406db741
20,741
[ -1 ]
20,742
image.lisp
sparkecho_clcv/io/image.lisp
(uiop/package:define-package :clcv/io/image (:use :common-lisp :clcv-core) (:import-from :opticl #:read-image-file #:write-image-file) (:export #:imread #:imwrite)) (in-package :clcv/io/image) (defun imread (file &optional option) (declare (ignore option)) (read-image-file file)) (defun imwrite (file image &optional option) (declare (ignore option)) (write-image-file file image))
447
Common Lisp
.lisp
14
26.357143
44
0.654206
sparkecho/clcv
2
0
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
9501c38c92761e75751311f656cb68386fb051112f14c183e2ab48ec99678491
20,742
[ -1 ]
20,743
all.lisp
sparkecho_clcv/io/all.lisp
(uiop/package:define-package :clcv/io/all (:nicknames :clcv-io) (:use :common-lisp) (:use-reexport :clcv/io/image)) (provide "clcv-io") (provide "CLCV-IO")
166
Common Lisp
.lisp
6
25
41
0.689873
sparkecho/clcv
2
0
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
08f2186a3bc97f73cab73e1ce2a36f72cc92df16b0e0767d4141db77d3bd6cb3
20,743
[ -1 ]
20,744
imshow.lisp
sparkecho_clcv/gui/imshow.lisp
(uiop/package:define-package :clcv/gui/imshow (:use :common-lisp) (:import-from :sdl2 #:with-init #:with-window #:with-renderer #:set-render-draw-color #:render-draw-point #:render-present #:with-event-loop #:scancode= #:scancode-value #:push-event #:delay) (:import-from :opticl #:with-image-bounds #:pixel) (:export #:imshow)) (in-package :clcv/gui/imshow) (declaim (inline put-pixel)) (defun put-pixel (renderer x y r g b a) (set-render-draw-color renderer r g b a) (render-draw-point renderer x y)) (defun imshow (image &key (title "") (delay-time 300) (display-channel t)) "Display the given image on the screen." (bt:make-thread (lambda () (with-init (:video) (with-image-bounds (height width channels) image (with-window (window :title title :w width :h height :flags '(:shown)) (with-renderer (renderer window :flags '(:renderer-accelerated)) (cond ;; gray scale image ((null channels) (case display-channel (:r (dotimes (y height) (dotimes (x width) (let ((grayscale (pixel image y x))) (put-pixel renderer x y grayscale 0 0 255))))) (:g (dotimes (y height) (dotimes (x width) (let ((grayscale (pixel image y x))) (put-pixel renderer x y 0 grayscale 0 255))))) (:b (dotimes (y height) (dotimes (x width) (let ((grayscale (pixel image y x))) (put-pixel renderer x y 0 0 grayscale 255))))) (:a (dotimes (y height) (dotimes (x width) (let ((grayscale (pixel image y x))) (put-pixel renderer x y 0 0 0 grayscale))))) (otherwise (dotimes (y height) (dotimes (x width) (let ((grayscale (pixel image y x))) (put-pixel renderer x y grayscale grayscale grayscale 255))))))) ;; rgb image / rgba image (t (dotimes (y height) (dotimes (x width) (multiple-value-bind (r g b a) (pixel image y x) (put-pixel renderer x y r g b (or a 255))))))) (render-present renderer) (with-event-loop (:method :poll) (:keyup (:keysym keysym) (when (scancode= (scancode-value keysym) :scancode-escape) (push-event :quit))) (:idle () (delay delay-time)) (:quit () t)))))))))
3,100
Common Lisp
.lisp
72
26.125
86
0.446245
sparkecho/clcv
2
0
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
a765ad6e8a97f0bf3f9002150255ed8bcfb527dadb0df8ebedb47c620af3fe40
20,744
[ -1 ]
20,745
all.lisp
sparkecho_clcv/gui/all.lisp
(uiop/package:define-package :clcv/gui/all (:nicknames :clcv-gui) (:use :common-lisp) (:use-reexport :clcv/gui/imshow)) (provide "clcv-gui") (provide "CLCV-GUI")
172
Common Lisp
.lisp
6
26
42
0.70122
sparkecho/clcv
2
0
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
fdf4ec1bdecfd2e24646417c83f83dfd10b020669eb8b7a6e9f8f99199311c75
20,745
[ -1 ]
20,746
image.lisp
sparkecho_clcv/core/image.lisp
(uiop/package:define-package :clcv/core/image (:use :common-lisp) (:export #:image #:gray-image #:rgb-image #:rgba-image #:make-image #:image-type #:define-image-type #:image-height #:image-width #:image-rows #:image-cols #:image-channels #:1uc1 #:2uc1 #:4uc1 #:4uc3 #:4uc4 #:8uc1 #:8uc2 #:8uc3 #:8uc4 #:8sc1 #:8sc2 #:8sc3 #:8sc4 #:16uc1 #:16uc2 #:16uc3 #:16uc4 #:16sc1 #:16sc2 #:16sc3 #:16sc4 #:32uc1 #:32uc2 #:32uc3 #:32uc4 #:32sc1 #:32sc2 #:32sc3 #:32sc4 #:fnc1 #:fnc2 #:fnc3 #:fnc4 #:sfc1 #:sfc2 #:sfc3 #:sfc4 #:dfc1 #:dfc2 #:dfc3 #:dfc4)) (in-package :clcv/core/image) (deftype image (&optional element-type channels) `(simple-array ,element-type ,(if (numberp channels) (if (= channels 1) `(* *) `(* * ,channels)) channels))) (deftype gray-image (&optional element-type) `(simple-array ,element-type (* *))) (deftype rgb-image (&optional element-type) `(simple-array ,element-type (* * 3))) (deftype rgba-image (&optional element-type) `(simple-array ,element-type (* * 4))) (defgeneric make-image (height width type) (:documentation "Generate an `height' * `width' image of type `type'")) ;;; `type' is a list contains two elements, the first is number of channels ;;; and the second element is the element-type of array. (defmethod make-image (height width (type list)) (let ((channels (first type))) (make-array (if (= channels 1) (list height width) (list height width channels)) :element-type (second type)))) (defmacro define-image-type (name &optional channels (element-type t)) "Defines a new image type. Under the covers, this results in evaluation of the appropriate deftype and make-my-image-type constructor functions. Returns the name of the created type (i.e. name)." (let ((type (read-from-string (format nil "~A" name)))) `(progn (deftype ,type () `(image ,(or ',element-type '*) ,(or ,channels '*))) (defmethod make-image (height width (type (eql ',type))) (make-array (if (or (null ,channels) (= ,channels 1)) `(,height ,width) `(,height ,width ,,channels)) :element-type ',element-type)) ',type))) (eval-when (:compile-toplevel :load-toplevel :execute) (defparameter *image-types* '((1uc1 1 (unsigned-byte 1)) (2uc1 1 (unsigned-byte 2)) (4uc1 1 (unsigned-byte 4)) (4uc3 3 (unsigned-byte 4)) (4uc4 4 (unsigned-byte 4)) (8uc1 1 (unsigned-byte 8)) (8uc2 2 (unsigned-byte 8)) (8uc3 3 (unsigned-byte 8)) (8uc4 4 (unsigned-byte 8)) (8sc1 1 (signed-byte 8)) (8sc2 2 (signed-byte 8)) (8sc3 3 (signed-byte 8)) (8sc4 4 (signed-byte 8)) (16uc1 1 (unsigned-byte 16)) (16uc2 2 (unsigned-byte 16)) (16uc3 3 (unsigned-byte 16)) (16uc4 4 (unsigned-byte 16)) (16sc1 1 (signed-byte 16)) (16sc2 2 (signed-byte 16)) (16sc3 3 (signed-byte 16)) (16sc4 4 (signed-byte 16)) (32uc1 1 (unsigned-byte 32)) (32uc2 2 (unsigned-byte 32)) (32uc3 3 (unsigned-byte 32)) (32uc4 4 (unsigned-byte 32)) (32sc1 1 (signed-byte 32)) (32sc2 2 (signed-byte 32)) (32sc3 3 (signed-byte 32)) (32sc4 4 (signed-byte 32)) (fnc1 1 fixnum) (fnc2 2 fixnum) (fnc3 3 fixnum) (fnc4 4 fixnum) (sfc1 1 single-float) (sfc2 2 single-float) (sfc3 3 single-float) (sfc4 4 single-float) (dfc1 1 double-float) (dfc2 2 double-float) (dfc3 3 double-float) (dfc4 4 double-float)))) ;; to define a new image type one could do: ;; (define-image-type rational-gray-image :channels 1 :element-type rational) (macrolet ((frobber () `(progn ,@(loop for image-spec in *image-types* collect (destructuring-bind (name channels element-type) image-spec `(define-image-type ,name ,channels ,element-type)))))) (frobber)) (defun image-type (image) (let ((element-type (array-element-type image)) (channels (case (array-rank image) (2 1) (3 (array-dimension image 2)) (otherwise (error "Argument is not a legal image."))))) (let ((prefix (if (listp element-type) (format nil "~A~A" (second element-type) (case (first element-type) (unsigned-byte "U") (signed-byte "S") (otherwise (error "Unsupported type ~A." element-type)))) (case element-type (fixnum "FN") (single-float "SF") (double-float "DF") (otherwise (error "Unsupported type ~A." element-type)))))) (prog1 (read-from-string (format nil "~AC~A" prefix channels)))))) (declaim (inline image-height image-width image-rows image-cols image-channels)) (defun image-height (image) (array-dimension image 0)) (defun image-width (image) (array-dimension image 1)) (defun image-rows (image) (array-dimension image 0)) (defun image-cols (image) (array-dimension image 1)) (defun image-channels (image) (case (array-rank image) (2 1) (3 (array-dimension image 2)) (otherwise (error "Invalid image as parameter."))))
6,242
Common Lisp
.lisp
183
23.661202
80
0.519914
sparkecho/clcv
2
0
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
e58154610d8d6416292f1569193585901de766b5b883bfbe74817ce4bed4f72e
20,746
[ -1 ]
20,747
array.lisp
sparkecho_clcv/core/array.lisp
(uiop/package:define-package :clcv/core/array (:use :common-lisp) (:export #:marray #:reshape #:copy-array #:copy-to)) (defun decode-type-specifier (type-specifier) (let* ((str (symbol-name type-specifier)) (end (1- (length str)))) (case (char str end) (#\U (if (> end 0) (list 'unsigned-byte (parse-integer str :start 0 :end end)) 'unsigned-byte)) (#\S (if (> end 0) (list 'signed-byte (parse-integer str :start 0 :end end)) 'signed-byte)) (#\F (if (> end 0) (progn (assert (= (1- end) 0) nil "Unsupported type specifier ~A." type-specifier) (case (char str (1- end)) (#\S 'single-float) (#\D 'double-float) (otherwise (error "Unsupported type specifier ~A." type-specifier)))) 'float)) (otherwise (error "Unsupported type specifier ~A." type-specifier))))) (defun array-type (arr) (let ((etype (array-element-type arr))) (if (listp etype) (intern (format nil "~A~A" (second etype) (ecase (first etype) (unsigned-byte #\U) (signed-byte #\S))) "KEYWORD") (ecase etype (float :f) (single-float :sf) (double-float :df))))) (defun marray (rows cols &optional (channels 1) (type-specifier :8u) value) (%marray rows cols channels (decode-type-specifier type-specifier) value)) (defun %marray (rows cols channels element-type value) (let ((dimensions (if (= channels 1) (list rows cols) (list rows cols channels)))) (typecase value (null (make-array dimensions :element-type element-type)) (number (assert (typep value element-type) nil "Initial value ~A is not of given type :~A." value element-type) (make-array dimensions :element-type element-type :initial-element value)) (vector (assert (> channels 1) nil "You should use this form of initialization only when channels >= 2.") (assert (= (length value) channels) nil "Initial value vector's size does not match channel number.") (let* ((arr (make-array dimensions :element-type element-type)) (vec (array-storage-vector arr)) (size (* rows cols channels))) ;; (dotimes (i channels) ;; (let ((val (aref value i))) ;; (loop for j from i below size by channels ;; do (setf (aref vec j) val)))) (loop for i below channels for val = (aref value i) do (loop for j from i below size by channels do (setf (aref vec j) val))) arr)) (list (assert (= (length value) channels) nil "Initial value list's size does not match channel number.") (let* ((arr (make-array dimensions :element-type element-type)) (vec (array-storage-vector arr)) (size (* rows cols channels))) (loop for i below channels for val = (pop value) do (loop for j from i below size by channels do (setf (aref vec j) val))) arr)) (otherwise (error "Unsupported initial form."))))) (defun reshape (arr rows cols &optional (channels 1)) (assert (= (array-total-size arr) (* rows cols channels)) nil "Number of elements does not equal.") (let ((dimensions (cond ((and (= rows 1) (= channels 1)) cols) ((= channels 1) (list rows cols)) ((= rows 1) (list cols channels)) (t (list rows cols channels))))) (make-array dimensions :element-type (array-element-type arr) :displaced-to arr))) (defun copy-array (arr) (let* ((val (make-array (array-dimensions arr) :element-type (array-element-type arr)))) (loop for i below (array-total-size arr) do (setf (row-major-aref val i) (row-major-aref arr i))) val)) ;; Add error check for parameter's dimensions (defun copy-to (src dst &optional mask) (if (null mask) (loop for i below (array-total-size src) do (setf (row-major-aref dst i) (row-major-aref src i))) (cond ((= (array-rank src) 2) (loop for i below (array-total-size src) do (setf (row-major-aref dst i) (logand (row-major-aref src i) (row-major-aref mask i))))) ((= (array-rank src) 3) (loop for i below (array-dimension src 0) do (loop for j below (array-dimension src 1) do (loop for k below (array-dimension src 2) do (setf (aref dst i j k) (logand (aref src i j k) (aref mask i j))))))) (t (error "Array has a rank > 3 is not supported right now."))))) (defun channels (arr) (if (< (array-rank arr) 3) 1 (array-dimension arr 2))) (defun cross (arr)) (defun dot (arr)) (defun diag (arr)) (defun for-each (arr fn) (let ((vec (array-storage-vector arr))))) (defun resize (arr)) (defun row (arr)) (defun col (arr)) (defclass array2d () ((rows :initarg :rows :reader rows :type unsigned-byte) (cols :initarg :cols :reader cols :type unsigned-byte) (channels :initform 1 :reader channels) (data :initarg :data :accessor data :type (simple-array * *)))) (defclass array3d () ((rows :initarg :rows :reader rows :type unsigned-byte) (cols :initarg :cols :reader cols :type unsigned-byte) (channels :initarg :channels :reader channels :type unsigned-byte) (data :initarg :data :accessor data :type (simple-array * *)))) (defgeneric ref (array i &optional j k)) (defmethod ref ((array array2d) i &optional j k) (declare (type unsigned-byte i)) (cond ((null j) (aref (data array) i)) ((null k) (aref (data array) (+ (* i (cols array)) j))) (t (error "You are accessing a two dimensional array, but 3 indices provided.")))) (defmethod ref ((array array3d) i &optional j k) (declare (type unsigned-byte i)) (cond ((null j) (aref (data array) i)) ((null k) (aref (data array) (+ (* i (cols array) (channels array)) j))) (t (aref (data array) (+ (* i (cols array) (channels array)) (* j (channels array)) k)))))
6,558
Common Lisp
.lisp
140
36.271429
111
0.559394
sparkecho/clcv
2
0
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
6e8d93c667678726d5391aef966fd6ba8c24de666ecf0bc27378507e16144568
20,747
[ -1 ]
20,748
point.lisp
sparkecho_clcv/core/point.lisp
(uiop/package:define-package :clcv/core/point (:use :common-lisp) (:export #:point #:make-point #:point-x #:point-y #:point-z #:p+ #:p- #:p* #:p/)) (in-package :clcv/core/point) (defclass point () ((x :initarg :x :accessor point-x) (y :initarg :y :accessor point-y))) (defun make-point (&optional (x 0) (y 0)) (make-instance 'point :x x :y y))
449
Common Lisp
.lisp
17
19.235294
45
0.514019
sparkecho/clcv
2
0
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
69e1792fce5e9ac535a1fd13aedb8c7112dd122942c9f86c9fe14aa656a413ea
20,748
[ -1 ]
20,749
type.lisp
sparkecho_clcv/core/type.lisp
(uiop/package:define-package :clcv/core/type (:use :common-lisp) (:export :int8 :int16 :int32 :uint8 :uint16 :uint32 :single :double :char :logical)) (in-package :clcv/core/type) (deftype :int8 () '(signed-byte 8)) (deftype :int16 () '(signed-byte 16)) (deftype :int32 () '(signed-byte 32)) (deftype :uint8 () '(unsigned-byte 8)) (deftype :uint16 () '(unsigned-byte 16)) (deftype :uint32 () '(unsigned-byte 32)) (deftype :single () 'single-float) (deftype :double () 'double-float) (deftype :char () 'character) (deftype :logical () 'bit)
585
Common Lisp
.lisp
17
30.941176
44
0.646536
sparkecho/clcv
2
0
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
d5873535a37ea13b6f3074a44e2ef2951d4e5d68cb3f3e438f743169e3e8ecb0
20,749
[ -1 ]
20,750
all.lisp
sparkecho_clcv/core/all.lisp
(uiop/package:define-package :clcv/core/all (:nicknames :clcv-core) (:use :common-lisp) (:use-reexport :clcv/core/type :clcv/core/image :clcv/core/array :clcv/core/point)) (provide "clcv-core") (provide "CLCV-CORE")
277
Common Lisp
.lisp
9
23
43
0.590226
sparkecho/clcv
2
0
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
0878f7437e0fdadde7efa079433ca86f3dc85a5c0b7d06edf61c72d5abfa543a
20,750
[ -1 ]
20,751
all.lisp
sparkecho_clcv/graphics/all.lisp
(uiop/package:define-package :clcv/graphics/all (:nicknames :clcv-graphics) (:use :common-lisp) (:use-reexport)) (provide "clcv-graphics") (provide "CLCV-GRAPHICS")
175
Common Lisp
.lisp
6
26.5
47
0.730539
sparkecho/clcv
2
0
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
603e38be711cd53544b458721f05c63e2d9e1eca83d68657746502046fcf4772
20,751
[ -1 ]
20,752
array2d.lisp
sparkecho_clcv/matrix/array2d.lisp
;;;; 2 dimensions array based matrix version (uiop/package:define-package :clcv/matrix/array2d (:use :common-lisp) (:export #:matrix #:m+ #:m- #:m* #:diag #:diagp #:eye #:eyep #:copy-matrix #:pr #:print-matrix #:mexpt #:trans #:row-multiplyf #:row-addf #:row-switchf #:col-multiplyf #:col-addf #:col-switchf #:rearrangef #:row-echelon #:row-canonical #:col-canonical #:canonical #:row-rank #:col-rank #:rank #:inversion #:det #:submatrix #:minor #:cofactor #:signed-minor #:adj #:inv #:tr #:dot #:mapeach #:msum #:norm #:euclidean-distance)) (in-package #:clcv/matrix/array2d) ;; 矩阵构造函数 ;; Constructor function of matrix (defun matrix (rows cols &optional initvec) (let ((mat (make-array (list rows cols) :initial-element 0))) (when initvec (loop for i from 0 below rows do (loop for j from 0 below cols do (let ((k (+ (* i cols) j))) (setf (aref mat i j) (svref initvec k)))))) mat)) ;; 构造以给定向量中元素为对角线元素的对角矩阵 ;; Build a diagonal matrix which has all elements in the given vector (defun diag (initvec) (let* ((order (length initvec)) (result (matrix order order))) (loop for i from 0 below order do (setf (aref result i i) (aref initvec i))) result)) ;; 判断是否是对角矩阵的谓词 ;; Predicate of if the given matrix is a diag matrix (defun diagp (mat) (let ((rows (array-dimension mat 0)) (cols (array-dimension mat 1))) (loop for i from 0 below rows do (unless (loop for j from 0 below cols do (when (and (/= (aref mat i j) 0) (/= i j)) (return nil)) finally (return t)) (return nil)) finally (return t)))) ;; 单位矩阵构造函数 ;; Build a `n order' eye matrix (identity matrix) (defun eye (n) (let ((mat (matrix n n))) (loop for i from 0 below n do (loop for j from 0 below n do (if (= i j) (setf (aref mat i j) 1) (setf (aref mat i j) 0)))) mat)) ;; 判断是否是单位矩阵的谓词 ;; Predicate of if the given matrix is a eye matrix (defun eyep (mat) (let ((rows (array-dimension mat 0)) (cols (array-dimension mat 1))) (and (= rows cols) (> rows 0) (> cols 0) (loop for i from 0 below rows do (unless (loop for j from 0 below cols do (when (if (= i j) (/= (aref mat i j) 1) (/= (aref mat i j) 0)) (return nil)) finally (return t)) (return nil)) finally (return t))))) ;; Build a new matrix with the same content of mat (defun copy-matrix (mat) (let* ((rows (array-dimension mat 0)) (cols (array-dimension mat 1)) (copy (matrix rows cols))) (loop for i from 0 below rows do (loop for j from 0 below cols do (setf (aref copy i j) (aref mat i j)))) copy)) ;; 矩阵美观打印函数 ;; Matrix pretty print (defun print-matrix (mat) (let ((rows (array-dimension mat 0)) (cols (array-dimension mat 1))) (loop for i from 0 below rows do (progn (loop for j from 0 below cols do (format t "~A~A" #\Tab (aref mat i j))) (format t "~%"))))) ;; print-matrix 的别名 ;; Nickname of print-matrix (defun pr (mat) (print-matrix mat)) ;; 二元矩阵加法运算 ;; Binary matrix addition (defun madd (mat1 mat2) (let ((rows1 (array-dimension mat1 0)) (cols1 (array-dimension mat1 1)) (rows2 (array-dimension mat2 0)) (cols2 (array-dimension mat2 1))) (assert (and (= rows1 rows2) (= cols1 cols2))) (let ((mat3 (matrix rows1 cols1))) (loop for i from 0 below rows1 do (loop for j from 0 below cols1 do (setf (aref mat3 i j) (+ (aref mat1 i j) (aref mat2 i j))))) mat3))) ;; 拓展的矩阵加法运算 ;; Extended matrix addition ;; m+ can add n matrices together (n >= 1) (defun m+ (mat &rest mats) (reduce #'madd (cons mat mats))) ;; 矩阵二元减法运算 ;; Binary subtraction of matrix (defun msub (mat1 mat2) (let ((rows1 (array-dimension mat1 0)) (cols1 (array-dimension mat1 1)) (rows2 (array-dimension mat2 0)) (cols2 (array-dimension mat2 1))) (assert (and (= rows1 rows2) (= cols1 cols2))) (let ((mat3 (matrix rows1 cols1))) (loop for i from 0 below rows1 do (loop for j from 0 below cols1 do (setf (aref mat3 i j) (- (aref mat1 i j) (aref mat2 i j))))) mat3))) ;; 矩阵取负(反)运算 ;; Build a new matrix with each element negative of the corresponding one in mat (defun mminus (mat) (let* ((rows (array-dimension mat 0)) (cols (array-dimension mat 1)) (result (matrix rows cols))) (loop for i from 0 below rows do (loop for j from 0 below cols do (setf (aref result i j) (- (aref mat i j))))) result)) ;; 拓展的矩阵减法 ;; Extended subtraction of matrix ;; When there is only one parameter passed, call function #'mminus instead of #'msub (defun m- (mat &rest mats) (if (null mats) (mminus mat) (reduce #'msub (cons mat mats)))) ;; 二元矩阵乘法运算 ;; Binary multiplication of matrix (defun mmul (mat1 mat2) (let ((rows1 (array-dimension mat1 0)) (cols1 (array-dimension mat1 1)) (rows2 (array-dimension mat2 0)) (cols2 (array-dimension mat2 1))) (assert (= cols1 rows2)) (let ((result (matrix rows1 cols2))) (loop for i from 0 below rows1 do (loop for j from 0 below cols2 do (setf (aref result i j) (loop for k from 0 below cols1 sum (* (aref mat1 i k) (aref mat2 k j)))))) (if (and (= rows1 1) (= cols2 1)) (aref result 0 0) result)))) ;; 矩阵数乘运算 ;; Compute a matrix multiplied by a number (defun nmul (num mat) (let* ((rows (array-dimension mat 0)) (cols (array-dimension mat 1)) (result (matrix rows cols))) (loop for i from 0 below rows do (loop for j from 0 below cols do (setf (aref result i j) (* num (aref mat i j))))) result)) ;; 混合二元乘法, 两个参数相乘, 每个参数要么是数字要么是矩阵 ;; Mixed binary multiplication of matrix ;; The two parameters are both required either a number or a matrix (defun mix* (num/mat1 num/mat2) (cond ((numberp num/mat1) (cond ((numberp num/mat2) (* num/mat1 num/mat2)) (t (nmul num/mat1 num/mat2)))) ((numberp num/mat2) (nmul num/mat2 num/mat1)) (t (mmul num/mat1 num/mat2)))) ;; 拓展的矩阵乘法 ;; Extended multiplication of matrix ;; Function #'m* can take more than one parameter, and each of them should be ;; either a number or a matrix (defun m* (num/mat &rest nums/mats) (reduce #'mix* (cons num/mat nums/mats))) ;; 矩阵乘方(矩阵幂运算) ;; Exponentiation of matrix (defun mexpt (mat power) (let ((rows (array-dimension mat 0)) (cols (array-dimension mat 1))) (assert (= rows cols)) (let ((result (eye rows))) (dotimes (i power) (setf result (m* result mat))) result))) ;; 开平方 ;; 结果中的每个元素为原矩阵中对应元素的平方根 ;; Square root of the matrix ;; Each element of the result is square root of the corresponding element ;; of the origin matrix (defun msqrt (mat) (let* ((rows (array-dimension mat 0)) (cols (array-dimension mat 1)) (result (matrix rows cols))) (loop for i from 0 below rows do (loop for j from 0 below cols do (setf (aref result i j) (sqrt (aref mat i j))))) result)) ;; 矩阵转置 ;; Matrix Transposion (defun trans (mat) (let* ((rows (array-dimension mat 0)) (cols (array-dimension mat 1)) (result (matrix cols rows))) (loop for i from 0 below rows do (loop for j from 0 below cols do (setf (aref result j i) (aref mat i j)))) result)) ;;; 初等行变换 ;;; Elementary row operation ;; 倍法变换 ;; Row multiplication (defun row-multiplyf (mat i k) (let ((cols (array-dimension mat 1))) (loop for col from 0 below cols do (setf (aref mat i col) (* k (aref mat i col)))) mat)) ;; 消法变换 ;; Row addition (defun row-addf (mat i j k) (let ((cols (array-dimension mat 1))) (loop for col from 0 below cols do (incf (aref mat i col) (* k (aref mat j col)))) mat)) ;; 换法变换 ;; Row switching (defun row-switchf (mat i j) (let ((cols (array-dimension mat 1))) (loop for col from 0 below cols do (rotatef (aref mat i col) (aref mat j col))) mat)) ;;; 初等行变换 ;;; Elementary row operation ;; 倍法变换 ;; Col multiplication (defun col-multiplyf (mat i k) (let ((rows (array-dimension mat 0))) (loop for row from 0 below rows do (setf (aref mat row i) (* k (aref mat row i)))) mat)) ;; 消法变换 ;; Col addition (defun col-addf (mat i j k) (let ((rows (array-dimension mat 0))) (loop for row from 0 below rows do (incf (aref mat row j) (* k (aref mat row i)))) mat)) ;; 换法变换 ;; Col switching (defun col-switchf (mat i j) (let ((rows (array-dimension mat 0))) (loop for row from 0 below rows do (rotatef (aref mat row i) (aref mat row j))) mat)) ;; 统计矩阵第 row 行中前导的 0 的个数 ;; Aux function ;; Count how many zeros are there in row-th row before a non-zero element (defun count-prefix-zeros (mat row) (let ((cnt 0)) (dotimes (col (array-dimension mat 1)) (if (zerop (aref mat row col)) (incf cnt) (return cnt))) cnt)) ;; 将矩阵按照每行前导的 0 的个数的升序重排行 ;; Aux function ;; Rearrange the matrix by quantity of prefixed zeros (defun rearrangef (mat) (let* ((rows (array-dimension mat 0)) (nums (make-array rows))) (dotimes (i rows) (setf (aref nums i) (count-prefix-zeros mat i))) (loop for k from 0 below rows do (loop for i from 1 below rows do (let ((j (- i 1))) (when (< (aref nums i) (aref nums j)) (rotatef (aref nums i) (aref nums j)) (row-switchf mat i j))))) mat)) ;; 化为行阶梯矩阵 ;; Gaussian elimination (row reduction) ;; Row echelon form (defun row-echelon (mat) (let ((tmat (copy-matrix mat))) (rearrangef tmat) (let ((rows (array-dimension mat 0)) (cols (array-dimension mat 1))) (loop for i from 0 below (1- rows) do (let ((pos (count-prefix-zeros tmat i))) (loop for j from (1+ i) below rows do (when (/= pos cols) (when (/= (aref tmat j pos) 0) (row-addf tmat j i (- (/ (aref tmat j pos) (aref tmat i pos))))))))) tmat))) ;; 化为行最简矩阵 (行规范型矩阵) ;; Reduced row echelon form / row canonical form (defun row-canonical (mat) (let ((tmat (row-echelon mat)) (rows (array-dimension mat 0)) (cols (array-dimension mat 1))) (loop for j from (1- rows) downto 1 do (let ((pos (count-prefix-zeros tmat j))) (when (/= pos cols) (row-multiplyf tmat j (/ 1 (aref tmat j pos))) (loop for i from (1- j) downto 0 do (when (/= (aref tmat i pos) 0) (row-addf tmat i j (- (/ (aref tmat i pos) (aref tmat j pos))))))))) tmat)) ;; 化为列最简矩阵 ;; Reduced col echelon form / col canonical form (defun col-canonical (mat) (trans (rearrangef (row-canonical (trans mat))))) ;; 化为标准型矩阵 ;; Transform the mat to canonical form (defun canonical (mat) (col-canonical (row-canonical mat))) ;; 矩阵的行秩 ;; Row rank of matrix (defun row-rank (mat) (let* ((tmat (row-echelon mat)) (rows (array-dimension mat 0)) (cols (array-dimension mat 1)) (rank rows)) (loop for i from (1- rows) downto 0 do (let ((flag t)) (loop for j from (1- cols) downto 0 do (when (/= (aref tmat i j) 0) (setf flag nil) (return))) (when flag (decf rank)))) rank)) ;; 矩阵的列秩 ;; Col rank of matrix (defun col-rank (mat) (row-rank (trans mat))) ;; 矩阵的秩 ;; Rank fo matrix (defun rank (mat) (min (row-rank (row-canonical mat)) (row-rank (row-canonical (trans mat))))) ;; 逆序数 ;; Compute the inversion of the vector vec's permutation (defun inversion (vec) (let ((len (length vec)) (cnt 0)) (loop for i from 0 below (1- len) do (loop for j from (1+ i) below len do (when (< (svref vec j) (svref vec i)) (incf cnt)))) cnt)) ;; 生成全排列 ;; 根据给定的数组生成包含该数组的所有全排列的列表 ;; Generate permutation ;; Generate a list that includes all the permutations of the given vector (defun permutation (vec) (let ((result nil)) (labels ((perm (vec k len) (if (= k len) (push (copy-seq vec) result) (loop for i from k below len do (progn (rotatef (aref vec i) (aref vec k)) (perm vec (1+ k) len) (rotatef (aref vec k) (aref vec i))))))) (perm vec 0 (length vec))) result)) ;; 生成一个从 0 到 n-1 的顺序数组 ;; Generate an ordered vector includes numbers that from 0 to n-1 (defun gen-seq-vec (n) (make-array n :initial-contents (loop for i from 0 below n collect i))) ;; 行列式 ;; Compute the determinant of a square matrix (defun det (mat) (let ((rows (array-dimension mat 0)) (cols (array-dimension mat 1))) (assert (= rows cols)) (let ((permutations (permutation (gen-seq-vec rows))) (acc 0)) (dolist (perm permutations) (let ((mul 1)) ;multiplicative (dotimes (i rows) (setf mul (* mul (aref mat i (svref perm i))))) (incf acc (* mul (expt -1 (inversion perm)))))) acc))) ;; 生成除第 i 行和第 j 行元素的子矩阵 ;; Generate the submatrix of the matrix mat that exclude i-th row and j-th colum elements (defun submatrix (mat i j) (let* ((rows (array-dimension mat 0)) (cols (array-dimension mat 1)) (result (matrix (1- rows) (1- cols)))) (loop for r from 0 below (1- rows) do (if (< r i) (loop for c from 0 below (1- cols) do (if (< c j) (setf (aref result r c) (aref mat r c)) (setf (aref result r c) (aref mat r (1+ c))))) (loop for c from 0 below (1- cols) do (if (< c j) (setf (aref result r c) (aref mat (1+ r) c)) (setf (aref result r c) (aref mat (1+ r) (1+ c))))))) result)) ;; 余子式 ;; Minor (defun minor (mat i j) (det (submatrix mat i j))) ;; 代数余子式 ;; Signed minor of a matrix (defun cofactor (mat i j) (* (expt -1 (+ i j)) (minor mat i j))) (defun signed-minor (mat i j) (cofactor mat i j)) ;; 伴随矩阵 ;; Adjugate (defun adj (mat) (let* ((order (array-dimension mat 0)) (result (matrix order order))) (loop for i from 0 below order do (loop for j from 0 below order do (setf (aref result i j) (cofactor mat j i)))) result)) ;; 矩阵的逆 ;; Inverse of matrix (defun inv (mat) (assert (/= (det mat) 0)) (m* (/ 1 (det mat)) (adj mat))) ;; 矩阵的迹 ;; Trace of matrix (defun tr (mat) (assert (= (array-dimension mat 0) (array-dimension mat 1))) (let ((order (array-dimension mat 0))) (loop for i from 0 below order sum (aref mat i i)))) ;; 计算向量的内积(数量积) ;; Compute inner product(scalar product) of two vector (defun dot (vec1 vec2) (let ((rows1 (array-dimension vec1 0)) (cols1 (array-dimension vec1 1)) (rows2 (array-dimension vec2 0)) (cols2 (array-dimension vec2 1))) (assert (and (= (min rows1 cols1) 1) (= (min rows2 cols2) 1) (= (max rows1 cols1) (max rows2 cols2)))) (let ((v1 (if (= rows1 1) vec1 (trans vec1))) (v2 (if (= cols2 1) vec2 (trans vec2)))) (m* v1 v2)))) ;; 对矩阵的每个元素进行操作 ;; Do the given function on each element of mat (defun mapeach (function mat) (let* ((rows (array-dimension mat 0)) (cols (array-dimension mat 1)) (result (matrix rows cols))) (loop for i from 0 below rows do (loop for j from 0 below cols do (setf (aref result i j) (funcall function (aref mat i j))))) result)) ;; 计算矩阵所有元素之和 ;; Compute the sum of all elements of the given mat (defun msum (mat) (let ((rows (array-dimension mat 0)) (cols (array-dimension mat 1))) (loop for i from 0 below rows sum (loop for j from 0 below cols sum (aref mat i j))))) ;; p-范数 ;; Compute p-norm of vector vec (defun norm (vec &optional (p 2)) (assert (or (= (array-dimension vec 0) 1) (= (array-dimension vec 1) 1))) (expt (msum (mapeach #'(lambda (x) (expt (abs x) p)) vec)) (/ 1 p))) ;; 欧几里得距离(欧式距离) ;; Euclidean distance of two vectors (defun euclidean-distance (vec1 vec2) (assert (and (= (array-dimension vec1 0) (array-dimension vec2 0)) (= (array-dimension vec1 1) (array-dimension vec2 1)))) (let ((vec (m- vec1 vec2))) (norm vec)))
18,532
Common Lisp
.lisp
522
26.434866
92
0.562669
sparkecho/clcv
2
0
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
df2a70077b1137705621a67025cb860254de7eef41929b96a5fa71b8ecf5c540
20,752
[ -1 ]
20,753
all.lisp
sparkecho_clcv/matrix/all.lisp
(uiop/package:define-package :clcv/matrix/all (:nicknames :clcv-matrix) (:use :common-lisp) (:use-reexport :clcv/matrix/array2d)) (provide "clcv-matrix") (provide "CLCV-MATRIX")
188
Common Lisp
.lisp
6
28.666667
45
0.727778
sparkecho/clcv
2
0
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
829db546a634fa0bdf0b99cf0b4f913b216e6744dcb153d4c6e46dd2f7f6f8a7
20,753
[ -1 ]
20,754
all.lisp
sparkecho_clcv/ml/all.lisp
(uiop/package:define-package :clcv/ml/all (:nicknames :clcv-ml) (:use :common-lisp) (:use-reexport)) (provide "clcv-ml") (provide "CLCV-ML")
151
Common Lisp
.lisp
6
22.5
41
0.685315
sparkecho/clcv
2
0
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
955a7dd205bc9c2f194b9659461cc2977e976b8cd74fb08a00e12e7a41256f83
20,754
[ -1 ]
20,755
clcv.asd
sparkecho_clcv/clcv.asd
;;;; clcv.asd #-asdf3.1 (error "clcv requires ASDF 3.1") (asdf:defsystem "clcv" :name "clcv" :description "Common Lisp Computer Vision Library" :author "sparkecho <[email protected]>" :license "GPL v3.0" :class :package-inferred-system :depends-on ("opticl" "sdl2" "bordeaux-threads" "clcv/core/all" "clcv/matrix/all" "clcv/dip/all" "clcv/gui/all" "clcv/io/all" "clcv/ml/all" "clcv/graphics/all") :in-order-to ((test-op (load-op "clcv/test/all"))) :perform (test-op (o c) (symbol-call :clcv/test/all :test-suite)) :serial nil :components ((:file "clcv") (:static-file "README.md") (:static-file "LICENSE") (:static-file "TODO.org"))) ;; ERROR with test (defsystem "clcv/test" :depends-on ("clcv/test/all")) (register-system-packages "clcv/graphic/all" '(:clcv-graphics)) (register-system-packages "clcv/matrix/all" '(:clcv-matrix)) (register-system-packages "clcv/core/all" '(:clcv-core)) (register-system-packages "clcv/dip/all" '(:clcv-dip)) (register-system-packages "clcv/gui/all" '(:clcv-gui)) (register-system-packages "clcv/io/all" '(:clcv-io)) (register-system-packages "clcv/ml/all" '(:clcv-ml)) (register-system-packages "clcv/test/all" '(:clcv-test))
1,383
Common Lisp
.asd
35
32.657143
67
0.606106
sparkecho/clcv
2
0
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
2bc11403ac1ab57ce92da2699d5453d50ebca06f92d8058907927d7a49beb961
20,755
[ -1 ]
20,793
util.lisp
borodust_post-man/src/util.lisp
(cl:in-package :post-man) (declaim (special *level* *player* *gameplay*)) (defvar *origin* (gamekit:vec2 0 0)) (defparameter *seed* "b00bface") (defvar *up* (gamekit:vec2 0 1)) (defvar *down* (gamekit:vec2 0 -1)) (defvar *left* (gamekit:vec2 1 0)) (defvar *right* (gamekit:vec2 -1 0)) (defvar *background* (gamekit:vec4 0.1 0.1 0.1 1)) (defvar *foreground* (gamekit:vec4 0.9 0.9 0.9 1)) (defparameter *grid-cell-width* 32) (defparameter *grid-size* 20) (defun vec= (this that) (and (< (abs (- (gamekit:x this) (gamekit:x that))) single-float-epsilon) (< (abs (- (gamekit:y this) (gamekit:y that))) single-float-epsilon))) ;; FIXME: detect unreachable paths (defun find-node-path (start-node goal-node &key heuristic-cost path-cost node-children node-equal) (labels ((%heuristic-cost (current-node) (funcall heuristic-cost current-node goal-node)) (%path-cost (current-node another-node) (funcall path-cost current-node another-node)) (%node-children (node) (funcall node-children node)) (%node-equal (this that) (funcall node-equal this that)) (%key (path-head) (destructuring-bind (path-cost . heuristic-cost) (first path-head) (+ heuristic-cost path-cost)))) (let ((paths (bodge-heap:make-binary-heap :key #'%key)) (processed (make-hash-table :test 'equal))) (bodge-heap:binary-heap-push paths (list* (cons 0 (%heuristic-cost start-node)) (list start-node))) (setf (gethash start-node processed) t) (loop for ((parent-path-cost . nil) . path) = (bodge-heap:binary-heap-pop paths) for parent = (first path) always parent until (%node-equal parent goal-node) do (loop for child in (%node-children parent) for heuristic-cost = (%heuristic-cost child) for path-cost = (+ parent-path-cost (%path-cost parent child)) for head = (cons path-cost heuristic-cost) unless (gethash child processed) do (setf (gethash child processed) t) (bodge-heap:binary-heap-push paths (list* head (list* child path)))) finally (return (nreverse path)))))) (defun to-isometric (position &key (width-factor 0.5) (height-factor 0.5) tile-width tile-height) (let* ((x-iso (* (- (gamekit:x position) (gamekit:y position)) (if tile-width (/ tile-width *grid-cell-width* 2) width-factor))) (y-iso (* (+ (gamekit:x position) (gamekit:y position)) (if tile-height (/ tile-height *grid-cell-width* 2) height-factor)))) (gamekit:vec2 x-iso y-iso))) (defun translate-isometric (position &key (width-factor 0.5) (height-factor 0.5) tile-width tile-height) (let ((position (to-isometric position :width-factor width-factor :height-factor height-factor :tile-width tile-width :tile-height tile-height))) (gamekit:translate-canvas (* (gamekit:x position) *grid-cell-width*) (* (gamekit:y position) *grid-cell-width*)))) (defun translate-position (position) (gamekit:translate-canvas (* (gamekit:x position) *grid-cell-width*) (* (gamekit:y position) *grid-cell-width*))) (defgeneric generate-random-integer (state bound)) (defgeneric generate-random-float (state bound)) (defun random-integer (bound) (generate-random-integer *gameplay* bound)) (defun random-float (bound) (generate-random-float *gameplay* bound)) (defun string-hash (string) (loop with accumulator = 1 with result = 0 for value across (babel:string-to-octets string) for i = 0 then (1+ i) if (and (> i 0) (= (mod i 8) 0)) do (setf result (logxor result accumulator) accumulator 1 i 0) else do (setf accumulator (* accumulator (- value 128))) finally (return (logxor result accumulator)))) (defgeneric select-direction (state))
4,541
Common Lisp
.lisp
91
36.978022
88
0.561411
borodust/post-man
2
1
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
211846fad4819ab6681c2e7648a35579c52d4a3063f279a2fdec0b6737d43e54
20,793
[ -1 ]
20,794
resources.lisp
borodust_post-man/src/resources.lisp
(cl:in-package :post-man) (gamekit:register-resource-package :keyword (asdf:system-relative-pathname :post-man "assets/")) (gamekit:define-font :retro "fonts/retro-gaming/Retro Gaming.ttf") (gamekit:define-image :splash "images/menu/Post_Logo.png" :use-nearest-interpolation t) ;;; ;;; ROB-O-MAN ;;; (gamekit:define-image :rob-o-man-front "images/rob-o-man/robo_idle.png" :use-nearest-interpolation t) (gamekit:define-image :rob-o-man-back "images/rob-o-man/robo_back.png" :use-nearest-interpolation t) (gamekit:define-image :rob-o-man-right "images/rob-o-man/robo_side.png" :use-nearest-interpolation t) (gamekit:define-image :rob-o-man-left "images/rob-o-man/robo_side_opposite.png" :use-nearest-interpolation t) ;;; ;;; BOGDAN ;;; (gamekit:define-image :bogdan-front "images/bogdan/bogdan_idle.png" :use-nearest-interpolation t) (gamekit:define-image :bogdan-back "images/bogdan/bogdan_back.png" :use-nearest-interpolation t) (gamekit:define-image :bogdan-right "images/bogdan/bogdan_walk.png" :use-nearest-interpolation t) (gamekit:define-image :bogdan-left "images/bogdan/bogdan_walk_opposite.png" :use-nearest-interpolation t) ;;; ;;; BOX ;;; (gamekit:define-image :box "images/level/box.png" :use-nearest-interpolation t) (gamekit:define-image :horizontal-rack "images/level/horizontal_boxes.png" :use-nearest-interpolation t) (gamekit:define-image :horizontal-rack-active "images/level/horizontal_boxes_active.png" :use-nearest-interpolation t) (gamekit:define-image :vertical-rack "images/level/vertical_boxes.png" :use-nearest-interpolation t) (gamekit:define-image :vertical-rack-active "images/level/vertical_boxes_active.png" :use-nearest-interpolation t) ;;; ;;; LEVEL ;;; (gamekit:define-image :floor "images/level/floor.png" :use-nearest-interpolation t) ;;; ;;; MUSIC ;;; (gamekit:define-sound :menu-tune "music/Alexander Nakarada - Be Jammin.ogg") (gamekit:define-sound :gameplay-tune "music/Kevin MacLeod - Funky Energy Loop.ogg") (gamekit:define-sound :capture-tune "music/Rafael Krux - Horror Suspense.ogg") ;;; ;;; SFX ;;; (gamekit:define-sound :user-action "sounds/404049__deathscyp__breaker-1.wav") (gamekit:define-sound :box-pick-up "sounds/422651__trullilulli__sfx-player-action-phone-pick-up.wav") (gamekit:define-sound :box-drop "sounds/272065__bexhillcollege__thrown-object.wav")
2,377
Common Lisp
.lisp
62
36.241935
83
0.767279
borodust/post-man
2
1
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
b6a730e58db3c1de96b07c5c6d1ef7548bfd439bfd60ac3cbac284f2481f5800
20,794
[ -1 ]
20,795
main.lisp
borodust_post-man/src/main.lisp
(cl:in-package :post-man) (gamekit:defgame post-man (gamekit.fistmachine:fistmachine) () (:viewport-width (* *grid-size* *grid-cell-width*)) (:viewport-height (* *grid-size* *grid-cell-width*)) (:viewport-title "POST-MAN") (:prepare-resources nil) (:default-initargs :initial-state 'init-state)) (defmethod gamekit:notice-resources (any &rest resources) (declare (ignore any resources))) (defun run () (gamekit:start 'post-man))
448
Common Lisp
.lisp
11
38
62
0.719907
borodust/post-man
2
1
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
b9795f8f0d8d02d54aec7501d0b7efb97124c918828cb4321cac650c41565783
20,795
[ -1 ]
20,796
main-menu.lisp
borodust_post-man/src/state/main-menu.lisp
(cl:in-package :post-man) (defun draw-splash () (gamekit:with-pushed-canvas () (gamekit:translate-canvas (- (/ (gamekit:viewport-width) 2) 160) (/ (gamekit:viewport-height) 2)) (gamekit:scale-canvas 0.5 0.5) (gamekit:draw-image (gamekit:vec2 0 0) :splash))) (defclass main-menu-state (input-handling-state) ((options :initform (make-array 2 :initial-contents '(:exit :start))) (selected-option-idx :initform 1))) (defmethod gamekit:post-initialize ((this main-menu-state)) (gamekit:stop-sound :gameplay-tune) (gamekit:stop-sound :capture-tune) (gamekit:play-sound :menu-tune :looped-p t)) (defmethod gamekit:pre-destroy ((this main-menu-state)) (gamekit:stop-sound :menu-tune)) (defmethod gamekit:draw ((this main-menu-state)) (with-slots (options selected-option-idx) this (bodge-canvas:clear-buffers *background*) (draw-splash) (gamekit:with-pushed-canvas () (gamekit:translate-canvas (- (/ (gamekit:viewport-width) 2) 100) (- (/ (gamekit:viewport-height) 2) 180)) (gamekit:scale-canvas 2 2) (loop for i from 0 for option across options when (= i selected-option-idx) do (gamekit:draw-text ">" (gamekit:vec2 0 (* i 15)) :font (gamekit:make-font :retro 20) :fill-color *foreground*) do (gamekit:draw-text (string option) (gamekit:vec2 20 (* i 15)) :font (gamekit:make-font :retro 20) :fill-color *foreground*))))) (defun select-next-menu-option (state) (with-slots (options selected-option-idx) state (play-user-action-sound) (setf selected-option-idx (mod (1+ selected-option-idx) (length options))))) (defun select-prev-menu-option (state) (with-slots (options selected-option-idx) state (play-user-action-sound) (setf selected-option-idx (mod (1- selected-option-idx) (length options))))) (defun invoke-action (this) (with-slots (options selected-option-idx) this (play-user-action-sound) (case (aref options selected-option-idx) (:start (gamekit:play-sound :gameplay-tune :looped-p t) (gamekit.fistmachine:transition-to 'gameplay-state :level 1 :seed (string-hash *seed*))) (:exit (gamekit:stop))))) (defmethod gamekit.input-handler:button-pressed ((this main-menu-state) (button (eql :down))) (select-next-menu-option this)) (defmethod gamekit.input-handler:button-pressed ((this main-menu-state) (button (eql :s))) (select-next-menu-option this)) (defmethod gamekit.input-handler:dpad-changed ((this main-menu-state) (button (eql :down))) (select-next-menu-option this)) (defmethod gamekit.input-handler:button-pressed ((this main-menu-state) (button (eql :up))) (select-prev-menu-option this)) (defmethod gamekit.input-handler:button-pressed ((this main-menu-state) (button (eql :w))) (select-prev-menu-option this)) (defmethod gamekit.input-handler:dpad-changed ((this main-menu-state) (button (eql :up))) (select-prev-menu-option this)) (defmethod gamekit.input-handler:button-pressed ((this main-menu-state) (button (eql :enter))) (invoke-action this)) (defmethod gamekit.input-handler:button-pressed ((this main-menu-state) (button (eql :gamepad-a))) (invoke-action this))
3,871
Common Lisp
.lisp
75
38.8
80
0.584861
borodust/post-man
2
1
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
aa5e11096b8bd369d3c5343c3e0c922ff54b880307bd551c85b971d19e9c7feb
20,796
[ -1 ]
20,797
gameplay.lisp
borodust_post-man/src/state/gameplay.lisp
(cl:in-package :post-man) (defparameter *max-bogdan-count* 30) (defparameter *max-box-count* 20) (defparameter *capture-fade-out-time* 5) (defparameter *capture-fade-out-scale* 5) (defparameter *level-fade-out-time* 1) (defclass gameplay-state (input-handling-state) ((level :initform nil) (bogdans :initform (list)) (rob-o-man :initform nil) (renderables :initform (make-array 0 :adjustable t :fill-pointer t)) (random-generator :initform nil) (level-number :initform nil) (box-count :initform nil) (bogdan-count :initform nil) (hud-font :initform (gamekit:make-font :retro 34)) (seed :initform (error ":seed missing") :initarg :seed) (next-seed :initform nil) (total-boxes-placed :initform 0 :initarg :total-boxes-placed) (total-time-spent :initform 0 :initarg :total-time-spent) (dpad-state :initform nil) (started-at :initform (bodge-util:real-time-seconds)) (captured-at :initform nil) (finished-at :initform nil))) (defmethod initialize-instance :after ((this gameplay-state) &key level) (with-slots (random-generator level-number box-count bogdan-count seed next-seed) this (let ((*gameplay* this)) (setf random-generator (random-state:make-generator :mersenne-twister-64 seed) level-number level box-count (min *max-box-count* (* 1 (1+ (truncate (/ level 2))))) bogdan-count (min *max-bogdan-count* (+ 10 (* 2 (truncate (/ level 3))))) next-seed (random-integer #xFFFFFFFFFFFFFFFF))))) (defun calc-level-stats (this) (with-slots (total-boxes-placed total-time-spent started-at captured-at level-number) this (let ((time-spent-current-level (- (or captured-at (bodge-util:real-time-seconds)) started-at))) (values total-boxes-placed (+ total-time-spent time-spent-current-level) level-number)))) (defun transition-to-endgame (this) (multiple-value-bind (boxes-placed time-spent level-reached) (calc-level-stats this) (gamekit.fistmachine:transition-to 'endgame-state :boxes-collected boxes-placed :seconds-spent time-spent :level level-reached))) (defun transition-to-next-level (this) (with-slots (next-seed) this (multiple-value-bind (boxes-placed time-spent level-reached) (calc-level-stats this) (gamekit.fistmachine:transition-to 'gameplay-state :level (1+ level-reached) :seed next-seed :total-boxes-placed boxes-placed :total-time-spent time-spent)))) (defmacro with-bound-objects ((state) &body body) (once-only (state) `(let ((*level* (slot-value ,state 'level)) (*player* (slot-value ,state 'rob-o-man)) (*gameplay* ,state)) ,@body))) (defun spawn-box () (with-slots (level bogdans) *gameplay* (add-object level (make-instance 'box) (position-of (first bogdans))))) (defmethod gamekit:post-initialize ((this gameplay-state)) (with-slots (bogdans level rob-o-man bogdan-count) this (let ((*gameplay* this)) (setf level (make-instance 'level) rob-o-man (make-instance 'rob-o-man)) (loop repeat bogdan-count do (push (make-instance 'bogdan :speed (+ (random-float 0.5) 1) :position (find-level-random-position level)) bogdans)) (spawn-box)))) (defun play-endgame-sequence (this) (with-slots (captured-at) this (setf captured-at (bodge-util:real-time-seconds)))) (defun play-next-level-sequence (this) (with-slots (finished-at) this (setf finished-at (bodge-util:real-time-seconds)))) (defun calc-text-width (text font) (multiple-value-bind (origin width height advance) (gamekit:calc-text-bounds text font) (declare (ignore origin width height)) advance)) (defmethod objective-reached ((this gameplay-state)) (with-slots (box-count total-boxes-placed) this (decf box-count) (incf total-boxes-placed) (if (> box-count 0) (spawn-box) (play-next-level-sequence this)))) (defmethod player-captured ((this gameplay-state)) (gamekit:stop-sound :gameplay-tune) (gamekit:play-sound :capture-tune :looped-p t) (play-endgame-sequence this)) (defun render-gameplay (this) (with-slots (renderables level-number box-count hud-font started-at) this (flet ((%y-coord (renderable) (gamekit:y (position-of renderable)))) (stable-sort renderables #'> :key #'%y-coord) (loop for renderable across renderables do (render renderable))) (gamekit:draw-text (format nil "Level ~2,'0d" level-number) (gamekit:vec2 6 (- (gamekit:viewport-height) 25)) :font hud-font :fill-color *foreground*) (let ((text (format nil "Left: ~2,'0d" box-count))) (gamekit:draw-text text (gamekit:vec2 (- (gamekit:viewport-width) (calc-text-width text hud-font) 6) (- (gamekit:viewport-height) 25)) :font hud-font :fill-color *foreground*)) (when (< (- (bodge-util:real-time-seconds) started-at) *level-fade-out-time*) (let ((scale (/ (- (bodge-util:real-time-seconds) started-at) *level-fade-out-time*))) (gamekit:draw-rect *origin* (gamekit:viewport-width) (gamekit:viewport-height) :fill-paint (gamekit:vec4 0.1 0.1 0.1 (- 1 scale))))))) (defun render-endgame (this) (with-slots (rob-o-man captured-at) this (let* ((transition (min 1.0 (/ (- (bodge-util:real-time-seconds) captured-at) *capture-fade-out-time*))) (scale (1+ (* (- *capture-fade-out-scale* 1) transition))) (scaled-x (* (+ (gamekit:x (position-of rob-o-man)) 1) (* *grid-cell-width* scale))) (scaled-y (* (+ (gamekit:y (position-of rob-o-man)) 1) (* *grid-cell-width* scale)))) (gamekit:translate-canvas (* (+ (- scaled-x) (/ (gamekit:viewport-width) 2)) transition) (* (+ (- scaled-y) (/ (gamekit:viewport-height) 2)) transition)) (gamekit:scale-canvas scale scale) (gamekit:with-pushed-canvas () (render-gameplay this)) (gamekit:draw-rect *origin* (gamekit:viewport-width) (gamekit:viewport-height) :fill-paint (gamekit:vec4 0.1 0.1 0.1 (/ scale *capture-fade-out-scale*)))))) (defun render-next-level (this) (with-slots (finished-at) this (render-gameplay this) (let ((transition (min 1.0 (/ (- (bodge-util:real-time-seconds) finished-at) *level-fade-out-time*)))) (gamekit:draw-rect *origin* (gamekit:viewport-width) (gamekit:viewport-height) :fill-paint (gamekit:vec4 0.1 0.1 0.1 transition))))) (defmethod gamekit:draw ((this gameplay-state)) (with-slots (captured-at finished-at) this (bodge-canvas:clear-buffers *background*) (bodge-canvas:antialias-shapes nil) (cond (captured-at (render-endgame this)) (finished-at (render-next-level this)) (t (render-gameplay this))))) (defmethod gamekit:act ((this gameplay-state)) (with-slots (rob-o-man bogdans level captured-at finished-at) this (cond (captured-at (when (> (- (bodge-util:real-time-seconds) captured-at) *capture-fade-out-time*) (transition-to-endgame this))) (finished-at (when (> (- (bodge-util:real-time-seconds) finished-at) *level-fade-out-time*) (transition-to-next-level this))) (t (with-bound-objects (this) (update level) (update rob-o-man) (loop for bogdan in bogdans do (update bogdan))))))) (defmethod register-renderable ((this gameplay-state) renderable) (with-slots (renderables) this (vector-push-extend renderable renderables))) (defmethod remove-renderable ((this gameplay-state) renderable) (with-slots (renderables) this (deletef renderables renderable))) (defun pause-game (this) (transition-to-endgame this)) (defun interact-with-obstacles (this) (with-slots (level rob-o-man) this (with-bound-objects (this) (if-let ((objects (find-adjacent-obstacles level (position-of rob-o-man)))) (loop for object in objects do (interact rob-o-man object)) (interact rob-o-man nil))))) (defmethod gamekit.input-handler:button-pressed ((this gameplay-state) (button (eql :gamepad-start))) (pause-game this)) (defmethod gamekit.input-handler:button-pressed ((this gameplay-state) (button (eql :escape))) (pause-game this)) (defmethod gamekit.input-handler:button-pressed ((this gameplay-state) (button (eql :enter))) (interact-with-obstacles this)) (defmethod gamekit.input-handler:button-pressed ((this gameplay-state) (button (eql :gamepad-a))) (interact-with-obstacles this)) (defmethod gamekit.input-handler:dpad-changed ((this gameplay-state) state) (with-slots (dpad-state) this (setf dpad-state state))) (defmethod generate-random-integer ((this gameplay-state) bound) (with-slots (random-generator) this (random-state:random-int random-generator 0 (1- bound)))) (defmethod generate-random-float ((this gameplay-state) bound) (with-slots (random-generator) this (random-state:random-float random-generator 0 (- bound single-float-epsilon)))) (defmethod select-direction ((this gameplay-state)) (with-slots (dpad-state) this (let ((button-bag (append (when dpad-state (list dpad-state)) (gamekit.input-handler:pressed-buttons *gameplay*)))) (flet ((%select (direction &rest buttons) (when (loop for button in buttons thereis (member button button-bag)) direction))) (or (%select :up :w :up) (%select :left :a :left) (%select :down :s :down ) (%select :right :d :right))))))
11,073
Common Lisp
.lisp
228
36.675439
98
0.583326
borodust/post-man
2
1
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
7cf5d3f0772fc4b83737aeb61669e03a2ecc435ebf648e121eea0992face4c6a
20,797
[ -1 ]
20,798
state.lisp
borodust_post-man/src/state/state.lisp
(cl:in-package :post-man) (defclass input-handling-state (gamekit.input-handler:input-handler) ()) (defmethod gamekit:post-initialize :around ((this input-handling-state)) (gamekit.input-handler:activate-input-handler this) (call-next-method)) (defmethod gamekit:pre-destroy :around ((this input-handling-state)) (unwind-protect (call-next-method) (gamekit.input-handler:deactivate-input-handler this)))
427
Common Lisp
.lisp
9
43.888889
72
0.76699
borodust/post-man
2
1
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
51c0ea3f3de6516f60ccd854ee616e2ee4c4286ec9e66534b05ddb2f988d1895
20,798
[ -1 ]