Notes on Deconstructing Pokemon Yellow

aurellem

Written by Dylan Holmes

1 Introduction

This article contains the results of my investigations with Pokémon Yellow as I searched for interesting data in the ROM. By using the Clojure language interface written by Robert1, I was able to interact with the game in real-time, sending commands and gathering data. The result is a manifestly accurate map of Pokémon Yellow; every result comes with runnable code that works. You can see the code and the output of every function and confirm for yourself that they are all correct. I hope you like the result!

To orient yourself, you can look for a specific topic in the table of contents above, or browse the map of the ROM, below.

If you have any questions or comments, please e-mail rlm@mit.edu.

2 Pokémon I

2.1 Names of each species

The names of the Pokémon species are stored in ROM@E8000. This name list is interesting, for a number of reasons:

  • The names are stored in internal order rather than in the familiar Pokédex order. This seemingly random order probably represents the order in which the authors created or programmed in the Pokémon; it's used throughout the game.
  • There is enough space allocated for 190 Pokémon. As I understand it, there were originally going to be 190 Pokémon in Generation I, but the creators decided to defer some to Generation II. This explains why many Gen I and Gen II Pokémon have the same aesthetic feel.
  • The list is pockmarked with random gaps, due to the strange internal ordering and the 39 unused spaces 2. These missing spaces are filled with the placeholder name MISSINGNO. (“Missing number”).

Each name is exactly ten letters long; whenever a name would be too short, the extra space is padded with the character 0x50.

See the data

Here you can see the raw data in three stages: in the first stage, we just grab the first few bytes starting from position 0xE8000. In the second stage, we partition the bytes into ten-letter chunks to show you where the names begin and end. In the final stage, we convert each byte into the letter it represents using the character-codes->str function. (0x50 is rendered as the symbol “ # ” for ease of reading).

(ns com.aurellem.gb.hxc
  (:use (com.aurellem.gb assembly characters gb-driver util mem-util
                         constants))
  (:import [com.aurellem.gb.gb_driver SaveState]))


(println (take 100 (drop 0xE8000 (rom))))

(println (partition 10 (take 100 (drop 0xE8000 (rom)))))

(println (character-codes->str (take 100 (drop 0xE8000 (rom)))))


(145 135 152 131 142 141 80 80 80 80 138 128 141 134 128 146 138 135 128 141 141 136 131 142 145 128 141 239 80 80 130 139 132 133 128 136 145 152 80 80 146 143 132 128 145 142 150 80 80 80 149 142 139 147 142 145 129 80 80 80 141 136 131 142 138 136 141 134 80 80 146 139 142 150 129 145 142 80 80 80 136 149 152 146 128 148 145 80 80 80 132 151 132 134 134 148 147 142 145 80)
((145 135 152 131 142 141 80 80 80 80) (138 128 141 134 128 146 138 135 128 141) (141 136 131 142 145 128 141 239 80 80) (130 139 132 133 128 136 145 152 80 80) (146 143 132 128 145 142 150 80 80 80) (149 142 139 147 142 145 129 80 80 80) (141 136 131 142 138 136 141 134 80 80) (146 139 142 150 129 145 142 80 80 80) (136 149 152 146 128 148 145 80 80 80) (132 151 132 134 134 148 147 142 145 80))
RHYDON####KANGASKHANNIDORAN♂##CLEFAIRY##SPEAROW###VOLTORB###NIDOKING##SLOWBRO###IVYSAUR###EXEGGUTOR#

Automatically grab the data.

(defn hxc-pokenames-raw
  "The hardcoded names of the 190 species in memory. List begins at
ROM@E8000. Although names in memory are padded with 0x50 to be 10 characters
  long, these names are stripped of padding. See also, hxc-pokedex-names"
  ([]
     (hxc-pokenames-raw com.aurellem.gb.gb-driver/original-rom))
  ([rom]
     (let [count-species 190
           name-length 10]
       (map character-codes->str
            (partition name-length
                       (map #(if (= 0x50 %) 0x00 %)
                            (take (* count-species name-length)
                                  (drop 0xE8000
                                        rom))))))))
(def hxc-pokenames
  (comp
   (partial map format-name)
   hxc-pokenames-raw))




(defn hxc-pokedex-names
  "The names of the pokemon in hardcoded pokedex order. List of the
  pokedex numbers of each pokemon (in internal order) begins at
ROM@410B1. See also, hxc-pokenames."
  ([] (hxc-pokedex-names
       com.aurellem.gb.gb-driver/original-rom))
  ([rom]
     (let [names (hxc-pokenames rom)]
       (#(mapv %
               ((comp range count keys) %))
        (zipmap
         (take (count names)
               (drop 0x410b1 rom))
         
         names)))))

2.2 Generic species information

(defn hxc-pokemon-base
  ([] (hxc-pokemon-base com.aurellem.gb.gb-driver/original-rom))
  ([rom]
     (let [entry-size 28
          
           pokemon (rest (hxc-pokedex-names))
 pkmn-count (inc(count pokemon))
           types (apply assoc {}
                        (interleave
                         (range)
                         pkmn-types)) ;;!! softcoded
           moves (apply assoc {}
                        (interleave
                         (range)
                         (map format-name
                              (hxc-move-names rom))))
           machines (hxc-machines)
           ]
       (zipmap
        pokemon
        (map
         (fn [[n
               rating-hp
               rating-atk
               rating-def
               rating-speed
               rating-special
               type-1
               type-2
               rarity ;; catch rate
               rating-xp ;; base exp yield
               pic-dimensions ;; tile_width|tile_height (8px/tile)
               ptr-pic-obverse-1
               ptr-pic-obverse-2
               ptr-pic-reverse-1
               ptr-pic-reverse-2
               move-1 ;; attacks known at level 0 [i.e. by default]
               move-2 ;; (0 for none)
               move-3
               move-4
               growth-rate
               &
               TMs|HMs]]
           (let
               [base-moves
                (mapv moves
                      ((comp
                        ;; since the game uses zero as a delimiter,
                        ;; it must also increment all move indices by 1.
                        ;; heren we decrement to correct this.
                        (partial map dec)
                        (partial take-while (comp not zero?)))
                       [move-1 move-2 move-3 move-4]))
                
                types
                (set (list (types type-1)
                           (types type-2)))
                TMs|HMs
                (map
                 (comp
                  (partial map first)
                  (partial remove (comp zero? second)))
                 (split-at
                  50
                  (map vector
                       (rest(range))
                       (reduce concat
                               (map
                                #(take 8
                                       (concat (bit-list %)
                                               (repeat 0)))
                                
                                TMs|HMs)))))
                
                TMs  (vec (first TMs|HMs))
                HMs (take 5 (map (partial + -50) (vec (second TMs|HMs))))
                
                
                ]
             
             
             {:dex# n
              :base-moves base-moves
              :types types
              :TMs TMs
              :HMs HMs
              :base-hp rating-hp
              :base-atk rating-atk
              :base-def rating-def
              :base-speed rating-speed
              :base-special rating-special
              :o0 pic-dimensions
              :o1 ptr-pic-obverse-1
              :o2 ptr-pic-obverse-2
              }))
         
         (partition entry-size
                    (take (* entry-size pkmn-count)
                          (drop 0x383DE
                                rom))))))))

2.3 Pokémon evolutions

(defn format-evo
  "Parse a sequence of evolution data, returning a map. First is the
method: 0 = end-evolution-data. 1 = level-up, 2 = item, 3 = trade. Next is an item id, if the
  method of evolution is by item (only stones will actually make pokemon
  evolve, for some auxillary reason.) Finally, the minimum level for
  evolution to occur (level 1 means no limit, which is used for trade
  and item evolutions), followed by the internal id of the pokemon
  into which to evolve. Hence, level up and trade evolutions are
  described with 3
  bytes; item evolutions with four."
  [coll]
  (let [method (first coll)]
    (cond (empty? coll) []
          (= 0 method) [] ;; just in case
          (= 1 method) ;; level-up evolution
          (conj (format-evo (drop 3 coll))
                            {:method :level-up
                             :min-level (nth coll 1)
                             :into (dec (nth coll 2))})
          
          (= 2 method) ;; item evolution
          (conj (format-evo (drop 4 coll))
                {:method :item
                 :item (dec (nth coll 1))
                 :min-level (nth coll 2)
                 :into (dec (nth coll 3))})

          (= 3 method) ;; trade evolution
          (conj (format-evo (drop 3 coll))
                {:method :trade
                 :min-level (nth coll 1) ;; always 1 for trade.
                 :into (dec (nth coll 2))}))))


(defn hxc-ptrs-evolve
  "A hardcoded collection of 190 pointers to alternating evolution/learnset data,
in internal order."
  ([]
     (hxc-ptrs-evolve com.aurellem.gb.gb-driver/original-rom))
  ([rom]
     (let [
           pkmn-count (count (hxc-pokenames-raw)) ;; 190
           ptrs
           (map (fn [[a b]] (low-high a b))
                (partition 2
                           (take (* 2 pkmn-count)
                                 (drop 0x3b1e5 rom))))]
       (map (partial + 0x34000) ptrs)

       )))
(defn hxc-evolution
  "Hardcoded evolution data in memory. The data exists at ROM@34000,
  sorted by internal order. Pointers to the data exist at ROM@3B1E5; see also, hxc-ptrs-evolve."
  ([] (hxc-evolution com.aurellem.gb.gb-driver/original-rom))
  ([rom]
       (apply assoc {}
               (interleave
                (hxc-pokenames rom)
                (map
                 (comp
                  format-evo
                  (partial take-while (comp not zero?))
                  #(drop % rom))
                 (hxc-ptrs-evolve rom)
                 )))))

(defn hxc-evolution-pretty
  "Like hxc-evolution, except it uses the names of items and pokemon
--- grabbed from ROM --- rather than their numerical identifiers."
  ([] (hxc-evolution-pretty com.aurellem.gb.gb-driver/original-rom))
  ([rom]
     (let
         [poke-names (vec (hxc-pokenames rom))
          item-names (vec (hxc-items rom))
          use-names
          (fn [m]
            (loop [ks (keys m) new-map m]
              (let [k (first ks)]
                (cond (nil? ks) new-map
                      (= k :into)
                      (recur
                       (next ks)
                       (assoc new-map
                         :into
                         (poke-names
                          (:into
                           new-map))))
                      (= k :item)
                      (recur
                       (next ks)
                       (assoc new-map
                         :item
                         (item-names
                          (:item new-map))))
                      :else
                      (recur
                       (next ks)
                       new-map)
                      ))))]

       (into {}
             (map (fn [[pkmn evo-coll]]
                    [pkmn (map use-names evo-coll)])
                  (hxc-evolution rom))))))


2.4 Level-up moves (learnsets)

(defn hxc-learnsets
  "Hardcoded map associating pokemon names to lists of pairs [lvl
  move] of abilities they learn as they level up. The data
exists at ROM@34000, sorted by internal order. Pointers to the data
  exist at ROM@3B1E5; see also, hxc-ptrs-evolve"
  ([] (hxc-learnsets com.aurellem.gb.gb-driver/original-rom))
  ([rom]
     (apply assoc
            {}
            (interleave
             (hxc-pokenames rom)
             (map (comp
                   (partial map
                            (fn [[lvl mv]] [lvl (dec mv)]))
                   (partial partition 2)
                   ;; keep the learnset data
                   (partial take-while (comp not zero?))
                   ;; skip the evolution data
                   rest
                   (partial drop-while (comp not zero?)))
                  (map #(drop % rom) 
                       (hxc-ptrs-evolve rom)))))))

(defn hxc-learnsets-pretty
  "Live hxc-learnsets except it reports the name of each move --- as
it appears in rom --- rather than the move index."
  ([] (hxc-learnsets-pretty com.aurellem.gb.gb-driver/original-rom))
  ([rom]
     (let [moves (vec(map format-name (hxc-move-names)))]
       (into {}
             (map (fn [[pkmn learnset]]
                    [pkmn (map (fn [[lvl mv]] [lvl (moves mv)])
                               learnset)])
                  (hxc-learnsets rom))))))
             
                                  

3 Pokémon II : the Pokédex

3.1 Species vital stats

(defn hxc-pokedex-stats
  "The hardcoded pokedex stats (species height weight) in memory. List
begins at ROM@40687"
  ([] (hxc-pokedex-stats com.aurellem.gb.gb-driver/original-rom))
  ([rom]
     (let [pokedex-names (zipmap (range) (hxc-pokedex-names rom))
           pkmn-count (count pokedex-names)
           ]
     ((fn capture-stats
        [n stats data]
        (if (zero? n) stats
            (let [[species
                   [_
                    height-ft
                    height-in
                    weight-1
                    weight-2
                    _
                    dex-ptr-1
                    dex-ptr-2
                    dex-bank
                    _
                    & data]]
                  (split-with (partial not= 0x50) data)]
              (recur (dec n)
                     (assoc stats
                       (pokedex-names (- pkmn-count (dec n)))
                       {:species
                        (format-name (character-codes->str species))
                        :height-ft
                        height-ft
                        :height-in
                        height-in
                        :weight
                        (/ (low-high weight-1 weight-2) 10.)
                        
                    ;;    :text
                    ;;    (character-codes->str
                    ;;     (take-while
                    ;;      (partial not= 0x50)
                    ;;      (drop
                    ;;       (+ 0xB8000
                    ;;          -0x4000
                    ;;          (low-high dex-ptr-1 dex-ptr-2))
                    ;;       rom)))
                        })
                     
                     data)
              
              
              )))
      
      pkmn-count
      {}
      (drop 0x40687 rom)))       ))

