Clojure 比特板上的射线攻击
我试图计算64位长的位板表示索引下的射线攻击:Clojure 比特板上的射线攻击,clojure,chess,bitboard,Clojure,Chess,Bitboard,我试图计算64位长的位板表示索引下的射线攻击: (defn se [board index] "Produces a ray attack from the indexed bit in the south-east direction" (reduce bit-or (for [bit (rest (range index 0 -7))] (bit-flip board bit)))) 车的攻击(直接沿着一个文件或职级)是很容易的。然而,上述代码的问题是,我最终得
(defn se [board index]
"Produces a ray attack from the indexed bit in the south-east direction"
(reduce bit-or
(for [bit (rest (range index 0 -7))]
(bit-flip board bit))))
车的攻击(直接沿着一个文件或职级)是很容易的。然而,上述代码的问题是,我最终得到了以下对角Bishop攻击的可能性:
00000000
00100000
01000000
10000001
00000010
00000100
00001000
00010000
我该如何解释当工件从电路板边缘脱落时的情况?我使用的是大端映射(A8=0,H1=63)。我可能会使用电路板上的x,y坐标来实现这一点:这使得在电路板边缘进行边界条件检查更容易,比如
(defn se [x y]
"Produces a ray attack from the indexed bit in the south-east direction"
(let [initial (bit-shift-left (bit-shift-left (long 1) x) (* y 8))
dx 1 ;; x direction
dy 1 ;; y direction
distance (min
(- 7 x)
(- 7 y))
shift (+ dx (* 8 dy))]
(loop [value 0
distance distance]
(if (<= distance 0)
value
(recur (bit-or value (bit-shift-left initial (* distance shift))) (dec distance))))))
(defn bits [^long bitboard]
(map
#(if (> (bit-and 1 (bit-shift-right bitboard %)) 0) 1 0)
(range 64)))
(defn display [bitboard]
(let [bits (partition 8 (bits bitboard))]
(doseq [ss bits]
(println (apply str ss)))))
(display (se 1 3))
00000000
00000000
00000000
00000000
00100000
00010000
00001000
00000100
(定义se[x y]
“从东南方向的索引位生成射线攻击”
(让[初始(位左移(位左移(长1)x)(*y8))
dx 1;;x方向
dy1;;y方向
距离(分钟)
(-7倍)
(-7岁))
移位(+dx(*8 dy))]
(循环[值0
距离]
(如果((位和1(位右移位板%)0)1 0)
(范围64)))
(defn显示[位板]
(让[位(分区8(位位板))]
(doseq[ss位]
(println(应用str ss(()())))
(显示器(se 1 3))
00000000
00000000
00000000
00000000
00100000
00010000
00001000
00000100
通过一点额外的工作,你可以将其推广到任何(dx,dy)方向投射光线,例如(1,0)一辆向东移动的车。如果你设置了距离限制,你甚至可以对骑士使用(2,1)
我认为这比为每个片段方向定义单独的函数更实用。不知道类型提示^,这仅仅是为了性能吗?我认为这里的类型提示目前实际上没有任何作用,但我把它们放在这里是为了提醒我自己参数类型,并防止将来的Clojure编译器出现错误xploit it for optimizationYep,现在可以工作了。剩下的唯一一件事是我需要说明0-7或63的索引。抛出此错误:ArityException错误的参数数(0)传递到:core$bit或clojure.lang.AFn.throwArity。需要捕获此异常并返回一个空板。没有其他错误:)我接受这个,因为它最好地回答了最初的问题。
(defn se [board index]
"Produces a ray attack from the indexed bit in the south-east direction"
(reduce bit-or 0
(for [bit (take (- 7 (rem index 8)) (rest (range index 0 -7)))]
(bit-flip board bit))))