所以我用Lisp制作一个相对简单的游戏。
我使用所有NIL元素创建一个具有指定大小的板:
(defun make-board(rows columns)
(cond ((= rows 1) (list (make-list columns)))
(t ( append (list (make-list columns)) (make-board (1- rows) columns)))))
现在我正在使用place函数,它将值放在2D列表的第一个NIL元素中:
(defun place(player column matrix)
;need some help here
;I can get the specified column, is there a better way?!
(let (col)(get-column column matrix))
)
我可以检索指定的列:
; return the given column
(defun get-column
(colnum matrix)
(mapcar (lambda (row) (nth colnum row)) matrix))
我觉得这很简单,但不幸的是Lisp并不适合我。我也更喜欢这种没有迭代的实现,因为这是做“Lisp”的“正确”方法。
编辑:
为了澄清,makeboard将返回如下内容:
(make-board 5 5)
((NIL NIL NIL NIL NIL)
(NIL NIL NIL NIL NIL)
(NIL NIL NIL NIL NIL)
(NIL NIL NIL NIL NIL)
(NIL NIL NIL NIL NIL))
答案 0 :(得分:1)
我不知道为什么递归应该是在Lisp中编程的“正确”方式。循环宏非常有用,可以使用它轻松实现类似你想要实现的功能。
(defun make-board(rows columns)
(loop repeat rows collect
(loop repeat columns collect nil)))
答案 1 :(得分:0)
我相信为你的电路板使用二维数组会更方便:
(defun make-board (rows columns)
(make-array (list rows columns)
:initial-element nil))
为了找到列的第一个空单元格,遍历该列:
(defun find-null-cell-index (column board)
"Returns the row index of the first cell in the given column of the board
that contains nil."
(loop :for i :below (array-dimension board 0)
:when (null (aref board i column))
:do (return-from find-null-cell-index i)))