3.2 Species synopses

(def hxc-pokedex-text-raw
  "The hardcoded pokedex entries in memory. List begins at
ROM@B8000, shortly before move names."
  (hxc-thunk-words 0xB8000 14754))




(defn hxc-pokedex-text
  "The hardcoded pokedex entries in memory, presented as an
associative hash map. List begins at ROM@B8000."
  ([] (hxc-pokedex-text com.aurellem.gb.gb-driver/original-rom))
  ([rom]
     (zipmap
      (hxc-pokedex-names rom)
      (cons nil ;; for missingno.
            (hxc-pokedex-text-raw rom)))))

3.3 Pokémon cries

See the data

Here, you can see that each Pokémon's cry data consists of three bytes: the cry-id, which is the basic sound byte to use, the pitch, which determines how high or low to make the sound byte, and the length, which is the amount of the sound byte to play.

Even though there are only a few different basic sound bytes (cry ids) to build from, by varying the pitch and length, you can create a wide variety of different Pokémon cries.

(ns com.aurellem.gb.hxc
  (:use (com.aurellem.gb assembly characters gb-driver util mem-util
                         constants))
  (:import [com.aurellem.gb.gb_driver SaveState]))

(->>
 (rom)
 (drop 0x39462)
 (take 12)
 (println))

(->>
 (rom)
 (drop 0x39462)
 (take 12)
 (partition 3)
 (map vec)
 (println))

(->>
 (rom)
 (drop 0x39462)
 (take 12)
 (partition 3)
 (map
  (fn [[id pitch length]]
    {:cry-id id :pitch pitch :length length}))
 (println))

(17 0 128 3 0 128 0 0 128 25 204 1)
([17 0 128] [3 0 128] [0 0 128] [25 204 1])
({:cry-id 17, :pitch 0, :length 128} {:cry-id 3, :pitch 0, :length 128} {:cry-id 0, :pitch 0, :length 128} {:cry-id 25, :pitch 204, :length 1})

It is interesting to note which Pokémon use the same basic cry-id — I call these cry groups. Here, you can see which Pokémon belong to the same cry group.

(ns com.aurellem.gb.hxc
  (:use (com.aurellem.gb assembly characters gb-driver util mem-util
                         constants))
  (:import [com.aurellem.gb.gb_driver SaveState]))

(println "POKEMON CRY GROUPS")
(doall
 (map println
      (let [cry-id
            (->>
             (rom)
             (drop 0x39462)  ;; get the cry data
             (partition 3)   ;; partition it into groups of three
             (map first)     ;; keep only the first item, the cry-id
             (zipmap (hxc-pokenames)) ;; associate each pokemon with its cry-id
             )]
        
        (->> (hxc-pokenames)                 ;; start with the list of pokemon
             (remove (partial = :missingno.)) ;; remove missingnos
             (sort-by cry-id)
             (partition-by cry-id)
             (map vec)))))

POKEMON CRY GROUPS
[:nidoran♂ :sandshrew :sandslash :nidorino]
[:nidoran♀ :nidorina]
[:slowpoke]
[:kangaskhan]
[:rhyhorn :magmar :charmander :charmeleon :charizard]
[:grimer :snorlax]
[:voltorb :electabuzz :electrode]
[:gengar :muk]
[:marowak :oddish :gloom]
[:nidoking :moltres :articuno :raichu]
[:nidoqueen :mankey :primeape]
[:exeggcute :diglett :doduo :dodrio :dugtrio]
[:lickitung :hitmonchan :seel :dewgong]
[:exeggutor :drowzee :jynx :hypno]
[:pidgey :poliwag :ditto :jigglypuff :wigglytuff :poliwhirl :poliwrath]
[:ivysaur :dragonite :pikachu :dratini :dragonair :bulbasaur :venusaur]
[:spearow :farfetch'd]
[:rhydon]
[:tangela :hitmonlee :golem :koffing :weezing]
[:blastoise :kakuna :beedrill]
[:pinsir :chansey :pidgeotto :pidgeot]
[:arcanine :weedle]
[:scyther :kabuto :caterpie :butterfree :goldeen :seaking]
[:gyarados :onix :arbok :ekans :magikarp]
[:shellder :fearow :zapdos :kabutops :cloyster]
[:clefairy :cubone :meowth :horsea :seadra :clefable :persian]
[:tentacool :venonat :eevee :flareon :jolteon :vaporeon :venomoth :tentacruel]
[:lapras]
[:gastly :kadabra :magneton :metapod :haunter :abra :alakazam :magnemite]
[:tauros :zubat :golbat :squirtle :wartortle]
[:mew :staryu :parasect :paras :mewtwo :starmie]
[:slowbro :growlithe :machoke :omanyte :omastar :machop :machamp]
[:mr.mime :krabby :kingler]
[:psyduck :golduck :bellsprout]
[:rattata :raticate]
[:aerodactyl :vileplume]
[:graveler :vulpix :ninetales :geodude]
[:ponyta :rapidash :porygon :weepinbell :victreebel]

Automatically grab the data

(defn hxc-cry
  "The pokemon cry data in internal order. List begins at ROM@39462"
  ([](hxc-cry com.aurellem.gb.gb-driver/original-rom))
  ([rom]
     (zipmap
      (hxc-pokenames rom)
      (map
       (fn [[cry-id pitch length]]
         {:cry-id cry-id
         :pitch pitch
          :length length}
         )
       (partition 3
                  (drop 0x39462 rom))))))

(defn hxc-cry-groups
  ([] (hxc-cry-groups com.aurellem.gb.gb-driver/original-rom))
  ([rom]
     (map #(mapv first
                (filter
                 (fn [[k v]]
                   (= % (:cry-id v)))
                 (hxc-cry)))
          ((comp
            range
            count
            set
            (partial map :cry-id)
            vals
            hxc-cry)
           rom))))


(defn cry-conversion!
  "Convert Porygon's cry in ROM to be the cry of the given pokemon."
  [pkmn]
  (write-rom!
   (rewrite-memory
    (vec(rom))
    0x3965D 
    (map second
         ((hxc-cry) pkmn)))))

4 Items

4.1 Item names

See the data

(ns com.aurellem.gb.hxc
  (:use (com.aurellem.gb assembly characters gb-driver util mem-util
                         constants))
  (:import [com.aurellem.gb.gb_driver SaveState]))

(println (take 100 (drop 0x045B7 (rom))))

(println
 (partition-by
  (partial = 0x50)
  (take 100 (drop 0x045B7 (rom)))))

(println
 (map character-codes->str
      (partition-by
       (partial = 0x50)
       (take 100 (drop 0x045B7 (rom))))))


