comparison clojure/com/aurellem/gb_funs.clj @ 84:26f002f2868c

better functional version of earlier code
author Robert McIntyre <rlm@mit.edu>
date Fri, 09 Mar 2012 23:28:07 -0600
parents 95cb2152d7cd
children 3f4fdd270059
comparison
equal deleted inserted replaced
83:95cb2152d7cd 84:26f002f2868c
77 ;; meta buttons 77 ;; meta buttons
78 :select 0x0004 78 :select 0x0004
79 :start 0x0008 79 :start 0x0008
80 80
81 ;; pseudo-buttons 81 ;; pseudo-buttons
82 :restart 0x0800 ; hard reset -- not really a button 82 :restart 0x0800 ; hard reset
83 :listen -1 ; listen for user input 83 :listen -1 ; listen for user input
84 }) 84 })
85 85
86 (defn button-mask [buttons] 86 (defn button-mask [buttons]
87 (reduce bit-or 0x0000 (map button-code buttons))) 87 (reduce bit-or 0x0000 (map button-code buttons)))
88 88
89 (def current-state (atom nil)) 89 (def current-state (atom nil))
90 90
91
92 (defn set-state! [^SaveState state]
93 (if (not @on?) (restart!))
94 (if (not= @current-state state)
95 (Gb/loadState (:data state)))
96 (reset! current-state state))
97
98 (defrecord Move [keys state])
99
91 (defn step 100 (defn step
92 ([^SaveState state buttons] 101 ([^SaveState state buttons]
93 (if (not @on?) (restart!)) 102 (set-state! state)
94 (if (not= @current-state state)
95 (Gb/loadState (:data state)))
96 (Gb/step (button-mask buttons)) 103 (Gb/step (button-mask buttons))
97 (reset! current-state 104 (reset! current-state
98 (SaveState. (inc (:frame state))(Gb/saveState))))) 105 (SaveState. (inc (:frame state))(Gb/saveState))))
99
100 (defn play
101 ([^SaveState state] 106 ([^SaveState state]
102 (step state [:listen])) 107 (step state [:listen]))
103 ([] (step (if @current-state @current-state (root))))) 108 ([] (step (if @current-state @current-state (root)))))
109
110 (defn move
111 [^Move move buttons]
112 (Move. (step (:state move) buttons) buttons))
113
114
115 (defn play
116 ([state n]
117 (reduce (fn [s _] (step s)) state (range n)))
118 ([state]
119 (dorun (iterate step state))))
120 ;;;;;;;;;;;
121
122
123 ;;;;;;;;;;;;;;; CPU data
124
125
126
127 (defn cpu-data [size arr-fn]
128 (let [store (int-array size)]
129 (fn [state] (set-state! state) (arr-fn store) store)))
130
131 (def ram
132 (cpu-data (Gb/getRAMSize) #(Gb/getRAM %)))
133
134 (def rom
135 (cpu-data (Gb/getROMSize) #(Gb/getROM %)))
136
137 (def working-ram
138 (cpu-data Gb/WRAM_SIZE #(Gb/getWRAM %)))
139
140 (def video-ram
141 (cpu-data Gb/VRAM_SIZE #(Gb/getVRAM %)))
142
143 (def registers
144 (cpu-data Gb/NUM_REGISTERS #(Gb/getRegisters %)))
145
146 ;; TODO add register names
147
148 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
149
150 (defn AF [state]
151 (nth (registers state) 2))
152
153 (defn BC [state]
154 (nth (registers state) 3))
155
156
157
104 158