changeset 422:b58a356f7cc2

merge.
author Robert McIntyre <rlm@mit.edu>
date Tue, 17 Apr 2012 06:36:43 -0500
parents f211cd655ccb (current diff) 13165fb5852b (diff)
children 971bd1774eab
files
diffstat 2 files changed, 877 insertions(+), 50 deletions(-) [+]
line wrap: on
line diff
     1.1 --- a/clojure/com/aurellem/gb/hxc.clj	Tue Apr 17 06:36:17 2012 -0500
     1.2 +++ b/clojure/com/aurellem/gb/hxc.clj	Tue Apr 17 06:36:43 2012 -0500
     1.3 @@ -184,7 +184,8 @@
     1.4  
     1.5  
     1.6  (defn hxc-pokedex-names
     1.7 -  "The names of the pokemon in hardcoded pokedex order. List begins at
     1.8 +  "The names of the pokemon in hardcoded pokedex order. List of the
     1.9 +  pokedex numbers of each pokemon (in internal order) begins at
    1.10  ROM@410B1. See also, hxc-pokenames."
    1.11    ([] (hxc-pokedex-names
    1.12         com.aurellem.gb.gb-driver/original-rom))
    1.13 @@ -350,10 +351,9 @@
    1.14  
    1.15  (def hxc-places
    1.16    "The hardcoded place names in memory. List begins at
    1.17 -ROM@71500. [Cinnabar] Mansion seems to be dynamically calculated."
    1.18 +ROM@71500. [Cinnabar/Celadon] Mansion seems to be dynamically calculated."
    1.19    (hxc-thunk-words 0x71500 560))
    1.20  
    1.21 -
    1.22  (defn hxc-dialog
    1.23    "The hardcoded dialogue in memory, including in-game alerts. Dialog
    1.24    seems to be separated by 0x57 instead of 0x50 (END). Begins at ROM@98000."
    1.25 @@ -923,25 +923,335 @@
    1.26  ;; note: 1195C-6A says ABLE#NOT ABLE#, but so does 119C0-119CE.
    1.27  ;; The first instance is for Machines; the second, for stones.
    1.28  
    1.29 -;; 0x251A (in indexable mem): image decompression routine seems to begin here.
    1.30 +;; note: according to
    1.31 +;; http://www.upokecenter.com/games/rby/guides/rgbtrainers.php
    1.32 +;; the amount of money given by a trainer is equal to the 
    1.33 +;; base money times the level of the last Pokemon on that trainer's
    1.34 +;; list. Other sources say it's the the level of the last pokemon 
    1.35 +;; /defeated/.
    1.36 +
    1.37 +;; todo: find base money.
    1.38 +
    1.39 +
    1.40 +;; note: 0xDFEA (in indexable mem) is the dex# of the currently-viewed Pokemon in
    1.41 +   ;; in the pokedex. It's used for other purposes if there is none.
    1.42 +
    1.43 +;; note: 0x9D35 (index.) switches from 0xFF to 0x00 temporarily when
    1.44 +;;   you walk between areas. 
    1.45 +
    1.46 +;; note: 0xD059 (index.) is the special battle type of your next battle:
    1.47 +;; - 00 is a usual battle
    1.48 +;; - 01 is a pre-scripted OLD MAN battle which always fails to catch the
    1.49 +;;      target Pokemon.
    1.50 +;; - 02 is a safari zone battle
    1.51 +;; - 03  obligates you to run away. (unused) 
    1.52 +;; - 04 is a pre-scripted OAK battle, which (temporarily) causes the
    1.53 +;;      enemy Pokemon to cry PIKAAA, and which always catches the target
    1.54 +;;      Pokemon. The target Pokemon is erased after the battle.
    1.55 +;; - 05+ are glitch states in which you are sort of the Pokemon.
    1.56 +
    1.57 +
    1.58 +;; note: 0x251A (in indexable mem): image decompression routine seems to begin here.
    1.59 +
    1.60 +;; note: 0x4845 (index): vending inventory is loaded here. possibly
    1.61 +   ;; other things, too.
    1.62 +(comment
    1.63 +  ;; temporarily intercept/adjust what pops out of the vending
    1.64 +  ;; machine.
    1.65 +  ;; (and how much it costs)
    1.66 +
    1.67 +  ;; located at 0x4845
    1.68 +  ;; not to be confused with shop inventory, 0xCF7B
    1.69 +  (do 
    1.70 +    (step (read-state "vend-menu"))
    1.71 +    (write-memory! (rewrite-memory (vec(memory)) 0x4845 [2 0 1 0]))
    1.72 +    (step @current-state [:a])
    1.73 +    (step @current-state [])
    1.74 +    (nstep @current-state 200) ))
    1.75  
    1.76  
    1.77  ;; Note: There are two tile tables, one from 8000-8FFF, the other from
    1.78  ;; 8800-97FF. The latter contains symbols, possibly map tiles(?), with some japanese chars and stuff at the end. 
    1.79  (defn print-pixel-letters!
    1.80    "The pixel tiles representing letters. Neat!"
    1.81 -  ([] (print-pixel-letters! (read-state "oak-speaks"))) 
    1.82 -  ([state] 
    1.83 -     (map
    1.84 -      (comp
    1.85 -       println
    1.86 -       (partial map #(if (zero? %) \space 0))
    1.87 -       #(if (< (count %) 8)
    1.88 -          (recur (cons 0 %))
    1.89 -          %)
    1.90 -       reverse bit-list)
    1.91 + ([] (print-pixel-letters! (read-state "oak-speaks"))) 
    1.92 +([state] 
    1.93 +   (map
    1.94 +    (comp
    1.95 +     println
    1.96 +     (partial map #(if (zero? %) \space 0))
    1.97 +     #(if (< (count %) 8)
    1.98 +        (recur (cons 0 %))
    1.99 +        %)
   1.100 +     reverse bit-list)
   1.101 +    
   1.102 +    (take 0xFFF (drop 0x8800 (memory state))))))
   1.103 +
   1.104 +
   1.105 +;; (defn test-2 []
   1.106 +;;   (loop [n 0
   1.107 +;;          pc-1 (pc-trail (-> state-defend (tick) (step [:a]) (step [:a]) (step []) (nstep 100)) 100000)
   1.108 +;;          pc-2 (pc-trail (-> state-speed (tick) (step [:a]) (step [:a])
   1.109 +;;   (step []) (nstep 100)) 100000)]
   1.110 +;;     (cond (empty? (drop n pc-1)) [pc-1 n]
   1.111 +;;           (not= (take 10 (drop n pc-1)) (take 10 pc-2))
   1.112 +;;           (recur  pc-1 pc-2 (inc n))
   1.113 +;;           :else
   1.114 +;;           [(take 1000 pc-2) n])))
   1.115 +
   1.116 +
   1.117 +
   1.118 +
   1.119 +(defn test-3 
   1.120 +  "Explore trainer data"
   1.121 +  ([] (test-3 0x3A289))
   1.122 +  ([start]
   1.123 +  (let [pokenames (vec(hxc-pokenames-raw))]
   1.124 +    (println 
   1.125 +     (reduce
   1.126 +      str
   1.127 +      (map
   1.128 +       (fn [[adr lvl pkmn]]
   1.129 +         (str (format "%-11s %4d       %02X %02X \t %05X\n"
   1.130 +                      
   1.131 +                      (cond
   1.132 +                        (zero? lvl) "+"
   1.133 +                        (nil? (get pokenames (dec pkmn)))
   1.134 +                        "-"
   1.135 +                        :else
   1.136 +                        (get pokenames (dec pkmn)))
   1.137 +                      lvl
   1.138 +                      pkmn
   1.139 +                      lvl
   1.140 +                      adr
   1.141 +                      )))
   1.142 +       (map cons
   1.143 +            (take-nth 2 (drop start (range)))
   1.144 +            (partition 2
   1.145 +                       (take 400;;703
   1.146 +                             (drop
   1.147 +                              start
   1.148 +                              ;; 0x3A75D
   1.149 +                              (rom)))))))))))
   1.150 +  
   1.151 +(defn search-memory* [mem codes k]
   1.152 +  (loop [index 0
   1.153 +         index-next 1
   1.154 +         start-match 0
   1.155 +         to-match codes
   1.156 +         matches []]
   1.157 +    (cond
   1.158 +      (>= index (count mem)) matches
   1.159 +
   1.160 +      (empty? to-match)
   1.161 +      (recur
   1.162 +       index-next
   1.163 +       (inc index-next)
   1.164 +       index-next
   1.165 +       codes
   1.166 +       (conj matches
   1.167 +             [(hex start-match) (take k (drop start-match mem))])
   1.168 +       )
   1.169 +
   1.170 +      (or (= (first to-match) \_) ;; wildcard
   1.171 +          (= (first to-match) (nth mem index)))
   1.172 +      (recur
   1.173 +       (inc index)
   1.174 +       index-next
   1.175 +       start-match
   1.176 +       (rest to-match)
   1.177 +       matches)
   1.178 +
   1.179 +      :else
   1.180 +      (recur
   1.181 +       index-next
   1.182 +       (inc index-next)
   1.183 +       index-next
   1.184 +       codes
   1.185 +       matches))))
   1.186        
   1.187 -      (take 0xFFF (drop 0x88000 (memory state))))))
   1.188 +
   1.189 +(defn search-pattern [ptn coll]
   1.190 +  (loop
   1.191 +      [index 0
   1.192 +       to-match ptn
   1.193 +       binds {}
   1.194 +
   1.195 +       next-index 1
   1.196 +       match-start 0
   1.197 +       matches []]
   1.198 +
   1.199 +    (cond
   1.200 +        (>= index (count coll)) matches
   1.201 +        (empty? to-match)
   1.202 +        (recur
   1.203 +         next-index
   1.204 +         ptn
   1.205 +         {}
   1.206 +         (inc next-index)
   1.207 +         next-index
   1.208 +         (conj match-start
   1.209 +               [(hex match-start) binds]))
   1.210 +
   1.211 +        :else
   1.212 +        (let [k (first to-match)
   1.213 +              v (nth coll index)]
   1.214 +        (cond
   1.215 +          (= k \_) ;; wildcard
   1.216 +          (recur
   1.217 +           (inc index)
   1.218 +           (rest to-match)
   1.219 +           binds
   1.220 +
   1.221 +           next-index
   1.222 +           match-start
   1.223 +           matches)
   1.224 +
   1.225 +          (keyword? k)
   1.226 +          (if (binds k)
   1.227 +            (if (= (binds k) v)
   1.228 +
   1.229 +              ;; consistent bindings
   1.230 +              (recur
   1.231 +               (inc index)
   1.232 +               (rest to-match)
   1.233 +               binds
   1.234 +
   1.235 +               next-index
   1.236 +               match-start
   1.237 +               matches)
   1.238 +
   1.239 +              ;; inconsistent bindings
   1.240 +              (recur
   1.241 +               next-index
   1.242 +               ptn
   1.243 +               {}
   1.244 +               (inc next-index)
   1.245 +               next-index
   1.246 +               matches))
   1.247 +              
   1.248 +            (if ((set (vals binds)) v)
   1.249 +              ;; bindings are not unique
   1.250 +              (recur
   1.251 +               next-index
   1.252 +               ptn
   1.253 +               {}
   1.254 +               (inc next-index)
   1.255 +               next-index
   1.256 +               matches)
   1.257 +
   1.258 +              ;; bindings are unique
   1.259 +              (recur
   1.260 +               (inc index)
   1.261 +               (rest to-match)
   1.262 +               (assoc binds k v)
   1.263 +
   1.264 +               next-index
   1.265 +               match-start
   1.266 +               matches)))
   1.267 +
   1.268 +          :else ;; k is just a number
   1.269 +          (if (= k v)
   1.270 +            (recur
   1.271 +             (inc index)
   1.272 +             (rest to-match)
   1.273 +             binds
   1.274 +
   1.275 +             next-index
   1.276 +             match-start
   1.277 +             matches)
   1.278 +
   1.279 +            (recur
   1.280 +             next-index
   1.281 +             ptn
   1.282 +             {}
   1.283 +             (inc next-index)
   1.284 +             next-index
   1.285 +             matches)))))))
   1.286 +
   1.287 +            
   1.288 +            
   1.289 +
   1.290 +              
   1.291 +
   1.292 +
   1.293 +
   1.294 +
   1.295 +(defn search-pattern* [ptn coll]
   1.296 +  (loop
   1.297 +      [
   1.298 +       binds {}
   1.299 +       index 0
   1.300 +       index-next 1
   1.301 +       start-match 0
   1.302 +       to-match ptn
   1.303 +       matches []]
   1.304 +
   1.305 +    (cond
   1.306 +        (>= index (count coll)) matches
   1.307 +        (empty? to-match)
   1.308 +        (recur
   1.309 +         {}
   1.310 +         index-next
   1.311 +         (inc index-next)
   1.312 +         index-next
   1.313 +         ptn
   1.314 +         (conj matches
   1.315 +               [(hex start-match) binds]))
   1.316 +
   1.317 +        :else
   1.318 +        (let [k (first to-match)
   1.319 +              v (nth coll index)]
   1.320 +        (cond
   1.321 +          (= k \_) ;; wildcard
   1.322 +          (recur
   1.323 +           binds
   1.324 +           (inc index)
   1.325 +           index-next
   1.326 +           start-match
   1.327 +           (rest to-match)
   1.328 +           matches)
   1.329 +
   1.330 +          (keyword? k)
   1.331 +          (if (binds k)
   1.332 +            (if (= (binds k) v)
   1.333 +              (recur
   1.334 +               binds
   1.335 +               (inc index)
   1.336 +               index-next
   1.337 +               start-match
   1.338 +               (rest to-match)
   1.339 +               matches)
   1.340 +              (recur
   1.341 +               {}
   1.342 +               index-next
   1.343 +               (inc index-next)
   1.344 +               index-next
   1.345 +               ptn
   1.346 +               matches))
   1.347 +            (if
   1.348 +                ;; every symbol must be bound to a different thing.
   1.349 +              ((set (vals binds)) v)
   1.350 +              (recur
   1.351 +               {}
   1.352 +               index-next
   1.353 +               (inc index-next)
   1.354 +               index-next
   1.355 +               ptn
   1.356 +               matches)
   1.357 +              (recur
   1.358 +               (assoc binds k v)
   1.359 +               (inc index)
   1.360 +               index-next
   1.361 +               start-match
   1.362 +               (rest to-match)
   1.363 +               matches))))))))
   1.364 +             
   1.365 +
   1.366 +
   1.367 +
   1.368 +;; look for the rainbow badge in memory
   1.369 +(println (reduce str (map #(str (first %) "\t" (vec(second %)) "\n") (search-memory (rom) [221] 10))))
   1.370  
   1.371  
   1.372  (comment 
     2.1 --- a/org/rom.org	Tue Apr 17 06:36:17 2012 -0500
     2.2 +++ b/org/rom.org	Tue Apr 17 06:36:43 2012 -0500
     2.3 @@ -1,8 +1,8 @@
     2.4  #+title: Notes on Deconstructing Pokemon Yellow
     2.5  #+author: Dylan Holmes
     2.6  #+email: rlm@mit.edu
     2.7 -#+description:
     2.8 -#+keywords:
     2.9 +#+description: A detailed explication of Pok\eacute{}mon Yellow, helped by Clojure.
    2.10 +#+keywords: pokemon, pokemon yellow, rom, gameboy, assembly, hex, pointers, clojure
    2.11  #+SETUPFILE: ../../aurellem/org/setup.org
    2.12  #+INCLUDE: ../../aurellem/org/level-0.org
    2.13  #+BABEL: :exports both :noweb yes :cache no :mkdirp yes
    2.14 @@ -12,7 +12,6 @@
    2.15  # pokedollar: U+20B1
    2.16  * Introduction
    2.17  
    2.18 -
    2.19  ** COMMENT Getting linguistic data: names, words, etc.
    2.20  
    2.21  Some of the simplest data 
    2.22 @@ -1011,6 +1010,83 @@
    2.23  
    2.24  ** COMMENT Status ailments
    2.25  
    2.26 +
    2.27 +* NPC Trainers
    2.28 +
    2.29 +** Trainer Pok\eacute{}mon
    2.30 +# http://hax.iimarck.us/topic/103/
    2.31 +There are two formats for specifying lists of NPC PPok\eacute{}mon:
    2.32 +- If all the Pok\eacute{}mon will have the same level, the format is
    2.33 +  - Level (used for all the Pok\eacute{}mon)
    2.34 +  - Any number of Pok\eacute{}mon internal ids.
    2.35 +  - 0x00, to indicate end-of-list.
    2.36 +- Otherwise, all the Pok\eacute{}mon will have their level
    2.37 +  specified. The format is
    2.38 +  - 0xFF, to indicate that we will be specifying the levels individually[fn::Because 0xFF is a
    2.39 +    forbidden level within the usual gameplay discipline, the game
    2.40 +    makers could safely use 0xFF as a mode indicator.].
    2.41 +  - Any number of alternating Level/Pokemon pairs
    2.42 +  - 0x00, to indicate end-of-list.
    2.43 +
    2.44 +*** Get the pointers
    2.45 +*** See the data
    2.46 +#+begin_src clojure :exports both :results output 
    2.47 +(ns com.aurellem.gb.hxc
    2.48 +  (:use (com.aurellem.gb assembly characters gb-driver util mem-util
    2.49 +                         constants))
    2.50 +  (:import [com.aurellem.gb.gb_driver SaveState]))
    2.51 +
    2.52 +(->>
    2.53 + (rom)
    2.54 + (drop 0x39E2F)
    2.55 + (take 21)
    2.56 + (println))
    2.57 +
    2.58 +
    2.59 +(->>
    2.60 + (rom)
    2.61 + (drop 0x39E2F)
    2.62 + (take 21)
    2.63 + (partition-by zero?)
    2.64 + (take-nth 2)
    2.65 + (println))
    2.66 +
    2.67 +
    2.68 +
    2.69 +(let
    2.70 +    [pokenames
    2.71 +     (zipmap
    2.72 +      (rest (range))
    2.73 +      (hxc-pokenames-raw))]
    2.74 +
    2.75 +  (->>
    2.76 +   (rom)
    2.77 +   (drop 0x39E2F)
    2.78 +   (take 21)   ;; (1922 in all)
    2.79 +   (partition-by zero?)
    2.80 +   (take-nth 2)
    2.81 +   (map
    2.82 +    (fn parse-team [[mode & team]]
    2.83 +      (if (not= 0xFF mode)
    2.84 +        (mapv
    2.85 +         #(hash-map :level mode :species (pokenames %))
    2.86 +         team)
    2.87 +        
    2.88 +        (mapv
    2.89 +         (fn [[lvl id]] (hash-map :level lvl :species (pokenames id)))
    2.90 +         (partition 2 team)))))
    2.91 +
    2.92 +   (println)))
    2.93 +
    2.94 +
    2.95 +
    2.96 +#+end_src
    2.97 +
    2.98 +#+results:
    2.99 +: (11 165 108 0 14 5 0 10 165 165 107 0 14 165 108 107 0 15 165 5 0)
   2.100 +: ((11 165 108) (14 5) (10 165 165 107) (14 165 108 107) (15 165 5))
   2.101 +: ([{:species RATTATA, :level 11} {:species EKANS, :level 11}] [{:species SPEAROW, :level 14}] [{:species RATTATA, :level 10} {:species RATTATA, :level 10} {:species ZUBAT, :level 10}] [{:species RATTATA, :level 14} {:species EKANS, :level 14} {:species ZUBAT, :level 14}] [{:species RATTATA, :level 15} {:species SPEAROW, :level 15}])
   2.102 +
   2.103  * Places
   2.104  ** Names of places
   2.105  
   2.106 @@ -1018,11 +1094,18 @@
   2.107  #+begin_src clojure
   2.108  (def hxc-places
   2.109    "The hardcoded place names in memory. List begins at
   2.110 -ROM@71500. [Cinnabar] Mansion seems to be dynamically calculated."
   2.111 +ROM@71500. [Cinnabar/Celadon] Mansion seems to be dynamically calculated."
   2.112    (hxc-thunk-words 0x71500 560))
   2.113 +#+end_src
   2.114  
   2.115 +*** See it work
   2.116 +#+begin_src clojure :exports both :results output 
   2.117 +(println (hxc-places))
   2.118  #+end_src
   2.119  
   2.120 +#+results:
   2.121 +: (PALLET TOWN VIRIDIAN CITY PEWTER CITY CERULEAN CITY LAVENDER TOWN VERMILION CITY CELADON CITY FUCHSIA CITY CINNABAR ISLAND INDIGO PLATEAU SAFFRON CITY ROUTE 1 ROUTE 2 ROUTE 3 ROUTE 4 ROUTE 5 ROUTE 6 ROUTE 7 ROUTE 8 ROUTE 9 ROUTE 10  ROUTE 11 ROUTE 12 ROUTE 13 ROUTE 14 ROUTE 15 ROUTE 16 ROUTE 17 ROUTE 18 SEA ROUTE 19 SEA ROUTE 20  SEA ROUTE 21 ROUTE 22 ROUTE 23 ROUTE 24 ROUTE 25 VIRIDIAN FOREST MT.MOON ROCK TUNNEL SEA COTTAGE S.S.ANNE [POKE]MON LEAGUE UNDERGROUND PATH [POKE]MON TOWER SEAFOAM ISLANDS VICTORY ROAD DIGLETT's CAVE ROCKET HQ SILPH CO. [0x4A] MANSION SAFARI ZONE)
   2.122 +
   2.123  ** Wild Pok\eacute{}mon demographics
   2.124  #+name: wilds
   2.125  #+begin_src clojure
   2.126 @@ -1065,12 +1148,111 @@
   2.127  
   2.128  
   2.129  
   2.130 +** Map data
   2.131 +
   2.132 +# http://www.pokecommunity.com/showthread.php?t=235311
   2.133 +# http://datacrystal.romhacking.net/wiki/Pokemon_Red/Blue:Notes
   2.134 +
   2.135 +#+name map
   2.136 +#+begin_src clojure :exports both :results output 
   2.137 +(ns com.aurellem.gb.hxc
   2.138 +  (:use (com.aurellem.gb assembly characters gb-driver util mem-util
   2.139 +                         constants))
   2.140 +  (:import [com.aurellem.gb.gb_driver SaveState]))
   2.141 +
   2.142 +
   2.143 +(defn parse-header-tileset
   2.144 +  [[bank#     ;; memory bank for blocks & tileset 
   2.145 +    
   2.146 +    blocks-lo ;; structure
   2.147 +    blocks-hi
   2.148 +    
   2.149 +    tileset-lo ;; style
   2.150 +    tileset-hi
   2.151 +    
   2.152 +      collision-lo ;; collision info
   2.153 +    collision-hi
   2.154 +    
   2.155 +    talk-here-1 ;; positions of up to three
   2.156 +    talk-here-2 ;; talk-over-countertop tiles
   2.157 +    talk-here-3 ;; --- 0xFF if unused.
   2.158 +    
   2.159 +    grass ;; grass tile --- 0xFF if unused
   2.160 +    
   2.161 +    animation-flags ;; settings for animation
   2.162 +    & _]]
   2.163 +  
   2.164 +  [bank#
   2.165 +   
   2.166 +   blocks-lo ;; structure
   2.167 +   blocks-hi
   2.168 +   
   2.169 +   tileset-lo ;; style
   2.170 +   tileset-hi
   2.171 +   
   2.172 +   collision-lo ;; collision info
   2.173 +   collision-hi
   2.174 +   
   2.175 +   talk-here-1 ;; positions of up to three
   2.176 +   talk-here-2 ;; talk-over-countertop tiles
   2.177 +   talk-here-3 ;; --- 0xFF if unused.
   2.178 +   
   2.179 +   grass ;; grass tile --- 0xFF if unused
   2.180 +   
   2.181 +   animation-flags ;; settings for animation
   2.182 +   ])
   2.183 +
   2.184 +
   2.185 +
   2.186 +(defn parse-header-map
   2.187 +  [start]
   2.188 +
   2.189 +  (let [connection-size 11
   2.190 +
   2.191 +        [tileset-index
   2.192 +         map-height
   2.193 +         map-width
   2.194 +         layout-lo
   2.195 +         layout-hi
   2.196 +         text-lo
   2.197 +         text-hi
   2.198 +         script-lo
   2.199 +         script-hi
   2.200 +         adjacency-flags ;; x x x x N S W E
   2.201 +         & etc]
   2.202 +        (drop start (rom))
   2.203 +
   2.204 +        [east? west? south? north?]
   2.205 +        (bit-list adjacency-flags)
   2.206 +
   2.207 +        [connections object-data]
   2.208 +        (split-at
   2.209 +         (* connection-size (+ east? west? south? north?))
   2.210 +         etc)
   2.211 +
   2.212 +        connections
   2.213 +        (partition connection-size connections)
   2.214 +        
   2.215 +
   2.216 +
   2.217 +
   2.218 +        ]
   2.219 +    (ptr->offset
   2.220 +     3
   2.221 +     (low-high layout-lo layout-hi))
   2.222 +    
   2.223 +
   2.224 +    ))
   2.225 +#+end_src
   2.226 +
   2.227 +#+results:
   2.228 +: 
   2.229 +
   2.230 +
   2.231  
   2.232  * Appendices
   2.233 -
   2.234 -
   2.235 -
   2.236  ** Mapping the ROM
   2.237 +# D3AD: Script:Use Pokeball?
   2.238  
   2.239  | ROM address (hex)     | Description     | Format          | Example         |
   2.240  |-----------------------+-----------------+-----------------+-----------------|
   2.241 @@ -1078,6 +1260,8 @@
   2.242  | 01823-0184A           | Important prefix strings. | Variable-length strings, separated by 0x50. | TM#TRAINER#PC#ROCKET#POK\eacute{}#... |
   2.243  | 0233C-                | Shop inventories. |                 |                 |
   2.244  | 02F47-                | (?) Move ids of some HM moves. | One byte per move id | 0x0F 0x13 0x39 0x46 0x94 0xFF, the move ids of CUT, FLY, SURF, STRENGTH, FLASH, then cancel. |
   2.245 +| 03E59-                | Start of the Give-Pok\eacute{}mon script. | Assembly. When called, converts the contents of register BC into a Pok\eacute{}mon: (B) is the level; (C) is the species. |                 |
   2.246 +| 03E3F-                | Start of the give-item script. | Assembly. When called, converts the contents of register BC into an item: (B) is the item type; (C) is the quantity. |                 |
   2.247  | 04495-                | Prices of items. | Each price is two bytes of binary-coded decimal. Prices are separated by zeroes. Priceless items[fn::Like the Pok\eacute{}dex and other unsellable items.] are given a price of zero. | The cost of lemonade is 0x03 0x50, which translates to a price of ₱350. |
   2.248  | 04524-04527           | (unconfirmed) possibly the bike price in Cerulean. |                 |                 |
   2.249  | 045B7-0491E           | Names of the items in memory. | Variable-length item names (strings of character codes). Names are separated by a single 0x50 character. | MASTER BALL#ULTRA BALL#... |
   2.250 @@ -1086,6 +1270,7 @@
   2.251  | 05DD2-05DF2           | Menu text for player info. |                 | PLAYER [newline] BADGES [nelwine] POK\Eacute{}DEX [newline] TIME [0x50] |
   2.252  | 05EDB.                | Which Pok\eacute{}mon to show during Prof. Oak's introduction. | A single byte, the Pok\eacute{}mon's internal id. | In Pok\eacute{}mon Yellow, it shows Pikachu during the introduction; Pikachu's internal id is 0x54. |
   2.253  | 06698-                | ? Background music. |                 |                 |
   2.254 +|-----------------------+-----------------+-----------------+-----------------|
   2.255  | 7550-7570             | Menu options for map directions[fn:unused:According to [[http://tcrf.net/Pok%C3%A9mon_Red_and_Blue#NORTH.2FWEST.2FSOUTH.2FEAST][The Cutting Room Floor]], this data is unused. ]. | Variable-length strings. | NORTH [newline] WEST [0x50] SOUTH [newline] EAST [0x50] NORTH [newline] EAST[0x50] |
   2.256  | 7570-757D             | Menu options for trading Pok\eacute{}mon |                 | TRADE [newline] CANCEL [0x50] |
   2.257  | 757D-758A             | Menu options for healing Pok\eacute{}mon |                 | HEAL [newline] CANCEL [0x50] |
   2.258 @@ -1094,18 +1279,34 @@
   2.259  | 0822E-082F?           | Pointers to background music, part I. |                 |                 |
   2.260  | 0CB95-                | Pointers to lists of wild pokemon to encounter in each region. These lists begin at 04D89, see above. | Each pointer is a low-byte, high-byte pair. | The first entry is 0x89 0x4D, corresponding to the address 0x4D89, the location of the first list of wild Pok\eacute{}mon (see 04D89, above). |
   2.261  |-----------------------+-----------------+-----------------+-----------------|
   2.262 -| 0DADB.                | Amount of HP restored by Hyper Potion. | The HP consists of a single byte. TODO: Discover what the surrounding data does, and find the data for the amount of HP restored by other items: Fresh Water (50HP), Soda (60HP), Lemonade(80HP). | 200             |
   2.263 +| 0DACB.                | Amount of HP restored by Soda Pop | The HP consists of a single numerical byte. | 60              |
   2.264 +| 0DACF.                | Amount of HP restored by Lemonade | "               | 80              |
   2.265 +| 0DAD5.                | Amount of HP restored by Fresh Water | "               | 50              |
   2.266 +| 0DADB.                | Amount of HP restored by Hyper Potion. | "               | 200             |
   2.267  | 0DAE0.                | Amount of HP restored by Super Potion. | "               | 50              |
   2.268  | 0DAE3.                | Amount of HP restored by Potion. | "               | 20              |
   2.269  |-----------------------+-----------------+-----------------+-----------------|
   2.270  | 0DD4D-DD72            | Names of permanent stats. | Variable-length strings separated by 0x50. | #HEALTH#ATTACK#DEFENSE#SPEED#SPECIAL# |
   2.271 +|-----------------------+-----------------+-----------------+-----------------|
   2.272 +| 0DE2F.                | Duration of Repel. | A single byte, representing the number of steps you can take before the effect wears off. | 100             |
   2.273 +| 0DF39.                | Duration of Super Repel. | "               | 200             |
   2.274 +| 0DF3E.                | Duration of Max Repel. | "               | 250             |
   2.275 +|-----------------------+-----------------+-----------------+-----------------|
   2.276  | 1164B-                | Terminology for the Pok\eacute{}mon menu. | Contiguous, variable-length strings. | TYPE1[newline]TYPE2[newline] *№*,[newline]OT,[newline][0x50]STATUS,[0x50]OK |
   2.277  | 116DE-                | Terminology for permanent stats in the Pok\eacute{}mon menu. | Contiguous, variable-length strings. | ATTACK[newline]DEFENSE[newline]SPEED[newline]SPECIAL[0x50] |
   2.278  | 11852-                | Terminology for current stats in the Pok\eacute{}mon menu. | Contiguous, variable-length strings. | EXP POINTS[newline]LEVEL UP[0x50] |
   2.279  | 1195C-1196A           | The two terms for being able/unable to learn a TM/HM. | Variable-length strings separated by 0x50. | ABLE#NOT ABLE#  |
   2.280  | 119C0-119CE           | The two terms for being able/unable to evolve using the current stone. | Variable-length strings separated by 0x50. | ABLE#NOT ABLE#  |
   2.281 +|-----------------------+-----------------+-----------------+-----------------|
   2.282 +| 11D53.                | Which badge is a prerequisite for CUT? | op code: which bit of A to test? | When this script is called, the bits of A contain your badges, and this op code will check a certain bit of A. The op codes for the badges are, in order, [0x47 0x4F 0x57 0x5F 0x67 0x6F 0x77 0x7F]. |
   2.283 +| 11D67.                | Which badge is a prerequisite for SURF? | "               | 0x67 (test for Soul Badge) |
   2.284 +| 11DAC.                | Which badge is a prerequisite for STRENGTH? | "               | 0x5F (test for Rainbow Badge) |
   2.285 +|-----------------------+-----------------+-----------------+-----------------|
   2.286  | 1232D-12364           | Which moves are taught by the TMs and HMs | A list of 55 move ids (50 TMs, plus 5 HMs). First, the move that will be taught by TM01; second, the move that will be taught by TM02; and so on. The last five entries are the moves taught by HMs 1-5. (See also, BC000 below) | The first few entries are (5 13 14 18 ...) corresponding to Mega Punch (TM01), Razor Wind (TM02), Swords Dance (TM03), Whirlwind (TM04), ... |
   2.287  |-----------------------+-----------------+-----------------+-----------------|
   2.288 +| 1CF8B-1CF8C           | Which Pok\eacute{}mon does Melanie give you in Cerulean City? | A level/internal-id pair. | (10 153), corresponding to a level 10 Bulbasaur. |
   2.289 +| 1D651-1D652           | Which Pok\eacute{}mon do you find at the top of Celadon Mansion? | A level/internal-id pair. | (25 102), corresponding to a level 25 Eevee. |
   2.290 +|-----------------------+-----------------+-----------------+-----------------|
   2.291  | 27D56 & 27D57.        | Pointer to the pointers to type names. | A single low-byte, high-byte pair. | 0x63 0x7D, corresponding to location 27D63\mdash{} the start of the next entry. |
   2.292  | 27D63-27D99           | Pointers to type names. | Each point is a low-byte, high-byte pair. The type names follows immediately after this section; see below. | The first pointer is [0x99 0x7D], corresponding to the location 27D99 ("NORMAL"). |
   2.293  | 27D99-27DFF           | Names of the Pok\eacute{}mon types. | Variable-length type names (strings of character codes). Names are separated by a single 0x50 character. | NORMAL#FIGHTING#... |
   2.294 @@ -1118,8 +1319,8 @@
   2.295  |-----------------------+-----------------+-----------------+-----------------|
   2.296  | 3997D-39B05           | Trainer titles (extended; see 27E77). This list includes strictly more trainers, seemingly at random inserted into the list from 27E77.[fn::The names added are in bold: YOUNGSTER, BUG CATCHER, LASS, *SAILOR*, JR TRAINER(m), JR TRAINER(f), POK\eacute{}MANIAC, SUPER NERD, *HIKER*, *BIKER*, BURGLAR, ENGINEER, JUGGLER, *FISHERMAN*, SWIMMER, *CUE BALL*, *GAMBLER*, BEAUTY,  *PSYCHIC*, ROCKER, JUGGLER (again), *TAMER*, *BIRDKEEPER*, BLACKBELT, *RIVAL1*, PROF OAK, CHIEF, SCIENTIST, *GIOVANNI*, ROCKET, COOLTRAINER(m), COOLTRAINER(f), *BRUNO*, *BROCK*, *MISTY*, *LT. SURGE*, *ERIKA*, *KOGA*, *BLAINE*, *SABRINA*, *GENTLEMAN*, *RIVAL2*, *RIVAL3*, *LORELEI*, *CHANNELER*, *AGATHA*, *LANCE*.] |                 |                 |
   2.297  | 39B05-39DD0.          | unknown         |                 |                 |
   2.298 -| 39DD1-                | (?) Pointers to trainer Pok\eacute{}mon |                 |                 |
   2.299 -| 3A289-3A540 (approx)  | Trainer Pok\eacute{}mon | Consecutive level/internal-id pairs (as with wild Pok\eacute{}mon; see 04D89) with irregular spacing \mdash{} the separators seem to have some metadata purpose. | The first entry is 0x05 0x66, representing level 5 Eevee (from your first battle in the game[fn::Incidentally, to change your rival's starter Pok\eacute{}mon, it's enough just to change its species in all of your battles with him.].) |
   2.300 +| 39DD1-39E2E           | Pointers to trainer Pok\eacute{}mon | Pairs of low-high bits. | The first pair is 0x2F 0x5E, which corresponds to memory location 5E2F relative to this 38000-3C000 bank, i.e.[fn::For details about how relative bank pointers work, see the relevant Appendix.] position 39E2F overall. |
   2.301 +| 39E2F-3A5B2           | Trainer Pok\eacute{}mon | Specially-formatted lists of various length, separated by 0x00. If the list starts with 0xFF, the rest of the list will alternate between levels and internal-ids. Otherwise, start of the list is the level of the whole team, and the rest of the list is internal-ids. | The first entry is (11 165 108 0), which means a level 11 team consisting of Rattata and Ekans. The entry for MISTY is (255 18 27 21 152 0), which means a team of various levels consisting of level 18 Staryu and level 21 Starmie. [fn::Incidentally, if you want to change your rival's starter Pok\eacute{}mon, it's enough just to change its species in all of your battles with him.].) |
   2.302  | 3B1E5-3B361           | Pointers to evolution/learnset data. | One high-low byte pair for each of the 190 Pok\eacute{}mon in internal order. |                 |
   2.303  |-----------------------+-----------------+-----------------+-----------------|
   2.304  | 3B361-3BBAA           | Evolution and learnset data. [fn::Evolution data consists of how to make Pok\eacute{}mon evolve, and what they evolve into. Learnset data consists of the moves that Pok\eacute{}mon learn as they level up.] | Variable-length evolution information (see below), followed by a list of level/move-id learnset pairs. |                 |
   2.305 @@ -1127,6 +1328,9 @@
   2.306  |-----------------------+-----------------+-----------------+-----------------|
   2.307  | 3D131-3D133           | The inventory of both OLD MAN and PROF. OAK when they battle for you. | Pairs of [item-id quantity], terminated by 0xFF. | (0x04 0x01 0xFF) They only have one Pok\eacute{}ball [fn::If you give them any ball, OAK will catch the enemy Pok\eacute{}mon and OLD MAN will miss. (OLD MAN misses even if he throws a MASTER BALL, which is a sight to see!) If you give them some other item first in the list, you'll be able to use that item normally but then you'll trigger the Safari Zone message: Pa will claim you're out of SAFARI BALLs and the battle will end. If you engage in either an OLD MAN or OAK battle with a Gym Leader, you will [1] get reprimanded if you try to throw a ball [2] incur the Safari Zone message [3] automatically win no matter which item you use [4] earn whichever reward they give you as usual [5] permanently retain the name OLD MAN / PROF. OAK.]. |
   2.308  | 3D6C7-3D6D6           | Two miscellaneous strings. | Variable length, separated by 0x50 | Disabled!#TYPE  |
   2.309 +| 3E190-3E194           | Which moves have an increased critical-hit ratio? | List of move ids, terminated by 0xFF. | (0x02 0x4B 0x98 0xA3 0xFF) corresponding to karate-chop, razor-leaf, crabhammer, slash, end-of-list. |
   2.310 +| 3E200-3E204           | " (???)         | "               | "               |
   2.311 +| 3E231.                | Besides normal-type, which type of move can COUNTER counter? | A single byte representing a type id. | This is set to 1, the id of the FIGHTING type. |
   2.312  |-----------------------+-----------------+-----------------+-----------------|
   2.313  | 40252-4027B           | Pok\eacute{}dex menu text | Variable-length strings separated by 0x50. | SEEN#OWN#CONTENTS#... |
   2.314  | 40370-40386           | Important constants for Pok\eacute{}dex entries |                 | HT _ _ *?′??″* [newline] WT _ _ _ *???* lb [0x50] *POK\Eacute{}* [0x50] |
   2.315 @@ -1134,6 +1338,12 @@
   2.316  | 41072-                | Pok\eacute{} placeholder species, "???" |                 |                 |
   2.317  |-----------------------+-----------------+-----------------+-----------------|
   2.318  | 410B1-4116F           | A conversion table between internal order and Pokedex order. | 190 bytes, corresponding to the Pok\eacute{}dex numbers of the 190 Pok\eacute{}mon listed in internal order. All =MISSINGNO.= are assigned a Pok\eacute{}dex number of 0. | The first few entries are (112 115 32 35 21 100 34 80 2 ...), which are the Pok\eacute{}dex numbers of Rhydon, Kangaskhan, Nidoran(m), Clefairy, Spearow, Voltorb, Nidoking, Slobrow, and Ivysaur. |
   2.319 +|-----------------------+-----------------+-----------------+-----------------|
   2.320 +| 509B4-509E0           | Saffron City's adjacency info. | Four adjacency lists, each 11 bytes long. (For more info on adjacency lists a.k.a. connection data, see [[http://datacrystal.romhacking.net/wiki/Pokemon_Red/Blue:Notes][here]]) | The first adjacency list is (0x10 0x70 0x46 0xF0 0xC6 0x0A 0x0A 0x23 0xF6 0x09 0xC8) |
   2.321 +|-----------------------+-----------------+-----------------+-----------------|
   2.322 +| 515AE-515AF           | Which Pok\eacute{}mon does the trainer near Route 25 give you? | A level/internal-id pair. | (10 176) corresponding to a level 10 Charmander. |
   2.323 +| 51DD5-51DD6           | Which Pok\eacute{}mon does the Silph Co. trainer give you? | A level/internal-id pair. | (15 19) corresponding to a level 15 Lapras. |
   2.324 +|-----------------------+-----------------+-----------------+-----------------|
   2.325  | 527BA-527DB           | The costs and kinds of prizes from Celadon Game Corner. | The following pattern repeats three times, once per window[fn::For the first two prize lists, ids are interpreted as Pok\eacute{}mon ids. For the last prize list, ids are (somehow) interpreted as item ids.]: Internal ids / 0x50 / Prices (two bytes of BCD)/ 0x50. | (0x94 0x52 0x65 0x50) Abra Vulpix Wigglytuff (0x02 0x30 0x10 0x00 0x26 0x80) 230C, 1000C, 2680C |
   2.326  | 5DE10-5DE30           | Abbreviations for status ailments. | Fixed-length strings, probably[fn::Here's something strange: all of the status messages start with 0x7F and end with 0x4F \mdash{}except PAR, which ends with 0x50.]. The last entry is QUIT##. | [0x7F] *SLP* [0x4E][0x7F] *PSN* [0x4E][0x7F] *PAR* [0x50][0x7F]... |
   2.327  |-----------------------+-----------------+-----------------+-----------------|
   2.328 @@ -1143,14 +1353,70 @@
   2.329  | 71C1E-71CAA (approx.) | Tradeable NPC Pok\eacute{}mon. | Internal ID, followed by nickname (11 chars; extra space padded by 0x50). Some of the Pokemon have unknown extra data around the id. | The first entry is [0x76] "GURIO######", corresponding to a Dugtrio named "GURIO". |
   2.330  | 7C249-7C2??           | Pointers to background music, pt II. |                 |                 |
   2.331  |-----------------------+-----------------+-----------------+-----------------|
   2.332 -| 98000-B8000           | Dialogue and other messsages. | Variable-length strings. |                 |
   2.333 +| 98000-B7190           | Dialogue and other messsages. | Variable-length strings. |                 |
   2.334 +| B7190-B8000           | (empty space)   |                 | 0 0 0 0 0 ...   |
   2.335  | B8000-BC000           | The text of each Pok\eacute{}mon's Pok\eacute{}dex entry. | Variable-length descriptions (strings) in Pok\eacute{}dex order, separated by 0x50. These entries use the special characters *0x49* (new page), *0x4E* (new line), and *0x5F* (end entry). | The first entry (Bulbasaur's) is: "It can go for days [0x4E] without eating a [0x4E] single morsel. [0x49] In the bulb on [0x4E] its back,  it [0x4E] stores energy [0x5F] [0x50]." |
   2.336 -| BC000-BC60E           | Move names.     | Variable-length move names, separated by 0x50. The moves are in internal order. | POUND#KARATE CHOP#DOUBLESLAP#COMET PUNCH#... |
   2.337 +| BC000-BC60F           | Move names.     | Variable-length move names, separated by 0x50. The moves are in internal order. | POUND#KARATE CHOP#DOUBLESLAP#COMET PUNCH#... |
   2.338 +| BC610-BD000           | (empty space)   |                 | 0 0 0 0 0 ...   |
   2.339  | E8000-E876C           | Names of the \ldquo{}190\rdquo{} species of Pok\eacute{}mon in memory. | Fixed length (10-letter) Pok\eacute{}mon names. Any extra space is padded with the character 0x50. The names are in \ldquo{}internal order\rdquo{}. | RHYDON####KANGASKHANNIDORAN♂#... |
   2.340  |-----------------------+-----------------+-----------------+-----------------|
   2.341  | E9BD5-                | The text PLAY TIME (see above, 70442) |                 |                 |
   2.342 +| F1A44-F1A45           | Which Pok\eacute{}mon does Officer Jenny give you? | A level/internal-id pair. | (10 177), corresponding to a level 10 Squirtle. |
   2.343 +| F21BF-F21C0           | Which Pok\eacute{}mon does the salesman at the Mt. Moon Pok\eacute{}mon center give you? | A level/internal-id pair | (5 133), corresponding to a level 5 Magikarp. |
   2.344 +|                       |                 |                 |                 |
   2.345     #+TBLFM: 
   2.346  
   2.347 +** COMMENT
   2.348 +Locations where Give Pokemon is used in a nonstraightforward way
   2.349 +0x5287C
   2.350 +0x5CE23
   2.351 +0x5C36B
   2.352 +0x7562E
   2.353 +
   2.354 +
   2.355 +** Understanding  memory banks and pointers
   2.356 +#+begin_src clojure
   2.357 +
   2.358 +(defn endian-flip
   2.359 +  "Flip the bytes of the two-byte number."
   2.360 +  [n]
   2.361 +  (assert (< n 0xFFFF))
   2.362 +  (+ (* 0x100 (rem n 0x100))
   2.363 +        (int (/ n 0x100))))
   2.364 +
   2.365 +
   2.366 +(defn offset->ptr
   2.367 +  "Convert an offset into a little-endian pointer."
   2.368 +  [n]
   2.369 +  (->
   2.370 +   n
   2.371 +   (rem 0x10000) ;; take last four bytes
   2.372 +   (rem 0x4000)   ;; get relative offset from the start of the bank
   2.373 +   (+ 0x4000)
   2.374 +   endian-flip))
   2.375 +
   2.376 +(defn offset->bank
   2.377 +  "Get the bank of the offset."
   2.378 +  [n]
   2.379 +  (int (/ n 0x4000)))
   2.380 +
   2.381 +(defn ptr->offset
   2.382 +  "Convert a two-byte little-endian pointer into an offset."
   2.383 +  [bank ptr]
   2.384 +  (->
   2.385 +   ptr
   2.386 +   endian-flip
   2.387 +   (- 0x4000)
   2.388 +   (+ (* 0x4000 bank))
   2.389 +   ))
   2.390 +
   2.391 +(defn same-bank-offset
   2.392 +  "Convert a ptr into an absolute offset by using the bank of the reference."
   2.393 +  [reference ptr]
   2.394 +  (ptr->offset
   2.395 +   (offset->bank reference)
   2.396 +   ptr))
   2.397 +#+end_src
   2.398  
   2.399  
   2.400  ** Internal Pok\eacute{}mon IDs
   2.401 @@ -1644,6 +1910,22 @@
   2.402  
   2.403  ;; note: 0x251A (in indexable mem): image decompression routine seems to begin here.
   2.404  
   2.405 +;; note: 0x4845 (index): vending inventory is loaded here. possibly
   2.406 +   ;; other things, too.
   2.407 +(comment
   2.408 +  ;; temporarily intercept/adjust what pops out of the vending
   2.409 +  ;; machine.
   2.410 +  ;; (and how much it costs)
   2.411 +
   2.412 +  ;; located at 0x4845
   2.413 +  ;; not to be confused with shop inventory, 0xCF7B
   2.414 +  (do 
   2.415 +    (step (read-state "vend-menu"))
   2.416 +    (write-memory! (rewrite-memory (vec(memory)) 0x4845 [2 0 1 0]))
   2.417 +    (step @current-state [:a])
   2.418 +    (step @current-state [])
   2.419 +    (nstep @current-state 200) ))
   2.420 +
   2.421  
   2.422  ;; Note: There are two tile tables, one from 8000-8FFF, the other from
   2.423  ;; 8800-97FF. The latter contains symbols, possibly map tiles(?), with some japanese chars and stuff at the end. 
   2.424 @@ -1663,30 +1945,32 @@
   2.425      (take 0xFFF (drop 0x8800 (memory state))))))
   2.426  
   2.427  
   2.428 -(defn test-2 []
   2.429 -  (loop [n 0
   2.430 -         pc-1 (pc-trail (-> state-defend (tick) (step [:a]) (step [:a]) (step []) (nstep 100)) 100000)
   2.431 -         pc-2 (pc-trail (-> state-speed (tick) (step [:a]) (step [:a])
   2.432 -  (step []) (nstep 100)) 100000)]
   2.433 -    (cond (empty? (drop n pc-1)) [pc-1 n]
   2.434 -          (not= (take 10 (drop n pc-1)) (take 10 pc-2))
   2.435 -          (recur  pc-1 pc-2 (inc n))
   2.436 -          :else
   2.437 -          [(take 1000 pc-2) n])))
   2.438 +;; (defn test-2 []
   2.439 +;;   (loop [n 0
   2.440 +;;          pc-1 (pc-trail (-> state-defend (tick) (step [:a]) (step [:a]) (step []) (nstep 100)) 100000)
   2.441 +;;          pc-2 (pc-trail (-> state-speed (tick) (step [:a]) (step [:a])
   2.442 +;;   (step []) (nstep 100)) 100000)]
   2.443 +;;     (cond (empty? (drop n pc-1)) [pc-1 n]
   2.444 +;;           (not= (take 10 (drop n pc-1)) (take 10 pc-2))
   2.445 +;;           (recur  pc-1 pc-2 (inc n))
   2.446 +;;           :else
   2.447 +;;           [(take 1000 pc-2) n])))
   2.448  
   2.449  
   2.450  
   2.451  
   2.452  (defn test-3 
   2.453    "Explore trainer data"
   2.454 -  []
   2.455 +  ([] (test-3 0x3A289))
   2.456 +  ([start]
   2.457    (let [pokenames (vec(hxc-pokenames-raw))]
   2.458      (println 
   2.459       (reduce
   2.460        str
   2.461        (map
   2.462 -       (fn [[lvl pkmn]]
   2.463 -         (str (format "%-11s %4d       %02X %02X"
   2.464 +       (fn [[adr lvl pkmn]]
   2.465 +         (str (format "%-11s %4d       %02X %02X \t %05X\n"
   2.466 +                      
   2.467                        (cond
   2.468                          (zero? lvl) "+"
   2.469                          (nil? (get pokenames (dec pkmn)))
   2.470 @@ -1696,14 +1980,16 @@
   2.471                        lvl
   2.472                        pkmn
   2.473                        lvl
   2.474 -                      ) "\n"))
   2.475 -       
   2.476 -       (partition 2
   2.477 -                  (take 100;;703
   2.478 -                        (drop
   2.479 -                         0x3A281
   2.480 -                        ;; 0x3A75D
   2.481 -                         (rom)))))))))
   2.482 +                      adr
   2.483 +                      )))
   2.484 +       (map cons
   2.485 +            (take-nth 2 (drop start (range)))
   2.486 +            (partition 2
   2.487 +                       (take 400;;703
   2.488 +                             (drop
   2.489 +                              start
   2.490 +                              ;; 0x3A75D
   2.491 +                              (rom)))))))))))
   2.492    
   2.493  (defn search-memory* [mem codes k]
   2.494    (loop [index 0
   2.495 @@ -1740,8 +2026,239 @@
   2.496         index-next
   2.497         codes
   2.498         matches))))
   2.499 -      
   2.500 -      
   2.501 +
   2.502 +
   2.503 +(def script-use-ball
   2.504 +  [0xFA ;; ld A, nn
   2.505 +   \_
   2.506 +   \_
   2.507 +   0xA7 ;; and A
   2.508 +   0xCA ;; JP Z
   2.509 +   \_
   2.510 +   \_
   2.511 +   0x3D ;; dec A
   2.512 +   0xC2 ;; JP NZ
   2.513 +   \_
   2.514 +   \_
   2.515 +   0xFA ;; LD A
   2.516 +   \_
   2.517 +   \_
   2.518 +   ])
   2.519 +
   2.520 +
   2.521 +
   2.522 +(defn search-pattern [ptn coll]
   2.523 +  (loop
   2.524 +      [index 0
   2.525 +       to-match ptn
   2.526 +       binds {}
   2.527 +
   2.528 +       next-index 1
   2.529 +       match-start 0
   2.530 +       matches []]
   2.531 +
   2.532 +    (cond
   2.533 +        (>= index (count coll)) matches
   2.534 +        (empty? to-match)
   2.535 +        (recur
   2.536 +         next-index
   2.537 +         ptn
   2.538 +         {}
   2.539 +         (inc next-index)
   2.540 +         next-index
   2.541 +         (conj match-start
   2.542 +               [(hex match-start) binds]))
   2.543 +
   2.544 +        :else
   2.545 +        (let [k (first to-match)
   2.546 +              v (nth coll index)]
   2.547 +        (cond
   2.548 +          (= k \_) ;; wildcard
   2.549 +          (recur
   2.550 +           (inc index)
   2.551 +           (rest to-match)
   2.552 +           binds
   2.553 +
   2.554 +           next-index
   2.555 +           match-start
   2.556 +           matches)
   2.557 +
   2.558 +          (keyword? k)
   2.559 +          (if (binds k)
   2.560 +            (if (= (binds k) v)
   2.561 +              (recur
   2.562 +               (inc index)
   2.563 +               (rest to-match)
   2.564 +               binds
   2.565 +               next-index
   2.566 +               match-start
   2.567 +               matches)
   2.568 +
   2.569 +              (recur
   2.570 +               next-index
   2.571 +               ptn
   2.572 +               {}
   2.573 +               (inc next-index)
   2.574 +               next-index
   2.575 +               matches))
   2.576 +              
   2.577 +              ;; ;; consistent bindings
   2.578 +              ;; (recur
   2.579 +              ;;  (inc index)
   2.580 +              ;;  (rest to-match)
   2.581 +              ;;  binds
   2.582 +
   2.583 +              ;;  next-index
   2.584 +              ;;  match-start
   2.585 +              ;;  matches)
   2.586 +
   2.587 +              ;; ;; inconsistent bindings
   2.588 +              ;; (recur
   2.589 +              ;;  next-index
   2.590 +              ;;  ptn
   2.591 +              ;;  {}
   2.592 +              ;;  (inc next-index)
   2.593 +              ;;  next-index
   2.594 +              ;;  matches))
   2.595 +              
   2.596 +            (if ((set (vals binds)) v)
   2.597 +              ;; bindings are not unique
   2.598 +              (recur
   2.599 +               next-index
   2.600 +               ptn
   2.601 +               {}
   2.602 +               (inc next-index)
   2.603 +               next-index
   2.604 +               matches)
   2.605 +
   2.606 +              ;; bindings are unique
   2.607 +              (recur
   2.608 +               (inc index)
   2.609 +               (rest to-match)
   2.610 +               (assoc binds k v)
   2.611 +
   2.612 +               next-index
   2.613 +               match-start
   2.614 +               matches)))
   2.615 +
   2.616 +          :else ;; k is just a number
   2.617 +          (if (= k v)
   2.618 +            (recur
   2.619 +             (inc index)
   2.620 +             (rest to-match)
   2.621 +             binds
   2.622 +
   2.623 +             next-index
   2.624 +             match-start
   2.625 +             matches)
   2.626 +
   2.627 +            (recur
   2.628 +             next-index
   2.629 +             ptn
   2.630 +             {}
   2.631 +             (inc next-index)
   2.632 +             next-index
   2.633 +             matches)))))))
   2.634 +
   2.635 +            
   2.636 +            
   2.637 +
   2.638 +              
   2.639 +
   2.640 +
   2.641 +
   2.642 +
   2.643 +(defn search-pattern* [ptn coll]
   2.644 +  (loop
   2.645 +      [
   2.646 +       binds {}
   2.647 +       index 0
   2.648 +       index-next 1
   2.649 +       start-match 0
   2.650 +       to-match ptn
   2.651 +       matches []]
   2.652 +
   2.653 +    (cond
   2.654 +        (>= index (count coll)) matches
   2.655 +        (empty? to-match)
   2.656 +        (recur
   2.657 +         {}
   2.658 +         index-next
   2.659 +         (inc index-next)
   2.660 +         index-next
   2.661 +         ptn
   2.662 +         (conj matches
   2.663 +               [(hex start-match) binds]))
   2.664 +
   2.665 +        :else
   2.666 +        (let [k (first to-match)
   2.667 +              v (nth coll index)]
   2.668 +        (cond
   2.669 +          (= k \_) ;; wildcard
   2.670 +          (recur
   2.671 +           binds
   2.672 +           (inc index)
   2.673 +           index-next
   2.674 +           start-match
   2.675 +           (rest to-match)
   2.676 +           matches)
   2.677 +
   2.678 +          (keyword? k)
   2.679 +          (if (binds k)
   2.680 +            (if (= (binds k) v)
   2.681 +              (recur
   2.682 +               binds
   2.683 +               (inc index)
   2.684 +               index-next
   2.685 +               start-match
   2.686 +               (rest to-match)
   2.687 +               matches)
   2.688 +              (recur
   2.689 +               {}
   2.690 +               index-next
   2.691 +               (inc index-next)
   2.692 +               index-next
   2.693 +               ptn
   2.694 +               matches))
   2.695 +            (if
   2.696 +                ;; every symbol must be bound to a different thing.
   2.697 +              ((set (vals binds)) v)
   2.698 +              (recur
   2.699 +               {}
   2.700 +               index-next
   2.701 +               (inc index-next)
   2.702 +               index-next
   2.703 +               ptn
   2.704 +               matches)
   2.705 +              (recur
   2.706 +               (assoc binds k v)
   2.707 +               (inc index)
   2.708 +               index-next
   2.709 +               start-match
   2.710 +               (rest to-match)
   2.711 +               matches)))
   2.712 +
   2.713 +          :else
   2.714 +          (if (= k v)
   2.715 +            (recur
   2.716 +             binds
   2.717 +             (inc index)
   2.718 +             index-next
   2.719 +             start-match
   2.720 +             (rest to-match)
   2.721 +             matches)
   2.722 +            (recur
   2.723 +             {}
   2.724 +             index-next
   2.725 +             (inc index-next)
   2.726 +             index-next
   2.727 +             ptn
   2.728 +             matches))
   2.729 +
   2.730 +
   2.731 +
   2.732 +)))))
   2.733 +             
   2.734  
   2.735  
   2.736