(140 128 146 147 132 145 127 129 128 139 139 80 148 139 147 145 128 127 129 128 139 139 80 134 145 132 128 147 127 129 128 139 139 80 143 142 138 186 127 129 128 139 139 80 147 142 150 141 127 140 128 143 80 129 136 130 152 130 139 132 80 230 230 230 230 230 80 146 128 133 128 145 136 127 129 128 139 139 80 143 142 138 186 131 132 151 80 140 142 142 141 127 146 147 142 141 132 80 128 141)
((140 128 146 147 132 145 127 129 128 139 139) (80) (148 139 147 145 128 127 129 128 139 139) (80) (134 145 132 128 147 127 129 128 139 139) (80) (143 142 138 186 127 129 128 139 139) (80) (147 142 150 141 127 140 128 143) (80) (129 136 130 152 130 139 132) (80) (230 230 230 230 230) (80) (146 128 133 128 145 136 127 129 128 139 139) (80) (143 142 138 186 131 132 151) (80) (140 142 142 141 127 146 147 142 141 132) (80) (128 141))
(MASTER BALL # ULTRA BALL # GREAT BALL # POKé BALL # TOWN MAP # BICYCLE # ????? # SAFARI BALL # POKéDEX # MOON STONE # AN)

Automatically grab the data

(def hxc-items-raw
  "The hardcoded names of the items in memory. List begins at
ROM@045B7"
  (hxc-thunk-words 0x45B7 870))

(def hxc-items
  "The hardcoded names of the items in memory, presented as
  keywords. List begins at ROM@045B7. See also, hxc-items-raw."
  (comp (partial map format-name) hxc-items-raw))

4.2 Item prices

(ns com.aurellem.gb.hxc
  (:use (com.aurellem.gb assembly characters gb-driver util mem-util
                         constants))
  (:import [com.aurellem.gb.gb_driver SaveState]))

(println (take 90 (drop 0x4495 (rom))))

(println
 (partition 3
            (take 90 (drop 0x4495 (rom)))))

(println
 (partition 3
            (map hex
                 (take 90 (drop 0x4495 (rom))))))

(println
 (map decode-bcd
      (map butlast
           (partition 3
                      (take 90 (drop 0x4495 (rom)))))))

(println
 (map
  vector
  (hxc-items (rom))
  (map decode-bcd
       (map butlast
            (partition 3
                       (take 90 (drop 0x4495 (rom))))))))
 




(0 0 0 18 0 0 6 0 0 2 0 0 0 0 0 0 0 0 0 0 0 16 0 0 0 0 0 0 0 0 1 0 0 2 80 0 2 80 0 2 0 0 2 0 0 48 0 0 37 0 0 21 0 0 7 0 0 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 5 80 0 3 80 0)
((0 0 0) (18 0 0) (6 0 0) (2 0 0) (0 0 0) (0 0 0) (0 0 0) (16 0 0) (0 0 0) (0 0 0) (1 0 0) (2 80 0) (2 80 0) (2 0 0) (2 0 0) (48 0 0) (37 0 0) (21 0 0) (7 0 0) (3 0 0) (0 0 0) (0 0 0) (0 0 0) (0 0 0) (0 0 0) (0 0 0) (0 0 0) (0 0 0) (5 80 0) (3 80 0))
((0x0 0x0 0x0) (0x12 0x0 0x0) (0x6 0x0 0x0) (0x2 0x0 0x0) (0x0 0x0 0x0) (0x0 0x0 0x0) (0x0 0x0 0x0) (0x10 0x0 0x0) (0x0 0x0 0x0) (0x0 0x0 0x0) (0x1 0x0 0x0) (0x2 0x50 0x0) (0x2 0x50 0x0) (0x2 0x0 0x0) (0x2 0x0 0x0) (0x30 0x0 0x0) (0x25 0x0 0x0) (0x15 0x0 0x0) (0x7 0x0 0x0) (0x3 0x0 0x0) (0x0 0x0 0x0) (0x0 0x0 0x0) (0x0 0x0 0x0) (0x0 0x0 0x0) (0x0 0x0 0x0) (0x0 0x0 0x0) (0x0 0x0 0x0) (0x0 0x0 0x0) (0x5 0x50 0x0) (0x3 0x50 0x0))
(0 1200 600 200 0 0 0 1000 0 0 100 250 250 200 200 3000 2500 1500 700 300 0 0 0 0 0 0 0 0 550 350)
([:master-ball 0] [:ultra-ball 1200] [:great-ball 600] [:poké-ball 200] [:town-map 0] [:bicycle 0] [:????? 0] [:safari-ball 1000] [:pokédex 0] [:moon-stone 0] [:antidote 100] [:burn-heal 250] [:ice-heal 250] [:awakening 200] [:parlyz-heal 200] [:full-restore 3000] [:max-potion 2500] [:hyper-potion 1500] [:super-potion 700] [:potion 300] [:boulderbadge 0] [:cascadebadge 0] [:thunderbadge 0] [:rainbowbadge 0] [:soulbadge 0] [:marshbadge 0] [:volcanobadge 0] [:earthbadge 0] [:escape-rope 550] [:repel 350])

(defn hxc-item-prices
  "The hardcoded list of item prices in memory. List begins at ROM@4495"
  ([] (hxc-item-prices com.aurellem.gb.gb-driver/original-rom))
  ([rom]
     (let [items (hxc-items rom)
           price-size 3]
       (zipmap items
               (map (comp
                     ;; zero-cost items are "priceless"
                     #(if (zero? %) :priceless %)
                     decode-bcd butlast)
                    (partition price-size
                               (take (* price-size (count items))
                                     (drop 0x4495 rom))))))))

4.3 Vendor inventories

(defn hxc-shops
  ([] (hxc-shops com.aurellem.gb.gb-driver/original-rom))
  ([rom]
     (let [items (zipmap (range) (hxc-items rom))

           ;; temporarily softcode the TM items
           items (into
                  items
                  (map (juxt identity
                             (comp keyword
                                   (partial str "tm-")
                                   (partial + 1 -200)
                                   )) 
                       (take 200 (drop 200 (range)))))
                       
           ]

       ((fn parse-shop [coll [num-items & items-etc]]
          (let [inventory (take-while
                           (partial not= 0xFF)
                           items-etc)
               [separator & items-etc] (drop num-items (rest items-etc))]
           (if (= separator 0x50)
             (map (partial mapv (comp items dec)) (conj coll inventory))
             (recur (conj coll inventory) items-etc)
             )
         ))

        '()
        (drop 0x233C rom))

     
     )))

5 Types

5.1 Names of types

5.2 Type effectiveness

(ns com.aurellem.gb.hxc
  (:use (com.aurellem.gb assembly characters gb-driver util mem-util
                         constants))
  (:import [com.aurellem.gb.gb_driver SaveState]))


;; POKEMON TYPES

(println pkmn-types) ;; these are the pokemon types
(println (map vector (range) pkmn-types)) ;; each type has an id number.

(newline)




;;; TYPE EFFECTIVENESS

(println (take 15 (drop 0x3E5FA (rom))))
(println (partition 3 (take 15 (drop 0x3E5FA (rom)))))

(println
 (map
  (fn [[atk-type def-type multiplier]]
    (list atk-type def-type (/ multiplier 10.)))

  (partition 3
             (take 15 (drop 0x3E5FA (rom))))))


(println
 (map
  (fn [[atk-type def-type multiplier]]
    [
     (get pkmn-types atk-type)
     (get pkmn-types def-type)
     (/ multiplier 10.)
    ])
  
  (partition 3
             (take 15 (drop 0x3E5FA (rom))))))

[:normal :fighting :flying :poison :ground :rock :bird :bug :ghost :A :B :C :D :E :F :G :H :I :J :K :fire :water :grass :electric :psychic :ice :dragon]
([0 :normal] [1 :fighting] [2 :flying] [3 :poison] [4 :ground] [5 :rock] [6 :bird] [7 :bug] [8 :ghost] [9 :A] [10 :B] [11 :C] [12 :D] [13 :E] [14 :F] [15 :G] [16 :H] [17 :I] [18 :J] [19 :K] [20 :fire] [21 :water] [22 :grass] [23 :electric] [24 :psychic] [25 :ice] [26 :dragon])

(21 20 20 20 22 20 20 25 20 22 21 20 23 21 20)
((21 20 20) (20 22 20) (20 25 20) (22 21 20) (23 21 20))
((21 20 2.0) (20 22 2.0) (20 25 2.0) (22 21 2.0) (23 21 2.0))
([:water :fire 2.0] [:fire :grass 2.0] [:fire :ice 2.0] [:grass :water 2.0] [:electric :water 2.0])

(defn hxc-advantage
  ;; in-game multipliers are stored as 10x their effective value
  ;; to allow for fractional multipliers like 1/2
  
  "The hardcoded type advantages in memory, returned as tuples of
  atk-type def-type multiplier. By default (i.e. if not listed here),
the multiplier is 1. List begins at 0x3E62D."
  ([] (hxc-advantage com.aurellem.gb.gb-driver/original-rom))
  ([rom]
     (map
      (fn [[atk def mult]] [(get pkmn-types atk (hex atk))
                            (get pkmn-types def (hex def))
                            (/ mult 10)])
      (partition 3
                 (take-while (partial not= 0xFF)
                             (drop 0x3E5FA rom))))))

6 Moves

6.1 Names of moves

See the data

(ns com.aurellem.gb.hxc
  (:use (com.aurellem.gb assembly characters gb-driver util mem-util
                         constants))
  (:import [com.aurellem.gb.gb_driver SaveState]))

(println (take 100 (drop 0xBC000 (rom))))

(println
 (partition-by
  (partial = 0x50)
  (take 100 (drop 0xBC000 (rom)))))

(println
 (map character-codes->str
      (partition-by
       (partial = 0x50)
       (take 100 (drop 0xBC000 (rom))))))


(143 142 148 141 131 80 138 128 145 128 147 132 127 130 135 142 143 80 131 142 148 129 139 132 146 139 128 143 80 130 142 140 132 147 127 143 148 141 130 135 80 140 132 134 128 127 143 148 141 130 135 80 143 128 152 127 131 128 152 80 133 136 145 132 127 143 148 141 130 135 80 136 130 132 127 143 148 141 130 135 80 147 135 148 141 131 132 145 143 148 141 130 135 80 146 130 145 128 147 130)
((143 142 148 141 131) (80) (138 128 145 128 147 132 127 130 135 142 143) (80) (131 142 148 129 139 132 146 139 128 143) (80) (130 142 140 132 147 127 143 148 141 130 135) (80) (140 132 134 128 127 143 148 141 130 135) (80) (143 128 152 127 131 128 152) (80) (133 136 145 132 127 143 148 141 130 135) (80) (136 130 132 127 143 148 141 130 135) (80) (147 135 148 141 131 132 145 143 148 141 130 135) (80) (146 130 145 128 147 130))
(POUND # KARATE CHOP # DOUBLESLAP # COMET PUNCH # MEGA PUNCH # PAY DAY # FIRE PUNCH # ICE PUNCH # THUNDERPUNCH # SCRATC)

Automatically grab the data

(def hxc-move-names
  "The hardcoded move names in memory. List begins at ROM@BC000"
  (hxc-thunk-words 0xBC000 1551))

6.2 Properties of moves

(defn hxc-move-data
  "The hardcoded (basic (move effects)) in memory. List begins at
0x38000. Returns a map of {:name :power :accuracy :pp :fx-id
  :fx-txt}. The move descriptions are handwritten, not hardcoded."
  ([]
     (hxc-move-data com.aurellem.gb.gb-driver/original-rom))
  ([rom]
     (let [names (vec (hxc-move-names rom))
           move-count (count names)
           move-size 6
           types pkmn-types ;;; !! hardcoded types
           ]
       (zipmap (map format-name names)
               (map
                (fn [[idx effect power type-id accuracy pp]]
                  {:name (names (dec idx))
                   :power power
                   :accuracy  accuracy
                   :pp pp
                   :type (types type-id)
                   :fx-id effect
                   :fx-txt (get move-effects effect) 
                   }
                  )
                
                (partition move-size
                           (take (* move-size move-count)
                                 (drop 0x38000 rom))))))))
  


(defn hxc-move-data*
  "Like hxc-move-data, but reports numbers as hexadecimal symbols instead."
  ([]
     (hxc-move-data* com.aurellem.gb.gb-driver/original-rom))
  ([rom]
     (let [names (vec (hxc-move-names rom))
           move-count (count names)
           move-size 6
           format-name (fn [s]
                         (keyword (.toLowerCase
                                   (apply str
                                          (map #(if (= % \space) "-" %) s)))))
           ]
       (zipmap (map format-name names)
               (map
                (fn [[idx effect power type accuracy pp]]
                  {:name (names (dec idx))
                   :power power
                   :accuracy (hex accuracy)
                   :pp pp
                   :fx-id (hex effect)
                   :fx-txt (get move-effects effect) 
                   }
                  )
                
                (partition move-size
                           (take (* move-size move-count)
                                 (drop 0x38000 rom))))))))
  

6.3 TM and HM moves

(ns com.aurellem.gb.hxc
  (:use (com.aurellem.gb assembly characters gb-driver util mem-util
                         constants))
  (:import [com.aurellem.gb.gb_driver SaveState]))


(println (hxc-move-names))
(println (map vector (rest(range)) (hxc-move-names)))

(newline)

(println (take 55 (drop 0x1232D (rom))))

(println
 (interpose "."
            (map
             (zipmap (rest (range)) (hxc-move-names))
             (take 55 (drop 0x1232D (rom))))))

(POUND KARATE CHOP DOUBLESLAP COMET PUNCH MEGA PUNCH PAY DAY FIRE PUNCH ICE PUNCH THUNDERPUNCH SCRATCH VICEGRIP GUILLOTINE RAZOR WIND SWORDS DANCE CUT GUST WING ATTACK WHIRLWIND FLY BIND SLAM VINE WHIP STOMP DOUBLE KICK MEGA KICK JUMP KICK ROLLING KICK SAND-ATTACK HEADBUTT HORN ATTACK FURY ATTACK HORN DRILL TACKLE BODY SLAM WRAP TAKE DOWN THRASH DOUBLE-EDGE TAIL WHIP POISON STING TWINEEDLE PIN MISSILE LEER BITE GROWL ROAR SING SUPERSONIC SONICBOOM DISABLE ACID EMBER FLAMETHROWER MIST WATER GUN HYDRO PUMP SURF ICE BEAM BLIZZARD PSYBEAM BUBBLEBEAM AURORA BEAM HYPER BEAM PECK DRILL PECK SUBMISSION LOW KICK COUNTER SEISMIC TOSS STRENGTH ABSORB MEGA DRAIN LEECH SEED GROWTH RAZOR LEAF SOLARBEAM POISONPOWDER STUN SPORE SLEEP POWDER PETAL DANCE STRING SHOT DRAGON RAGE FIRE SPIN THUNDERSHOCK THUNDERBOLT THUNDER WAVE THUNDER ROCK THROW EARTHQUAKE FISSURE DIG TOXIC CONFUSION PSYCHIC HYPNOSIS MEDITATE AGILITY QUICK ATTACK RAGE TELEPORT NIGHT SHADE MIMIC SCREECH DOUBLE TEAM RECOVER HARDEN MINIMIZE SMOKESCREEN CONFUSE RAY WITHDRAW DEFENSE CURL BARRIER LIGHT SCREEN HAZE REFLECT FOCUS ENERGY BIDE METRONOME MIRROR MOVE SELFDESTRUCT EGG BOMB LICK SMOG SLUDGE BONE CLUB FIRE BLAST WATERFALL CLAMP SWIFT SKULL BASH SPIKE CANNON CONSTRICT AMNESIA KINESIS SOFTBOILED HI JUMP KICK GLARE DREAM EATER POISON GAS BARRAGE LEECH LIFE LOVELY KISS SKY ATTACK TRANSFORM BUBBLE DIZZY PUNCH SPORE FLASH PSYWAVE SPLASH ACID ARMOR CRABHAMMER EXPLOSION FURY SWIPES BONEMERANG REST ROCK SLIDE HYPER FANG SHARPEN CONVERSION TRI ATTACK SUPER FANG SLASH SUBSTITUTE STRUGGLE)
([1 POUND] [2 KARATE CHOP] [3 DOUBLESLAP] [4 COMET PUNCH] [5 MEGA PUNCH] [6 PAY DAY] [7 FIRE PUNCH] [8 ICE PUNCH] [9 THUNDERPUNCH] [10 SCRATCH] [11 VICEGRIP] [12 GUILLOTINE] [13 RAZOR WIND] [14 SWORDS DANCE] [15 CUT] [16 GUST] [17 WING ATTACK] [18 WHIRLWIND] [19 FLY] [20 BIND] [21 SLAM] [22 VINE WHIP] [23 STOMP] [24 DOUBLE KICK] [25 MEGA KICK] [26 JUMP KICK] [27 ROLLING KICK] [28 SAND-ATTACK] [29 HEADBUTT] [30 HORN ATTACK] [31 FURY ATTACK] [32 HORN DRILL] [33 TACKLE] [34 BODY SLAM] [35 WRAP] [36 TAKE DOWN] [37 THRASH] [38 DOUBLE-EDGE] [39 TAIL WHIP] [40 POISON STING] [41 TWINEEDLE] [42 PIN MISSILE] [43 LEER] [44 BITE] [45 GROWL] [46 ROAR] [47 SING] [48 SUPERSONIC] [49 SONICBOOM] [50 DISABLE] [51 ACID] [52 EMBER] [53 FLAMETHROWER] [54 MIST] [55 WATER GUN] [56 HYDRO PUMP] [57 SURF] [58 ICE BEAM] [59 BLIZZARD] [60 PSYBEAM] [61 BUBBLEBEAM] [62 AURORA BEAM] [63 HYPER BEAM] [64 PECK] [65 DRILL PECK] [66 SUBMISSION] [67 LOW KICK] [68 COUNTER] [69 SEISMIC TOSS] [70 STRENGTH] [71 ABSORB] [72 MEGA DRAIN] [73 LEECH SEED] [74 GROWTH] [75 RAZOR LEAF] [76 SOLARBEAM] [77 POISONPOWDER] [78 STUN SPORE] [79 SLEEP POWDER] [80 PETAL DANCE] [81 STRING SHOT] [82 DRAGON RAGE] [83 FIRE SPIN] [84 THUNDERSHOCK] [85 THUNDERBOLT] [86 THUNDER WAVE] [87 THUNDER] [88 ROCK THROW] [89 EARTHQUAKE] [90 FISSURE] [91 DIG] [92 TOXIC] [93 CONFUSION] [94 PSYCHIC] [95 HYPNOSIS] [96 MEDITATE] [97 AGILITY] [98 QUICK ATTACK] [99 RAGE] [100 TELEPORT] [101 NIGHT SHADE] [102 MIMIC] [103 SCREECH] [104 DOUBLE TEAM] [105 RECOVER] [106 HARDEN] [107 MINIMIZE] [108 SMOKESCREEN] [109 CONFUSE RAY] [110 WITHDRAW] [111 DEFENSE CURL] [112 BARRIER] [113 LIGHT SCREEN] [114 HAZE] [115 REFLECT] [116 FOCUS ENERGY] [117 BIDE] [118 METRONOME] [119 MIRROR MOVE] [120 SELFDESTRUCT] [121 EGG BOMB] [122 LICK] [123 SMOG] [124 SLUDGE] [125 BONE CLUB] [126 FIRE BLAST] [127 WATERFALL] [128 CLAMP] [129 SWIFT] [130 SKULL BASH] [131 SPIKE CANNON] [132 CONSTRICT] [133 AMNESIA] [134 KINESIS] [135 SOFTBOILED] [136 HI JUMP KICK] [137 GLARE] [138 DREAM EATER] [139 POISON GAS] [140 BARRAGE] [141 LEECH LIFE] [142 LOVELY KISS] [143 SKY ATTACK] [144 TRANSFORM] [145 BUBBLE] [146 DIZZY PUNCH] [147 SPORE] [148 FLASH] [149 PSYWAVE] [150 SPLASH] [151 ACID ARMOR] [152 CRABHAMMER] [153 EXPLOSION] [154 FURY SWIPES] [155 BONEMERANG] [156 REST] [157 ROCK SLIDE] [158 HYPER FANG] [159 SHARPEN] [160 CONVERSION] [161 TRI ATTACK] [162 SUPER FANG] [163 SLASH] [164 SUBSTITUTE] [165 STRUGGLE])

(5 13 14 18 25 92 32 34 36 38 61 55 58 59 63 6 66 68 69 99 72 76 82 85 87 89 90 91 94 100 102 104 115 117 118 120 121 126 129 130 135 138 143 156 86 149 153 157 161 164 15 19 57 70 148)
(MEGA PUNCH . RAZOR WIND . SWORDS DANCE . WHIRLWIND . MEGA KICK . TOXIC . HORN DRILL . BODY SLAM . TAKE DOWN . DOUBLE-EDGE . BUBBLEBEAM . WATER GUN . ICE BEAM . BLIZZARD . HYPER BEAM . PAY DAY . SUBMISSION . COUNTER . SEISMIC TOSS . RAGE . MEGA DRAIN . SOLARBEAM . DRAGON RAGE . THUNDERBOLT . THUNDER . EARTHQUAKE . FISSURE . DIG . PSYCHIC . TELEPORT . MIMIC . DOUBLE TEAM . REFLECT . BIDE . METRONOME . SELFDESTRUCT . EGG BOMB . FIRE BLAST . SWIFT . SKULL BASH . SOFTBOILED . DREAM EATER . SKY ATTACK . REST . THUNDER WAVE . PSYWAVE . EXPLOSION . ROCK SLIDE . TRI ATTACK . SUBSTITUTE . CUT . FLY . SURF . STRENGTH . FLASH)

(defn hxc-machines
  "The hardcoded moves taught by TMs and HMs. List begins at ROM@1232D."
  ([] (hxc-machines
       com.aurellem.gb.gb-driver/original-rom))
  ([rom]
     (let [moves (hxc-move-names rom)]
       (zipmap
        (range)
        (take-while
            (comp not nil?)
            (map (comp
                  format-name
                  (zipmap
                   (range)
                   moves)
              dec)
                 (take 100
                       (drop 0x1232D rom))))))))

7 NPC Trainers

7.1 Trainer Pokémon

There are two formats for specifying lists of NPC PPokémon:

  • If all the Pokémon will have the same level, the format is
    • Level (used for all the Pokémon)
    • Any number of Pokémon internal ids.
    • 0x00, to indicate end-of-list.
  • Otherwise, all the Pokémon will have their level specified. The format is
    • 0xFF, to indicate that we will be specifying the levels individually3.
    • Any number of alternating Level/Pokemon pairs
    • 0x00, to indicate end-of-list.

Get the pointers

See the data

(ns com.aurellem.gb.hxc
  (:use (com.aurellem.gb assembly characters gb-driver util mem-util
                         constants))
  (:import [com.aurellem.gb.gb_driver SaveState]))

(->>
 (rom)
 (drop 0x39E2F)
 (take 21)
 (println))


(->>
 (rom)
 (drop 0x39E2F)
 (take 21)
 (partition-by zero?)
 (take-nth 2)
 (println))



(let
    [pokenames
     (zipmap
      (rest (range))
      (hxc-pokenames-raw))]

  (->>
   (rom)
   (drop 0x39E2F)
   (take 21)   ;; (1922 in all)
   (partition-by zero?)
   (take-nth 2)
   (map
    (fn parse-team [[mode & team]]
      (if (not= 0xFF mode)
        (mapv
         #(hash-map :level mode :species (pokenames %))
         team)
        
        (mapv
         (fn [[lvl id]] (hash-map :level lvl :species (pokenames id)))
         (partition 2 team)))))

   (println)))



(11 165 108 0 14 5 0 10 165 165 107 0 14 165 108 107 0 15 165 5 0)
((11 165 108) (14 5) (10 165 165 107) (14 165 108 107) (15 165 5))
([{: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}])

8 Places

8.1 Names of places

(def hxc-places
  "The hardcoded place names in memory. List begins at
ROM@71500. [Cinnabar/Celadon] Mansion seems to be dynamically calculated."
  (hxc-thunk-words 0x71500 560))

See it work

(println (hxc-places))
(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)

8.2 Wild Pokémon demographics

;; 0x0489, relative to 0xCB95, points to 0xCD89.
(defn hxc-ptrs-wild
  "A list of the hardcoded wild encounter data in memory. Pointers
  begin at ROM@0CB95; data begins at ROM@0x0CD89" 
  ([] (hxc-ptrs-wild com.aurellem.gb.gb-driver/original-rom))
  ([rom]
     (let [ptrs
           (map (fn [[a b]] (+ a (* 0x100 b)))
            (take-while (partial not= (list 0xFF 0xFF))
                            (partition 2 (drop 0xCB95 rom))))]
       ptrs)))



(defn hxc-wilds
  "A list of the hardcoded wild encounter data in memory. Pointers
  begin at ROM@0CB95; data begins at ROM@0x0CD89" 
  ([] (hxc-wilds com.aurellem.gb.gb-driver/original-rom))
  ([rom]
     (let [pokenames (zipmap (range) (hxc-pokenames rom))]
       (map
        (partial map 
                 (fn [[a b]]
                   {:species (pokenames (dec b))
                    :level a}))
        (partition 10  
                   (take-while
                    (comp (partial not= 1) first) 
                    (partition 2
                               (drop 0xCD8C rom))
                   
                   ))))))

8.3 Map data

(ns com.aurellem.gb.hxc
  (:use (com.aurellem.gb assembly characters gb-driver util mem-util
                         constants))
  (:import [com.aurellem.gb.gb_driver SaveState]))


(defn parse-header-tileset
  [[bank#     ;; memory bank for blocks & tileset 
    
    blocks-lo ;; structure
    blocks-hi
    
    tileset-lo ;; style
    tileset-hi
    
      collision-lo ;; collision info
    collision-hi
    
    talk-here-1 ;; positions of up to three
    talk-here-2 ;; talk-over-countertop tiles
    talk-here-3 ;; --- 0xFF if unused.
    
    grass ;; grass tile --- 0xFF if unused
    
    animation-flags ;; settings for animation
    & _]]
  
  [bank#
   
   blocks-lo ;; structure
   blocks-hi
   
   tileset-lo ;; style
   tileset-hi
   
   collision-lo ;; collision info
   collision-hi
   
   talk-here-1 ;; positions of up to three
   talk-here-2 ;; talk-over-countertop tiles
   talk-here-3 ;; --- 0xFF if unused.
   
   grass ;; grass tile --- 0xFF if unused
   
   animation-flags ;; settings for animation
   ])



(defn parse-header-map
  [start]

  (let [connection-size 11

        [tileset-index
         map-height
         map-width
         layout-lo
         layout-hi
         text-lo
         text-hi
         script-lo
         script-hi
         adjacency-flags ;; x x x x N S W E
         & etc]
        (drop start (rom))

        [east? west? south? north?]
        (bit-list adjacency-flags)

        [connections object-data]
        (split-at
         (* connection-size (+ east? west? south? north?))
         etc)

        connections
        (partition connection-size connections)
        



        ]
    (ptr->offset
     3
     (low-high layout-lo layout-hi))
    

    ))

9 Appendices

9.1 Mapping the ROM

ROM address (hex)DescriptionFormatExample
01823-0184AImportant prefix strings.Variable-length strings, separated by 0x50.TM#TRAINER#PC#ROCKET#POKé#…
0233C-Shop inventories.
02F47-(?) Move ids of some HM moves.One byte per move id0x0F 0x13 0x39 0x46 0x94 0xFF, the move ids of CUT, FLY, SURF, STRENGTH, FLASH, then cancel.
03E59-Start of the Give-Pokémon script.Assembly. When called, converts the contents of register BC into a Pokémon: (B) is the level; (C) is the species.
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.
04495-Prices of items.Each price is two bytes of binary-coded decimal. Prices are separated by zeroes. Priceless items4 are given a price of zero.The cost of lemonade is 0x03 0x50, which translates to a price of ₱350.
04524-04527(unconfirmed) possibly the bike price in Cerulean.
045B7-0491ENames 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#…
05DD2-05DF2Menu text for player info.PLAYER [newline] BADGES [nelwine] POKÉDEX [newline] TIME [0x50]
05EDB.Which Pokémon to show during Prof. Oak's introduction.A single byte, the Pokémon's internal id.In Pokémon Yellow, it shows Pikachu during the introduction; Pikachu's internal id is 0x54.
06698-? Background music.
7550-7570Menu options for map directions5.Variable-length strings.NORTH [newline] WEST [0x50] SOUTH [newline] EAST [0x50] NORTH [newline] EAST[0x50]
7570-757DMenu options for trading PokémonTRADE [newline] CANCEL [0x50]
757D-758AMenu options for healing PokémonHEAL [newline] CANCEL [0x50]
7635-Menu options for selected Pokémon (Includes names of out-of-battle moves).Variable-length strings separated by 0x50.CUT [0x50] FLY [0x50] SURF [0x50] STRENGTH [0x50] FLASH [0x50] DIG [0x50] TELEPORT [0x50] SOFTBOILED [0x50] STATS [newline] SWITCH [newline] CANCEL [0x50]
7AF0-8000(empty space)0 0 0 0 0 …
0822E-082F?Pointers to background music, part I.
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 relative to this memory bank, i.e. absolute address 0xCD89, the location of the first list of wild Pokémon. (For details on pointer addresses, see the relevant appendix.)
0CD89-Lists of wild Pokémon to encounter in each region.Lists of 12 bytes. First, an encounter rate6. Next, ten alternating Pokémon/level pairs. Each list ends with 0x00. If the encounter rate is zero, the list ends immediately.The first nonempty list (located at ROM@0CD8B) is (25; 3 36 4 36 2 165 3 165 2 36 3 36 5 36 4 165 6 36 7 36; 0), i.e. 25 encounter rate; level 3 pidgey, level 4 pidgey, level 2 rattata, level 3 rattata, level 2 pidgey, level 3 pidgey, level 5 pidgey, level 4 rattata, level 6 pidgey, level 7 pidgey, 0 (i.e., end-of-list).
0DACB.Amount of HP restored by Soda PopThe HP consists of a single numerical byte.60
0DACF.Amount of HP restored by Lemonade"80
0DAD5.Amount of HP restored by Fresh Water"50
0DADB.Amount of HP restored by Hyper Potion."200
0DAE0.Amount of HP restored by Super Potion."50
0DAE3.Amount of HP restored by Potion."20
0DD4D-DD72Names of permanent stats.Variable-length strings separated by 0x50.#HEALTH#ATTACK#DEFENSE#SPEED#SPECIAL#
0DE2F.Duration of Repel.A single byte, representing the number of steps you can take before the effect wears off.100
0DF39.Duration of Super Repel."200
0DF3E.Duration of Max Repel."250
1164B-Terminology for the Pokémon menu.Contiguous, variable-length strings.TYPE1[newline]TYPE2[newline] ,[newline]OT,[newline][0x50]STATUS,[0x50]OK
116DE-Terminology for permanent stats in the Pokémon menu.Contiguous, variable-length strings.ATTACK[newline]DEFENSE[newline]SPEED[newline]SPECIAL[0x50]
11852-Terminology for current stats in the Pokémon menu.Contiguous, variable-length strings.EXP POINTS[newline]LEVEL UP[0x50]
1195C-1196AThe two terms for being able/unable to learn a TM/HM.Variable-length strings separated by 0x50.ABLE#NOT ABLE#
119C0-119CEThe two terms for being able/unable to evolve using the current stone.Variable-length strings separated by 0x50.ABLE#NOT ABLE#
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].
11D67.Which badge is a prerequisite for SURF?"0x67 (test for Soul Badge)
11DAC.Which badge is a prerequisite for STRENGTH?"0x5F (test for Rainbow Badge)
1232D-12364Which moves are taught by the TMs and HMsA 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), …
1CF8B-1CF8CWhich Pokémon does Melanie give you in Cerulean City?A level/internal-id pair.(10 153), corresponding to a level 10 Bulbasaur.
1D651-1D652Which Pokémon do you find at the top of Celadon Mansion?A level/internal-id pair.(25 102), corresponding to a level 25 Eevee.
27D56 & 27D57.Pointer to the pointers to type names.A single low-byte, high-byte pair.0x63 0x7D, corresponding to location 27D63— the start of the next entry.
27D63-27D99Pointers 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").
27D99-27DFFNames of the Pokémon types.Variable-length type names (strings of character codes). Names are separated by a single 0x50 character.NORMAL#FIGHTING#…
27DFF-27E77?120 bytes of unknown data.
27E77-Trainer title names.Variable-length names separated by 0x50.YOUNGSTER#BUG CATCHER#LASS#…
34000-
38000-383DEThe basic properties and effects of moves. (165 moves total)Fixed-length (6 byte) continguous descriptions (no separating character): move-index, move-effect, power, move-type, accuracy, pp.The entry for Pound, the first attack in the list, is (1 0 40 0 255 35). See below for more explanation.
383DE-Species data for the Pokemon, listed in Pokedex order: Pokedex number; base moves; types; learnable TMs and HMs; base HP, attack, defense, speed, special; sprite data.
39462-The Pokémon cry data.Fixed-length (3 byte) descriptions of cries.
3997D-39B05Trainer titles (extended; see 27E77). This list includes strictly more trainers, seemingly at random inserted into the list from 27E77.7
39B05-39DD0.unknown
39DD1-39E2EPointers to trainer PokémonPairs of low-high bits.The first pair is 0x2F 0x5E, which corresponds to memory location 5E2F relative to this 38000-3C000 bank, i.e.8 position 39E2F overall.
39E2F-3A5B2Trainer PokémonSpecially-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. 9.)
3B1E5-3B361Pointers to evolution/learnset data.One high-low byte pair for each of the 190 Pokémon in internal order.
3B361-3BBAAEvolution and learnset data. 10Variable-length evolution information (see below), followed by a list of level/move-id learnset pairs.
3BBAA-3C000(empty)0 0 0 0 …
3D131-3D133The 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éball 11.
3D6C7-3D6D6Two miscellaneous strings.Variable length, separated by 0x50Disabled!#TYPE
3E190-3E194Which 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.
3E200-3E204" (???)""
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.
3E5FA-3E6F0.Type effectivenessTriples of bytes: atk-type, def-type, multiplier. The multiplier is stored as 10x its actual value to allow for fractions; so, 20 means 2.0x effective, 5 means 0.5x effective. Unlisted type combinations have 1.0x effectiveness by default.The first few entries are (21 20 20) (20 22 20) (20 25 20) (22 21 20) (23 21 20), corresponding to [:water :fire 2.0] [:fire :grass 2.0] [:fire :ice 2.0]
40252-4027BPokédex menu textVariable-length strings separated by 0x50.SEEN#OWN#CONTENTS#…
40370-40386Important constants for Pokédex entriesHT _ _ ?′??″ [newline] WT _ _ _ ??? lb [0x50] POKÉ [0x50]
40687-41072Species data from the Pokédex: species name, height, weight, etc.Variable-length species names, followed by 0x50, followed by fixed-length height/weight/etc. data.The first entry is (146 132 132 131, 80, 2 4, 150 0, 23, 0 64 46, 80), which are the the stats of Bulbasaur: the first entry spells "SEED", then 0x80, then the height (2' 4"), then the weight (formatted as a low-high byte pair), then various Pokédex pointer data (see elsewhere).
41072-Poké placeholder species, "???"
410B1-4116FA conversion table between internal order and Pokedex order.190 bytes, corresponding to the Pokédex numbers of the 190 Pokémon listed in internal order. All MISSINGNO. are assigned a Pokédex number of 0.The first few entries are (112 115 32 35 21 100 34 80 2 …), which are the Pokédex numbers of Rhydon, Kangaskhan, Nidoran(m), Clefairy, Spearow, Voltorb, Nidoking, Slobrow, and Ivysaur.
509B4-509E0Saffron City's adjacency info.Four adjacency lists, each 11 bytes long. (For more info on adjacency lists a.k.a. connection data, see here)The first adjacency list is (0x10 0x70 0x46 0xF0 0xC6 0x0A 0x0A 0x23 0xF6 0x09 0xC8)
515AE-515AFWhich Pokémon does the trainer near Route 25 give you?A level/internal-id pair.(10 176) corresponding to a level 10 Charmander.
51DD5-51DD6Which Pokémon does the Silph Co. trainer give you?A level/internal-id pair.(15 19) corresponding to a level 15 Lapras.
527BA-527DBThe costs and kinds of prizes from Celadon Game Corner.The following pattern repeats three times, once per window12: 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
5DE10-5DE30Abbreviations for status ailments.Fixed-length strings, probably13. The last entry is QUIT##.[0x7F] SLP [0x4E][0x7F] PSN [0x4E][0x7F] PAR [0x50][0x7F]…
70295-Hall of fameThe text "HALL OF FAME"
70442-Play time/moneyThe text "PLAY TIME [0x50] MONEY"
71500-7174BNames of places.Variable-length place names (strings), separated by 0x50.PALLET TOWN#VIRIDIAN CITY#PEWTER CITY#CERULEAN CITY#…
71C1E-71CAA (approx.)Tradeable NPC Poké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".
7C249-7C2??Pointers to background music, pt II.
98000-B7190Dialogue and other messsages.Variable-length strings.
B7190-B8000(empty space)0 0 0 0 0 …
B8000-BC000The text of each Pokémon's Pokédex entry.Variable-length descriptions (strings) in Poké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]."
BC000-BC60FMove names.Variable-length move names, separated by 0x50. The moves are in internal order.POUND#KARATE CHOP#DOUBLESLAP#COMET PUNCH#…
BC610-BD000(empty space)0 0 0 0 0 …
E8000-E876CNames of the “190” species of Pokémon in memory.Fixed length (10-letter) Pokémon names. Any extra space is padded with the character 0x50. The names are in “internal order”.RHYDON####KANGASKHANNIDORAN♂#…
E9BD5-The text PLAY TIME (see above, 70442)
F1A44-F1A45Which Pokémon does Officer Jenny give you?A level/internal-id pair.(10 177), corresponding to a level 10 Squirtle.
F21BF-F21C0Which Pokémon does the salesman at the Mt. Moon Pokémon center give you?A level/internal-id pair(5 133), corresponding to a level 5 Magikarp.

9.2 Understanding memory banks and pointers

(defn endian-flip
  "Flip the bytes of the two-byte number."
  [n]
  (assert (< n 0xFFFF))
  (+ (* 0x100 (rem n 0x100))
        (int (/ n 0x100))))


(defn offset->ptr
  "Convert an offset into a little-endian pointer."
  [n]
  (->
   n
   (rem 0x10000) ;; take last four bytes
   (rem 0x4000)   ;; get relative offset from the start of the bank
   (+ 0x4000)
   endian-flip))

(defn offset->bank
  "Get the bank of the offset."
  [n]
  (int (/ n 0x4000)))

(defn ptr->offset
  "Convert a two-byte little-endian pointer into an offset."
  [bank ptr]
  (->
   ptr
   endian-flip
   (- 0x4000)
   (+ (* 0x4000 bank))
   ))

(defn same-bank-offset
  "Convert a ptr into an absolute offset by using the bank of the reference."
  [reference ptr]
  (ptr->offset
   (offset->bank reference)
   ptr))

9.3 Internal Pokémon IDs

9.4 Type IDs

(def pkmn-types
  [:normal    ;;0
   :fighting  ;;1
   :flying    ;;2
   :poison    ;;3
   :ground    ;;4
   :rock      ;;5
   :bird      ;;6
   :bug       ;;7
   :ghost     ;;8
   :A
   :B
   :C
   :D
   :E
   :F
   :G
   :H
   :I
   :J
   :K
   :fire     ;;20 (0x14)
   :water    ;;21 (0x15)
   :grass    ;;22 (0x16)
   :electric ;;23 (0x17)
   :psychic  ;;24 (0x18)
   :ice      ;;25 (0x19)
   :dragon   ;;26 (0x1A)
   ])

9.5 Basic effects of moves

Table of basic effects

The possible effects of moves in Pokémon — for example, dealing damage, leeching health, or potentially poisoning the opponent — are stored in a table. Each move has exactly one effect, and different moves might have the same effect.

For example, Leech Life, Mega Drain, and Absorb all have effect ID #3, which is “Leech half of the inflicted damage.”

All the legitimate move effects are listed in the table below. Here are some notes for reading it:

  • Whenever an effect has a chance of doing something (like a chance of poisoning the opponent), I list the chance as a hexadecimal amount out of 256; this is to avoid rounding errors. To convert the hex amount into a percentage, divide by 256.
  • For some effects, the description is too cumbersome to write. Instead, I just write a move name in parentheses, like: (leech seed). That move gives a characteristic example of the effect.
  • I use the abbreviations atk, def, spd, spc, acr, evd for attack, defense, speed, special, accuracy, and evasiveness.

.

ID (hex)DescriptionNotes
0normal damage
1no damage, just sleepTODO: find out how many turns
20x4C chance of poison
3leech half of inflicted damage
40x19 chance of burn
50x19 chance of freeze
60x19 chance of paralysis
7user faints; opponent's defense is halved during attack.
8leech half of inflicted damage ONLY if the opponent is asleep
9imitate last attack
Auser atk +1
Buser def +1
Cuser spd +1
Duser spc +1
Euser acr +1This effect is unused.
Fuser evd +1
10get post-battle money = 2 * level * uses
11move has 0xFE acr, regardless of battle stat modifications.
12opponent atk -1
13opponent def -1
14opponent spd -1
15opponent spc -1
16opponent acr -1
17opponent evd -1
18converts user's type to opponent's.
19(haze)
1A(bide)
1B(thrash)
1C(teleport)
1D(fury swipes)
1Eattacks 2-5 turnsUnused. TODO: find out what it does.
1F0x19 chance of flinching
20opponent sleep for 1-7 turns
210x66 chance of poison
220x4D chance of burn
230x4D chance of freeze
240x4D chance of paralysis
250x4D chance of flinching
26one-hit KO
27charge one turn, atk next.
28fixed damage, leaves 1HP.Is the fixed damage the power of the move?
29fixed damage.Like seismic toss, dragon rage, psywave.
2Aatk 2-5 turns; opponent can't attackThe odds of attacking for n turns are: (0 0x60 0x60 0x20 0x20)
2Bcharge one turn, atk next. (can't be hit when charging)
2Catk hits twice.
2Duser takes 1 damage if misses.
2Eevade status-lowering effectsCaused by you or also your opponent?
2Fbroken: if user is slower than opponent, makes critical hit impossible, otherwise has no effectThis is the effect of Focus Energy. It's (very) broken.
30atk causes recoil dmg = 1/4 dmg dealt
31confuses opponent
32user atk +2
33user def +2
34user spd +2
35user spc +2
36user acr +2This effect is unused.
37user evd +2This effect is unused.
38restores up to half of user's max hp.
39(transform)
3Aopponent atk -2
3Bopponent def -2
3Copponent spd -2
3Dopponent spc -2
3Eopponent acr -2
3Fopponent evd -2
40doubles user spc when attacked
41doubles user def when attacked
42just poisons opponent
43just paralyzes opponent
440x19 chance opponent atk -1
450x19 chance opponent def -1
460x19 chance opponent spd -1
470x4C chance opponent spc -1
480x19 chance opponent acr -1
490x19 chance opponent evd -1
4A???;; unused? no effect?
4B???;; unused? no effect?
4C0x19 chance of confusing the opponent
4Datk hits twice. 0x33 chance opponent poisioned.
4Ebroken. crash the game after attack.
4F(substitute)
50unless opponent faints, user must recharge after atk. some exceptions apply
51(rage)
52(mimic)
53(metronome)
54(leech seed)
55does nothing (splash)
56(disable)

Source

(def move-effects
  ["normal damage"
   "no damage, just opponent sleep" ;; how many turns? is atk power ignored?
   "0x4C chance of poison"
   "leech half of inflicted damage"
   "0x19 chance of burn"
   "0x19 chance of freeze"
   "0x19 chance of paralyze"
   "user faints; opponent defense halved during attack."
   "leech half of inflicted damage ONLY if sleeping opponent."
   "imitate last attack"
   "user atk +1"
   "user def +1"
   "user spd +1"
   "user spc +1"
   "user acr +1" ;; unused?!
   "user evd +1"
   "get post-battle $ = 2*level*uses"
   "0xFE acr, no matter what."
   "opponent atk -1"     ;; acr taken from move acr?
   "opponent def -1"     ;;
   "opponent spd -1"   ;;
   "opponent spc -1" ;;
   "opponent acr -1";;
   "opponent evd -1"
   "converts user's type to opponent's."
   "(haze)"
   "(bide)"
   "(thrash)"
   "(teleport)"
   "(fury swipes)"
   "attacks 2-5 turns" ;; unused? like rollout?
   "0x19 chance of flinch"
   "opponent sleep for 1-7 turns"
   "0x66 chance of poison"
   "0x4D chance of burn"
   "0x4D chance of freeze"
   "0x4D chance of paralyze"
   "0x4D chance of flinch"
   "one-hit KO"
   "charge one turn, atk next."
   "fixed damage, leaves 1HP." ;; how is dmg determined?
   "fixed damage."             ;; cf seismic toss, dragon rage, psywave.
   "atk 2-5 turns; opponent can't attack" ;; unnormalized? (0 0x60 0x60 0x20 0x20)
   "charge one turn, atk next. (can't be hit when charging)"
   "atk hits twice."
   "user takes 1 damage if misses."
   "evade status-lowering effects" ;;caused by you or also your opponent?
   "(broken) if user is slower than opponent, makes critical hit impossible, otherwise has no effect"
   "atk causes recoil dmg = 1/4 dmg dealt"
   "confuses opponent" ;; acr taken from move acr
   "user atk +2"
   "user def +2"
   "user spd +2"
   "user spc +2"
   "user acr +2" ;; unused!
   "user evd +2" ;; unused!
   "restores up to half of user's max hp." ;; broken: fails if the difference
   ;; b/w max and current hp is one less than a multiple of 256.
   "(transform)"
   "opponent atk -2"
   "opponent def -2"
   "opponent spd -2"
   "opponent spc -2"
   "opponent acr -2"
   "opponent evd -2"
   "doubles user spc when attacked"
   "doubles user def when attacked"
   "just poisons opponent"   ;;acr taken from move acr
   "just paralyzes opponent" ;;
   "0x19 chance opponent atk -1"
   "0x19 chance opponent def -1"
   "0x19 chance opponent spd -1"
   "0x4C chance opponent spc -1" ;; context suggest chance is 0x19
   "0x19 chance opponent acr -1"
   "0x19 chance opponent evd -1"
   "???" ;; unused? no effect?
   "???" ;; unused? no effect?
   "0x19 chance opponent confused"
   "atk hits twice. 0x33 chance opponent poisioned."
   "broken. crash the game after attack."
   "(substitute)"
   "unless opponent faints, user must recharge after atk. some
  exceptions apply."
   "(rage)"
   "(mimic)"
   "(metronome)"
   "(leech seed)"
   "does nothing (splash)"
   "(disable)"
   ])

9.6 Alphabet code

10 Source

(ns com.aurellem.gb.hxc
  (:use (com.aurellem.gb assembly characters gb-driver util mem-util
                         constants species))
  (:import [com.aurellem.gb.gb_driver SaveState]))

; ************* HANDWRITTEN CONSTANTS

(def pkmn-types
  [:normal    ;;0
   :fighting  ;;1
   :flying    ;;2
   :poison    ;;3
   :ground    ;;4
   :rock      ;;5
   :bird      ;;6
   :bug       ;;7
   :ghost     ;;8
   :A
   :B
   :C
   :D
   :E
   :F
   :G
   :H
   :I
   :J
   :K
   :fire     ;;20 (0x14)
   :water    ;;21 (0x15)
   :grass    ;;22 (0x16)
   :electric ;;23 (0x17)
   :psychic  ;;24 (0x18)
   :ice      ;;25 (0x19)
   :dragon   ;;26 (0x1A)
   ])


;; question: when status effects claim to take
;; their accuracy from the move accuracy, does
;; this mean that the move always "hits" but the
;; status effect may not?

(def move-effects
  ["normal damage"
   "no damage, just opponent sleep" ;; how many turns? is atk power ignored?
   "0x4C chance of poison"
   "leech half of inflicted damage"
   "0x19 chance of burn"
   "0x19 chance of freeze"
   "0x19 chance of paralyze"
   "user faints; opponent defense halved during attack."
   "leech half of inflicted damage ONLY if sleeping opponent."
   "imitate last attack"
   "user atk +1"
   "user def +1"
   "user spd +1"
   "user spc +1"
   "user acr +1" ;; unused?!
   "user evd +1"
   "get post-battle $ = 2*level*uses"
   "0xFE acr, no matter what."
   "opponent atk -1"     ;; acr taken from move acr?
   "opponent def -1"     ;;
   "opponent spd -1"   ;;
   "opponent spc -1" ;;
   "opponent acr -1";;
   "opponent evd -1"
   "converts user's type to opponent's."
   "(haze)"
   "(bide)"
   "(thrash)"
   "(teleport)"
   "(fury swipes)"
   "attacks 2-5 turns" ;; unused? like rollout?
   "0x19 chance of flinch"
   "opponent sleep for 1-7 turns"
   "0x66 chance of poison"
   "0x4D chance of burn"
   "0x4D chance of freeze"
   "0x4D chance of paralyze"
   "0x4D chance of flinch"
   "one-hit KO"
   "charge one turn, atk next."
   "fixed damage, leaves 1HP." ;; how is dmg determined?
   "fixed damage."             ;; cf seismic toss, dragon rage, psywave.
   "atk 2-5 turns; opponent can't attack" ;; unnormalized? (0 0x60 0x60 0x20 0x20)
   "charge one turn, atk next. (can't be hit when charging)"
   "atk hits twice."
   "user takes 1 damage if misses."
   "evade status-lowering effects" ;;caused by you or also your opponent?
   "(broken) if user is slower than opponent, makes critical hit impossible, otherwise has no effect"
   "atk causes recoil dmg = 1/4 dmg dealt"
   "confuses opponent" ;; acr taken from move acr
   "user atk +2"
   "user def +2"
   "user spd +2"
   "user spc +2"
   "user acr +2" ;; unused!
   "user evd +2" ;; unused!
   "restores up to half of user's max hp." ;; broken: fails if the difference
   ;; b/w max and current hp is one less than a multiple of 256.
   "(transform)"
   "opponent atk -2"
   "opponent def -2"
   "opponent spd -2"
   "opponent spc -2"
   "opponent acr -2"
   "opponent evd -2"
   "doubles user spc when attacked"
   "doubles user def when attacked"
   "just poisons opponent"   ;;acr taken from move acr
   "just paralyzes opponent" ;;
   "0x19 chance opponent atk -1"
   "0x19 chance opponent def -1"
   "0x19 chance opponent spd -1"
   "0x4C chance opponent spc -1" ;; context suggest chance is 0x19
   "0x19 chance opponent acr -1"
   "0x19 chance opponent evd -1"
   "???" ;; unused? no effect?
   "???" ;; unused? no effect?
   "0x19 chance opponent confused"
   "atk hits twice. 0x33 chance opponent poisioned."
   "broken. crash the game after attack."
   "(substitute)"
   "unless opponent faints, user must recharge after atk. some
  exceptions apply."
   "(rage)"
   "(mimic)"
   "(metronome)"
   "(leech seed)"
   "does nothing (splash)"
   "(disable)"
   ])

;; ************** HARDCODED DATA

(defn hxc-thunk
  "Creates a thunk (nullary fn) that grabs data in a certain region of rom and
splits it into a collection by 0x50. If rom is not supplied, uses the
  original rom data."
  [start length]
  (fn self
    ([rom]
       (take-nth 2
                 (partition-by #(= % 0x50)
                               (take length
                                     (drop start rom)))))
    ([]
      (self com.aurellem.gb.gb-driver/original-rom))))

(def hxc-thunk-words
  "Same as hxc-thunk, except it interprets the rom data as characters,
  returning a collection of strings."
  (comp
   (partial comp (partial map character-codes->str))
   hxc-thunk))

;; --------------------------------------------------


(defn hxc-pokenames-raw
  "The hardcoded names of the 190 species in memory. List begins at
ROM@E8000. Although names in memory are padded with 0x50 to be 10 characters
  long, these names are stripped of padding. See also, hxc-pokedex-names"
  ([]
     (hxc-pokenames-raw com.aurellem.gb.gb-driver/original-rom))
  ([rom]
     (let [count-species 190
           name-length 10]
       (map character-codes->str
            (partition name-length
                       (map #(if (= 0x50 %) 0x00 %)
                            (take (* count-species name-length)
                                  (drop 0xE8000
                                        rom))))))))
(def hxc-pokenames
  (comp
   (partial map format-name)
   hxc-pokenames-raw))




(defn hxc-pokedex-names
  "The names of the pokemon in hardcoded pokedex order. List of the
  pokedex numbers of each pokemon (in internal order) begins at
ROM@410B1. See also, hxc-pokenames."
  ([] (hxc-pokedex-names
       com.aurellem.gb.gb-driver/original-rom))
  ([rom]
     (let [names (hxc-pokenames rom)]
       (#(mapv %
               ((comp range count keys) %))
        (zipmap
         (take (count names)
               (drop 0x410b1 rom))
         
         names)))))

(def hxc-types
  "The hardcoded type names in memory. List begins at ROM@27D99,
  shortly before hxc-titles."
  (hxc-thunk-words 0x27D99 102))


;; http://hax.iimarck.us/topic/581/
(defn hxc-cry
  "The pokemon cry data in internal order. List begins at ROM@39462"
  ([](hxc-cry com.aurellem.gb.gb-driver/original-rom))
  ([rom]
     (zipmap
      (hxc-pokenames rom)
      (map
       (fn [[cry-id pitch length]]
         {:cry-id cry-id
         :pitch pitch
          :length length}
         )
       (partition 3
                  (drop 0x39462 rom))))))

(defn hxc-cry-groups
  ([] (hxc-cry-groups com.aurellem.gb.gb-driver/original-rom))
  ([rom]
     (map #(mapv first
                (filter
                 (fn [[k v]]
                   (= % (:cry-id v)))
                 (hxc-cry)))
          ((comp
            range
            count
            set
            (partial map :cry-id)
            vals
            hxc-cry)
           rom))))


(defn cry-conversion!
  "Convert Porygon's cry in ROM to be the cry of the given pokemon."
  [pkmn]
  (write-rom!
   (rewrite-memory
    (vec(rom))
    0x3965D 
    (map second
         ((hxc-cry) pkmn)))))




(def hxc-items-raw
  "The hardcoded names of the items in memory. List begins at
ROM@045B7"
  (hxc-thunk-words 0x45B7 870))

(def hxc-items
  "The hardcoded names of the items in memory, presented as
  keywords. List begins at ROM@045B7. See also, hxc-items-raw."
  (comp (partial map format-name) hxc-items-raw))



(def hxc-titles
  "The hardcoded names of the trainer titles in memory. List begins at
ROM@27E77"
  (hxc-thunk-words 0x27E77 196))


(def hxc-pokedex-text-raw
  "The hardcoded pokedex entries in memory. List begins at
ROM@B8000, shortly before move names."
  (hxc-thunk-words 0xB8000 14754))




(defn hxc-pokedex-text
  "The hardcoded pokedex entries in memory, presented as an
associative hash map. List begins at ROM@B8000."
  ([] (hxc-pokedex-text com.aurellem.gb.gb-driver/original-rom))
  ([rom]
     (zipmap
      (hxc-pokedex-names rom)
      (cons nil ;; for missingno.
            (hxc-pokedex-text-raw rom)))))

;; In red/blue, pokedex stats are in internal order.
;; In yellow, pokedex stats are in pokedex order.
(defn hxc-pokedex-stats
  "The hardcoded pokedex stats (species height weight) in memory. List
begins at ROM@40687"
  ([] (hxc-pokedex-stats com.aurellem.gb.gb-driver/original-rom))
  ([rom]
     (let [pokedex-names (zipmap (range) (hxc-pokedex-names rom))
           pkmn-count (count pokedex-names)
           ]
     ((fn capture-stats
        [n stats data]
        (if (zero? n) stats
            (let [[species
                   [_
                    height-ft
                    height-in
                    weight-1
                    weight-2
                    _
                    dex-ptr-1
                    dex-ptr-2
                    dex-bank
                    _
                    & data]]
                  (split-with (partial not= 0x50) data)]
              (recur (dec n)
                     (assoc stats
                       (pokedex-names (- pkmn-count (dec n)))
                       {:species
                        (format-name (character-codes->str species))
                        :height-ft
                        height-ft
                        :height-in
                        height-in
                        :weight
                        (/ (low-high weight-1 weight-2) 10.)
                        
                    ;;    :text
                    ;;    (character-codes->str
                    ;;     (take-while
                    ;;      (partial not= 0x50)
                    ;;      (drop
                    ;;       (+ 0xB8000
                    ;;          -0x4000
                    ;;          (low-high dex-ptr-1 dex-ptr-2))
                    ;;       rom)))
                        })
                     
                     data)
              
              
              )))
      
      pkmn-count
      {}
      (drop 0x40687 rom)))       ))




(def hxc-places
  "The hardcoded place names in memory. List begins at
ROM@71500. [Cinnabar/Celadon] Mansion seems to be dynamically calculated."
  (hxc-thunk-words 0x71500 560))

(defn hxc-dialog
  "The hardcoded dialogue in memory, including in-game alerts. Dialog
  seems to be separated by 0x57 instead of 0x50 (END). Begins at ROM@98000."
  ([rom]
     (map character-codes->str
          (take-nth 2
                    (partition-by #(= % 0x57)
                                  (take 0x0F728
                                        (drop 0x98000 rom))))))
  ([]
     (hxc-dialog com.aurellem.gb.gb-driver/original-rom)))


(def hxc-move-names
  "The hardcoded move names in memory. List begins at ROM@BC000"
  (hxc-thunk-words 0xBC000 1551))
(defn hxc-move-data
  "The hardcoded (basic (move effects)) in memory. List begins at
0x38000. Returns a map of {:name :power :accuracy :pp :fx-id
  :fx-txt}. The move descriptions are handwritten, not hardcoded."
  ([]
     (hxc-move-data com.aurellem.gb.gb-driver/original-rom))
  ([rom]
     (let [names (vec (hxc-move-names rom))
           move-count (count names)
           move-size 6
           types pkmn-types ;;; !! hardcoded types
           ]
       (zipmap (map format-name names)
               (map
                (fn [[idx effect power type-id accuracy pp]]
                  {:name (names (dec idx))
                   :power power
                   :accuracy  accuracy
                   :pp pp
                   :type (types type-id)
                   :fx-id effect
                   :fx-txt (get move-effects effect) 
                   }
                  )
                
                (partition move-size
                           (take (* move-size move-count)
                                 (drop 0x38000 rom))))))))
  


(defn hxc-move-data*
  "Like hxc-move-data, but reports numbers as hexadecimal symbols instead."
  ([]
     (hxc-move-data* com.aurellem.gb.gb-driver/original-rom))
  ([rom]
     (let [names (vec (hxc-move-names rom))
           move-count (count names)
           move-size 6
           format-name (fn [s]
                         (keyword (.toLowerCase
                                   (apply str
                                          (map #(if (= % \space) "-" %) s)))))
           ]
       (zipmap (map format-name names)
               (map
                (fn [[idx effect power type accuracy pp]]
                  {:name (names (dec idx))
                   :power power
                   :accuracy (hex accuracy)
                   :pp pp
                   :fx-id (hex effect)
                   :fx-txt (get move-effects effect) 
                   }
                  )
                
                (partition move-size
                           (take (* move-size move-count)
                                 (drop 0x38000 rom))))))))
  

(defn hxc-machines
  "The hardcoded moves taught by TMs and HMs. List begins at ROM@1232D."
  ([] (hxc-machines
       com.aurellem.gb.gb-driver/original-rom))
  ([rom]
     (let [moves (hxc-move-names rom)]
       (zipmap
        (range)
        (take-while
            (comp not nil?)
            (map (comp
                  format-name
                  (zipmap
                   (range)
                   moves)
              dec)
                 (take 100
                       (drop 0x1232D rom))))))))




(defn internal-id
  ([rom]
     (zipmap 
      (hxc-pokenames rom)
      (range)))
  ([]
     (internal-id com.aurellem.gb.gb-driver/original-rom)))





;; nidoran gender change upon levelup
;; (->
;;  @current-state
;;  rom
;;  vec
;;  (rewrite-memory
;;   (nth (hxc-ptrs-evolve) ((internal-id) :nidoran♂))
;;   [1 1 15])
;;  (rewrite-memory
;;   (nth (hxc-ptrs-evolve) ((internal-id) :nidoran♀))
;;   [1 1 3])
;;  (write-rom!)

;;  )



(defn hxc-advantage
  ;; in-game multipliers are stored as 10x their effective value
  ;; to allow for fractional multipliers like 1/2
  
  "The hardcoded type advantages in memory, returned as tuples of
  atk-type def-type multiplier. By default (i.e. if not listed here),
the multiplier is 1. List begins at 0x3E62D."
  ([] (hxc-advantage com.aurellem.gb.gb-driver/original-rom))
  ([rom]
     (map
      (fn [[atk def mult]] [(get pkmn-types atk (hex atk))
                            (get pkmn-types def (hex def))
                            (/ mult 10)])
      (partition 3
                 (take-while (partial not= 0xFF)
                             (drop 0x3E5FA rom))))))



(defn format-evo
  "Parse a sequence of evolution data, returning a map. First is the
method: 0 = end-evolution-data. 1 = level-up, 2 = item, 3 = trade. Next is an item id, if the
  method of evolution is by item (only stones will actually make pokemon
  evolve, for some auxillary reason.) Finally, the minimum level for
  evolution to occur (level 1 means no limit, which is used for trade
  and item evolutions), followed by the internal id of the pokemon
  into which to evolve. Hence, level up and trade evolutions are
  described with 3
  bytes; item evolutions with four."
  [coll]
  (let [method (first coll)]
    (cond (empty? coll) []
          (= 0 method) [] ;; just in case
          (= 1 method) ;; level-up evolution
          (conj (format-evo (drop 3 coll))
                            {:method :level-up
                             :min-level (nth coll 1)
                             :into (dec (nth coll 2))})
          
          (= 2 method) ;; item evolution
          (conj (format-evo (drop 4 coll))
                {:method :item
                 :item (dec (nth coll 1))
                 :min-level (nth coll 2)
                 :into (dec (nth coll 3))})

          (= 3 method) ;; trade evolution
          (conj (format-evo (drop 3 coll))
                {:method :trade
                 :min-level (nth coll 1) ;; always 1 for trade.
                 :into (dec (nth coll 2))}))))


(defn hxc-ptrs-evolve
  "A hardcoded collection of 190 pointers to alternating evolution/learnset data,
in internal order."
  ([]
     (hxc-ptrs-evolve com.aurellem.gb.gb-driver/original-rom))
  ([rom]
     (let [
           pkmn-count (count (hxc-pokenames-raw)) ;; 190
           ptrs
           (map (fn [[a b]] (low-high a b))
                (partition 2
                           (take (* 2 pkmn-count)
                                 (drop 0x3b1e5 rom))))]
       (map (partial + 0x34000) ptrs)

       )))

(defn hxc-evolution
  "Hardcoded evolution data in memory. The data exists at ROM@34000,
  sorted by internal order. Pointers to the data exist at ROM@3B1E5; see also, hxc-ptrs-evolve."
  ([] (hxc-evolution com.aurellem.gb.gb-driver/original-rom))
  ([rom]
       (apply assoc {}
               (interleave
                (hxc-pokenames rom)
                (map
                 (comp
                  format-evo
                  (partial take-while (comp not zero?))
                  #(drop % rom))
                 (hxc-ptrs-evolve rom)
                 )))))

(defn hxc-evolution-pretty
  "Like hxc-evolution, except it uses the names of items and pokemon
--- grabbed from ROM --- rather than their numerical identifiers."
  ([] (hxc-evolution-pretty com.aurellem.gb.gb-driver/original-rom))
  ([rom]
     (let
         [poke-names (vec (hxc-pokenames rom))
          item-names (vec (hxc-items rom))
          use-names
          (fn [m]
            (loop [ks (keys m) new-map m]
              (let [k (first ks)]
                (cond (nil? ks) new-map
                      (= k :into)
                      (recur
                       (next ks)
                       (assoc new-map
                         :into
                         (poke-names
                          (:into
                           new-map))))
                      (= k :item)
                      (recur
                       (next ks)
                       (assoc new-map
                         :item
                         (item-names
                          (:item new-map))))
                      :else
                      (recur
                       (next ks)
                       new-map)
                      ))))]

       (into {}
             (map (fn [[pkmn evo-coll]]
                    [pkmn (map use-names evo-coll)])
                  (hxc-evolution rom))))))




(defn hxc-learnsets
  "Hardcoded map associating pokemon names to lists of pairs [lvl
  move] of abilities they learn as they level up. The data
exists at ROM@34000, sorted by internal order. Pointers to the data
  exist at ROM@3B1E5; see also, hxc-ptrs-evolve"
  ([] (hxc-learnsets com.aurellem.gb.gb-driver/original-rom))
  ([rom]
     (apply assoc
            {}
            (interleave
             (hxc-pokenames rom)
             (map (comp
                   (partial map
                            (fn [[lvl mv]] [lvl (dec mv)]))
                   (partial partition 2)
                   ;; keep the learnset data
                   (partial take-while (comp not zero?))
                   ;; skip the evolution data
                   rest
                   (partial drop-while (comp not zero?)))
                  (map #(drop % rom) 
                       (hxc-ptrs-evolve rom)))))))

(defn hxc-learnsets-pretty
  "Live hxc-learnsets except it reports the name of each move --- as
it appears in rom --- rather than the move index."
  ([] (hxc-learnsets-pretty com.aurellem.gb.gb-driver/original-rom))
  ([rom]
     (let [moves (vec(map format-name (hxc-move-names)))]
       (into {}
             (map (fn [[pkmn learnset]]
                    [pkmn (map (fn [[lvl mv]] [lvl (moves mv)])
                               learnset)])
                  (hxc-learnsets rom))))))
             
                                  

(defn hxc-pokemon-base
  ([] (hxc-pokemon-base com.aurellem.gb.gb-driver/original-rom))
  ([rom]
     (let [entry-size 28
          
           pokemon (rest (hxc-pokedex-names))
 pkmn-count (inc(count pokemon))
           types (apply assoc {}
                        (interleave
                         (range)
                         pkmn-types)) ;;!! softcoded
           moves (apply assoc {}
                        (interleave
                         (range)
                         (map format-name
                              (hxc-move-names rom))))
           machines (hxc-machines)
           ]
       (zipmap
        pokemon
        (map
         (fn [[n
               rating-hp
               rating-atk
               rating-def
               rating-speed
               rating-special
               type-1
               type-2
               rarity ;; catch rate
               rating-xp ;; base exp yield
               pic-dimensions ;; tile_width|tile_height (8px/tile)
               ptr-pic-obverse-1
               ptr-pic-obverse-2
               ptr-pic-reverse-1
               ptr-pic-reverse-2
               move-1 ;; attacks known at level 0 [i.e. by default]
               move-2 ;; (0 for none)
               move-3
               move-4
               growth-rate
               &
               TMs|HMs]]
           (let
               [base-moves
                (mapv moves
                      ((comp
                        ;; since the game uses zero as a delimiter,
                        ;; it must also increment all move indices by 1.
                        ;; heren we decrement to correct this.
                        (partial map dec)
                        (partial take-while (comp not zero?)))
                       [move-1 move-2 move-3 move-4]))
                
                types
                (set (list (types type-1)
                           (types type-2)))
                TMs|HMs
                (map
                 (comp
                  (partial map first)
                  (partial remove (comp zero? second)))
                 (split-at
                  50
                  (map vector
                       (rest(range))
                       (reduce concat
                               (map
                                #(take 8
                                       (concat (bit-list %)
                                               (repeat 0)))
                                
                                TMs|HMs)))))
                
                TMs  (vec (first TMs|HMs))
                HMs (take 5 (map (partial + -50) (vec (second TMs|HMs))))
                
                
                ]
             
             
             {:dex# n
              :base-moves base-moves
              :types types
              :TMs TMs
              :HMs HMs
              :base-hp rating-hp
              :base-atk rating-atk
              :base-def rating-def
              :base-speed rating-speed
              :base-special rating-special
              :o0 pic-dimensions
              :o1 ptr-pic-obverse-1
              :o2 ptr-pic-obverse-2
              }))
         
         (partition entry-size
                    (take (* entry-size pkmn-count)
                          (drop 0x383DE
                                rom))))))))

  
  
(defn hxc-intro-pkmn
  "The hardcoded pokemon to display in Prof. Oak's introduction; the pokemon's
internal id is stored at ROM@5EDB."
  ([] (hxc-intro-pkmn
       com.aurellem.gb.gb-driver/original-rom))
  ([rom]
     (nth (hxc-pokenames rom) (nth rom 0x5EDB))))

(defn sxc-intro-pkmn!
  "Set the hardcoded pokemon to display in Prof. Oak's introduction."
  [pokemon]
  (write-rom! 
   (rewrite-rom 0x5EDB
                [
                 (inc
                  ((zipmap
                    (hxc-pokenames)
                    (range))
                   pokemon))])))
  

(defn hxc-item-prices
  "The hardcoded list of item prices in memory. List begins at ROM@4495"
  ([] (hxc-item-prices com.aurellem.gb.gb-driver/original-rom))
  ([rom]
     (let [items (hxc-items rom)
           price-size 3]
       (zipmap items
               (map (comp
                     ;; zero-cost items are "priceless"
                     #(if (zero? %) :priceless %)
                     decode-bcd butlast)
                    (partition price-size
                               (take (* price-size (count items))
                                     (drop 0x4495 rom))))))))

(defn hxc-shops
  ([] (hxc-shops com.aurellem.gb.gb-driver/original-rom))
  ([rom]
     (let [items (zipmap (range) (hxc-items rom))

           ;; temporarily softcode the TM items
           items (into
                  items
                  (map (juxt identity
                             (comp keyword
                                   (partial str "tm-")
                                   (partial + 1 -200)
                                   )) 
                       (take 200 (drop 200 (range)))))
                       
           ]

       ((fn parse-shop [coll [num-items & items-etc]]
          (let [inventory (take-while
                           (partial not= 0xFF)
                           items-etc)
               [separator & items-etc] (drop num-items (rest items-etc))]
           (if (= separator 0x50)
             (map (partial mapv (comp items dec)) (conj coll inventory))
             (recur (conj coll inventory) items-etc)
             )
         ))

        '()
        (drop 0x233C rom))

     
     )))


;; 0x0489, relative to 0xCB95, points to 0xCD89.
(defn hxc-ptrs-wild
  "A list of the hardcoded wild encounter data in memory. Pointers
  begin at ROM@0CB95; data begins at ROM@0x0CD89" 
  ([] (hxc-ptrs-wild com.aurellem.gb.gb-driver/original-rom))
  ([rom]
     (let [ptrs
           (map (fn [[a b]] (+ a (* 0x100 b)))
            (take-while (partial not= (list 0xFF 0xFF))
                            (partition 2 (drop 0xCB95 rom))))]
       ptrs)))



(defn hxc-wilds
  "A list of the hardcoded wild encounter data in memory. Pointers
  begin at ROM@0CB95; data begins at ROM@0x0CD89" 
  ([] (hxc-wilds com.aurellem.gb.gb-driver/original-rom))
  ([rom]
     (let [pokenames (zipmap (range) (hxc-pokenames rom))]
       (map
        (partial map 
                 (fn [[a b]]
                   {:species (pokenames (dec b))
                    :level a}))
        (partition 10  
                   (take-while
                    (comp (partial not= 1) first) 
                    (partition 2
                               (drop 0xCD8C rom))
                   
                   ))))))



;; ********************** MANIPULATION FNS


(defn same-type
  ([pkmn move]
     (same-type
      com.aurellem.gb.gb-driver/original-rom pkmn move))
  ([rom pkmn move]
     (((comp :types (hxc-pokemon-base rom)) pkmn)
      ((comp :type (hxc-move-data rom)) move))))




(defn submap?
  "Compares the two maps. Returns true if map-big has the same associations as map-small, otherwise false." 
  [map-small map-big]
  (cond (empty? map-small) true
        (and
         (contains? map-big (ffirst map-small))
         (= (get map-big (ffirst map-small))
            (second (first map-small))))
        (recur (next map-small) map-big)

        :else false))  


(defn search-map [proto-map maps]
  "Returns all the maps that make the same associations as proto-map."
  (some (partial submap? proto-map) maps))

(defn filter-vals
  "Returns a map consisting of all the pairs [key val] for
  which (pred key) returns true."
  [pred map]
  (reduce (partial apply assoc) {}
          (filter (fn [[k v]] (pred v)) map)))


(defn search-moves
  "Returns a subcollection of all hardcoded moves with the
  given attributes. Attributes consist of :name :power
  :accuracy :pp :fx-id
  (and also :fx-txt, but it contains the same information
  as :fx-id)"
  ([attribute-map]
     (search-moves
      com.aurellem.gb.gb-driver/original-rom attribute-map))
  ([rom attribute-map]
     (filter-vals (partial submap? attribute-map)
                  (hxc-move-data rom))))





;; note: 0x2f31 contains the names "TM" "HM"?

;; note for later: credits start at F1290

;; note: DADB hyper-potion-hp _ _ _ super-potion-hp _ _ _ potion-hp ??

;; note: DD4D spells out pokemon vital stat names ("speed", etc.)

;; note: 1195C-6A says ABLE#NOT ABLE#, but so does 119C0-119CE.
;; The first instance is for Machines; the second, for stones.

;; note: according to
;; http://www.upokecenter.com/games/rby/guides/rgbtrainers.php
;; the amount of money given by a trainer is equal to the 
;; base money times the level of the last Pokemon on that trainer's
;; list. Other sources say it's the the level of the last pokemon 
;; /defeated/.

;; todo: find base money.


;; note: 0xDFEA (in indexable mem) is the dex# of the currently-viewed Pokemon in
   ;; in the pokedex. It's used for other purposes if there is none.

;; note: 0x9D35 (index.) switches from 0xFF to 0x00 temporarily when
;;   you walk between areas. 

;; note: 0xD059 (index.) is the special battle type of your next battle:
;; - 00 is a usual battle
;; - 01 is a pre-scripted OLD MAN battle which always fails to catch the
;;      target Pokemon.
;; - 02 is a safari zone battle
;; - 03  obligates you to run away. (unused) 
;; - 04 is a pre-scripted OAK battle, which (temporarily) causes the
;;      enemy Pokemon to cry PIKAAA, and which always catches the target
;;      Pokemon. The target Pokemon is erased after the battle.
;; - 05+ are glitch states in which you are sort of the Pokemon.


;; note: 0x251A (in indexable mem): image decompression routine seems to begin here.

;; note: 0x4845 (index): vending inventory is loaded here. possibly
   ;; other things, too.
(comment
  ;; temporarily intercept/adjust what pops out of the vending
  ;; machine.
  ;; (and how much it costs)

  ;; located at 0x4845
  ;; not to be confused with shop inventory, 0xCF7B
  (do 
    (step (read-state "vend-menu"))
    (write-memory! (rewrite-memory (vec(memory)) 0x4845 [2 0 1 0]))
    (step @current-state [:a])
    (step @current-state [])
    (nstep @current-state 200) ))


;; Note: There are two tile tables, one from 8000-8FFF, the other from
;; 8800-97FF. The latter contains symbols, possibly map tiles(?), with some japanese chars and stuff at the end. 
(defn print-pixel-letters!
  "The pixel tiles representing letters. Neat!"
 ([] (print-pixel-letters! (read-state "oak-speaks"))) 
([state] 
   (map
    (comp
     println
     (partial map #(if (zero? %) \space 0))
     #(if (< (count %) 8)
        (recur (cons 0 %))
        %)
     reverse bit-list)
    
    (take 0xFFF (drop 0x8800 (memory state))))))


;; (defn test-2 []
;;   (loop [n 0
;;          pc-1 (pc-trail (-> state-defend (tick) (step [:a]) (step [:a]) (step []) (nstep 100)) 100000)
;;          pc-2 (pc-trail (-> state-speed (tick) (step [:a]) (step [:a])
;;   (step []) (nstep 100)) 100000)]
;;     (cond (empty? (drop n pc-1)) [pc-1 n]
;;           (not= (take 10 (drop n pc-1)) (take 10 pc-2))
;;           (recur  pc-1 pc-2 (inc n))
;;           :else
;;           [(take 1000 pc-2) n])))




(defn test-3 
  "Explore trainer data"
  ([] (test-3 0x3A289))
  ([start]
  (let [pokenames (vec(hxc-pokenames-raw))]
    (println 
     (reduce
      str
      (map
       (fn [[adr lvl pkmn]]
         (str (format "%-11s %4d       %02X %02X \t %05X\n"
                      
                      (cond
                        (zero? lvl) "+"
                        (nil? (get pokenames (dec pkmn)))
                        "-"
                        :else
                        (get pokenames (dec pkmn)))
                      lvl
                      pkmn
                      lvl
                      adr
                      )))
       (map cons
            (take-nth 2 (drop start (range)))
            (partition 2
                       (take 400;;703
                             (drop
                              start
                              ;; 0x3A75D
                              (rom)))))))))))
  
(defn search-memory* [mem codes k]
  (loop [index 0
         index-next 1
         start-match 0
         to-match codes
         matches []]
    (cond
      (>= index (count mem)) matches

      (empty? to-match)
      (recur
       index-next
       (inc index-next)
       index-next
       codes
       (conj matches
             [(hex start-match) (take k (drop start-match mem))])
       )

      (or (= (first to-match) \_) ;; wildcard
          (= (first to-match) (nth mem index)))
      (recur
       (inc index)
       index-next
       start-match
       (rest to-match)
       matches)

      :else
      (recur
       index-next
       (inc index-next)
       index-next
       codes
       matches))))


(def script-use-ball
  [0xFA ;; ld A, nn
   \_
   \_
   0xA7 ;; and A
   0xCA ;; JP Z
   \_
   \_
   0x3D ;; dec A
   0xC2 ;; JP NZ
   \_
   \_
   0xFA ;; LD A
   \_
   \_
   ])



(defn search-pattern [ptn coll]
  (loop
      [index 0
       to-match ptn
       binds {}

       next-index 1
       match-start 0
       matches []]

    (cond
        (>= index (count coll)) matches
        (empty? to-match)
        (recur
         next-index
         ptn
         {}
         (inc next-index)
         next-index
         (conj match-start
               [(hex match-start) binds]))

        :else
        (let [k (first to-match)
              v (nth coll index)]
        (cond
          (= k \_) ;; wildcard
          (recur
           (inc index)
           (rest to-match)
           binds

           next-index
           match-start
           matches)

          (keyword? k)
          (if (binds k)
            (if (= (binds k) v)
              (recur
               (inc index)
               (rest to-match)
               binds
               next-index
               match-start
               matches)

              (recur
               next-index
               ptn
               {}
               (inc next-index)
               next-index
               matches))
              
              ;; ;; consistent bindings
              ;; (recur
              ;;  (inc index)
              ;;  (rest to-match)
              ;;  binds

              ;;  next-index
              ;;  match-start
              ;;  matches)

              ;; ;; inconsistent bindings
              ;; (recur
              ;;  next-index
              ;;  ptn
              ;;  {}
              ;;  (inc next-index)
              ;;  next-index
              ;;  matches))
              
            (if ((set (vals binds)) v)
              ;; bindings are not unique
              (recur
               next-index
               ptn
               {}
               (inc next-index)
               next-index
               matches)

              ;; bindings are unique
              (recur
               (inc index)
               (rest to-match)
               (assoc binds k v)

               next-index
               match-start
               matches)))

          :else ;; k is just a number
          (if (= k v)
            (recur
             (inc index)
             (rest to-match)
             binds

             next-index
             match-start
             matches)

            (recur
             next-index
             ptn
             {}
             (inc next-index)
             next-index
             matches)))))))

            
            

              




(defn search-pattern* [ptn coll]
  (loop
      [
       binds {}
       index 0
       index-next 1
       start-match 0
       to-match ptn
       matches []]

    (cond
        (>= index (count coll)) matches
        (empty? to-match)
        (recur
         {}
         index-next
         (inc index-next)
         index-next
         ptn
         (conj matches
               [(hex start-match) binds]))

        :else
        (let [k (first to-match)
              v (nth coll index)]
        (cond
          (= k \_) ;; wildcard
          (recur
           binds
           (inc index)
           index-next
           start-match
           (rest to-match)
           matches)

          (keyword? k)
          (if (binds k)
            (if (= (binds k) v)
              (recur
               binds
               (inc index)
               index-next
               start-match
               (rest to-match)
               matches)
              (recur
               {}
               index-next
               (inc index-next)
               index-next
               ptn
               matches))
            (if
                ;; every symbol must be bound to a different thing.
              ((set (vals binds)) v)
              (recur
               {}
               index-next
               (inc index-next)
               index-next
               ptn
               matches)
              (recur
               (assoc binds k v)
               (inc index)
               index-next
               start-match
               (rest to-match)
               matches)))

          :else
          (if (= k v)
            (recur
             binds
             (inc index)
             index-next
             start-match
             (rest to-match)
             matches)
            (recur
             {}
             index-next
             (inc index-next)
             index-next
             ptn
             matches))



)))))
             



;; look for the rainbow badge in memory
(println (reduce str (map #(str (first %) "\t" (vec(second %)) "\n") (search-memory (rom) [221] 10))))


(comment 

(def hxc-later
  "Running this code produces, e.g. hardcoded names NPCs give
their pokemon. Will sort through it later."
(print (character-codes->str(take 10000
                          (drop 0x71597
                                (rom (root)))))))

(let [dex
      (partition-by #(= 0x50 %)
                    (take 2540
                          (drop 0x40687
                                (rom (root)))))]
  (def dex dex)
  (def hxc-species
    (map character-codes->str
         (take-nth 4 dex))))
)


Footnotes:

1 This Clojure interface will be published to aurellem.org soon.

2 190 allocated spaces minus 151 true Pokémon

3 Because 0xFF is a forbidden level within the usual gameplay discipline, the game makers could safely use 0xFF as a mode indicator.

4 Like the Pokédex and other unsellable items.

5 According to The Cutting Room Floor, this data is unused.

6 I suspect this is an amount out of 256.

7 The names added are in bold: YOUNGSTER, BUG CATCHER, LASS, SAILOR, JR TRAINER(m), JR TRAINER(f), POKé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.

8 For details about how relative bank pointers work, see the relevant Appendix.

9 Incidentally, if you want to change your rival's starter Pokémon, it's enough just to change its species in all of your battles with him.

10 Evolution data consists of how to make Pokémon evolve, and what they evolve into. Learnset data consists of the moves that Pokémon learn as they level up.

11 If you give them any ball, OAK will catch the enemy Poké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.

12 For the first two prize lists, ids are interpreted as Pokémon ids. For the last prize list, ids are (somehow) interpreted as item ids.

13 Here's something strange: all of the status messages start with 0x7F and end with 0x4F —except PAR, which ends with 0x50.

Date: 2013-06-09 20:53:29 BST

Author: Dylan Holmes

Org version 7.7 with Emacs version 23

Validate XHTML 1.0