Guest User

Untitled

a guest
Feb 3rd, 2016
382
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. Random numbers in Dragon Warrior III
  2. ====================================
  3.  
  4.  
  5. How the random number generator is seeded
  6. -----------------------------------------
  7.  
  8. The random number generator is seeded from the save file checksum
  9. whenever a save file is saved (or checked, on reset -- note that while
  10. the files are checked in slot order, DW3 swaps the positions of save
  11. files to put the current file in the first slot, so the seed on reset is
  12. not necessarily from file #3). See the bottom of this file for details
  13. of how this works and how it can be abused to break the RNG. On reset
  14. with a fresh cart (backup RAM not initialized) or in which the file in
  15. the third slot is save file #3 and is empty, the initial seed when the
  16. main menu opens is $3D27.
  17.  
  18.  
  19. Random numbers in character creation
  20. ------------------------------------
  21.  
  22. When creating characters in a new file:
  23. - If the character is not the hero, choose the name by taking the low 2
  24. bits of a random number as an index into a table of 4 predefined names
  25. (each character has a different list of 4 possible names).
  26. - Take the predefined base values for the character's class and add the
  27. low bit of a random number to each (in the order Luck, Intelligence,
  28. Vitality, Agility, Strength).
  29. - The file is then checksummed (after other non-random initialization
  30. like inventory setup), resetting the RNG seed.
  31.  
  32. When creating a character at Luisa's Place 2F:
  33. - Store the predefined base stats for the selected character class.
  34. - Take a multi-random number in the range 0 through 4 (as in battles;
  35. see below) and add 2; this is the number of stats to increment.
  36. - For that number of times, take a multi-random number in the range 0
  37. through 4 and increment the stat selected by that index (in the order
  38. Strength, Agility, Vitality, Intelligence, Luck).
  39. - The file is checksummed after other character setup is complete.
  40.  
  41.  
  42. Random numbers on the field
  43. ---------------------------
  44.  
  45. - When entering a new map, a random number is taken and discarded.
  46.  
  47. - When an NPC is about to move, a random number is taken and the low 2
  48. bits are used to select the direction the NPC moves in. (NPCs move
  49. based on the global frame timer: NPCs 0 and 1 move on frames $00 and
  50. $80, NPCs 2 and 3 move on frames $10 and $90, etc. Movement is
  51. suppressed if the NPC is offscreen or in a different map room.)
  52.  
  53. - Numbness healing while moving: For each numb character, take a random
  54. number at each step; numbness heals if the low 4 bits of the random
  55. number are zero.
  56.  
  57. - While on the non-Alefgard overworld and neither the current tile nor
  58. the last 3 tiles are map entrances, every 64 frames (when the low 6
  59. bits of the $90 frame counter are zero):
  60. - Take a random number. If the low 3 bits are zero, take another
  61. random number.
  62. - Take another random number.
  63.  
  64. - On the overworld, on each step (before checking for encounters), add
  65. ((seed & 31) + 223) / 256 to the time-of-day timer. The timer is an
  66. 8.8 fixed-point value with a period of 204; "night" is any value 120
  67. or greater. Note that this does not take a new random number from the
  68. RNG, but just uses the current seed value.
  69.  
  70. - If in a zone (overworld) or map (town/dungeon) with enemies,
  71. encounters are checked for on each step (see $8222 in bank 0):
  72. - If in a low encounter rate area (16/256, 64/256, 128/256), take a
  73. random number and skip the encounter check if the number is greater
  74. than or equal to the /256 chance.
  75. - Multiply the encounter rate (1 for low encounter rate areas) by:
  76. - On the overworld:
  77. - Water: 4 during the day, 5 at night
  78. - Grass tiles: 10 during the day, 13 at night
  79. - Woods, desert, ice tiles: 15 during the day, 19 at night
  80. - Heavy forest, swamp tiles: 18 during the day, 22 at night
  81. - Hills: 25 during the day, 31 at night
  82. - Other tiles: encounter not possible, abort
  83. - In dungeons: 84 after a room transition, 10 elsewhere
  84. But set the encounter rate to 100 if any party member has the
  85. Golden Claw (equipped or not), or if the product is greater than
  86. 100. Then take a random number, and an encounter occurs if the
  87. random number is less than the encounter rate.
  88. - If an encounter occurs, use a random number to choose one of the 14
  89. encounters in the group (encounters are weighted based on tables,
  90. see 0/$90F3). If on the overworld, and:
  91. - during daytime, the chosen encounter is 4, 10, or 13; or
  92. - during nighttime, the chosen encounter is 0 or 6,
  93. or if the chosen encounter is $FF, repeat up to 98 more times, then
  94. abort the encounter.
  95. - Choose enemy groups:
  96. - If the encounter is index $00 through $04, then:
  97. - Add a group of 1 of the base enemy to the encounter.
  98. - For up to 19 tries, choose a random number from 0 through 5
  99. (using $C3F1, which repeatedly takes random numbers and masks
  100. off high bits [$F8, in this case] until the masked value is
  101. in range). If the number is not the same as the encounter
  102. index, the number is valid for the current day/night state
  103. (if on the overworld), the enemy ID of that encounter is not
  104. $FF, and that enemy has not been seen yet:
  105. - Add a group of that enemy (count 1) and mark it as seen.
  106. - Compare a random number against the chance of adding
  107. another group (this chance is part of the encounter data);
  108. if greater or equal, stop adding enemies.
  109. - Advance the additional-group-chance index, and if it
  110. reaches 2, stop adding enemies.
  111. - Choose a random number from 0 through 2. If it is zero,
  112. stop. Otherwise, choose another random number from 0 through
  113. the highest defined enemy group index (or 4, if both
  114. additional-group chances were consumed); if that group is not
  115. the encounter $05 enemy, add 1 to the group count. Then
  116. repeat this step.
  117. - If the encounter is index $05, add a group of 1 of the base
  118. enemy to the encounter; then choose a random number from 0
  119. through 4, and add 8 of that enemy to the encounter. If on the
  120. overworld and the selected encounter is invalid for the current
  121. day/night state, or if the selected encounter ID is $FF, repeat
  122. 18 more times, then skip adding a second group.
  123. - If the encounter is index $06 through $0A, choose a random
  124. number of enemies from the random range selected for the
  125. encounter and set that as the solitary enemy group's count.
  126. Note that if the random range is a power of 2 (e.g. 4-7), $C3F1
  127. masks off one bit too few, so the random number range check will
  128. fail half the time.
  129. - If the encounter is index $0B, there is no randomness (one fixed
  130. enemy in the encounter).
  131. - If the encounter is index $0C or $0D, then for each of 4 enemy
  132. groups, choose a random count from the random range defined for
  133. the group. This is performed even if the random range is 1
  134. (constant count) and even if the group does not exist in the
  135. encounter (enemy ID is $FF).
  136.  
  137.  
  138. Random numbers in battle (and damage calculations, etc.)
  139. ------------------------
  140.  
  141. Aside from the regular RNG function ($C3B8, below just "random number"),
  142. the battle system uses several non-straightforward methods to get random
  143. numbers. I refer to them with the following terms (see the noted
  144. routine addresses in bank 4 for implementations).
  145.  
  146. - "multi-random number" ($ACBE): a random number taken after discarding
  147. a count of numbers from the stream equal to the value of $6A68 plus 1;
  148. see also the note below about "why battle outcomes can differ even
  149. with the same RNG seed".
  150.  
  151. - "multi-random number in a range" ($ACA3): a multi-random number
  152. multiplied by a range and divided by 256. For a range R, this gives
  153. values (approximately) evenly distributed from 0 through R-1 without
  154. needing to repeatedly take random numbers as with $C3F1.
  155.  
  156. - "random-16 number" ($BA5C): a random number computed by summing the
  157. low 5 bits of 16 consecutive random seeds (each taken after discarding
  158. a random number from the stream) and subtracting 120, then repeating
  159. until the result is in the range [0,255]. This gives a result
  160. weighted toward 128, similar to how rolling two fair six-sided dice
  161. will result in a sum of 7 more often than 2 or 12.
  162.  
  163. - "random-32 number" ($BA64): like random-16, but computed by summing
  164. the low 4 bits of 32 consecutive random seeds and subtracting 112.
  165.  
  166. The last two methods have a theoretical risk of infinite-looping if the
  167. RNG gets stuck in a hole, since the counter ($00A4) which is normally
  168. added to the RNG seed when returning a random number is ignored.
  169. Fortunately, the two holes in the actual function used by the RNG land
  170. within the [0,255] range, so they're safe; seed $5FEA gives results of
  171. 40 for random-16 and 208 for random-32, while $AFF5 gives results of 216
  172. for random-16 and 48 for random-32.
  173.  
  174. Battles proceed as follows (omitting some non-random logic for brevity):
  175.  
  176. - At startup:
  177. - For each Shadow is in the party:
  178. - Take a random-16 number.
  179. - Let N be that number times the lead party member's level,
  180. divided by 100, plus one; if N is greater than 130, set it to
  181. 130.
  182. - Take a multi-random number in the range 0 through N-1, and set
  183. the effective enemy ID to that value.
  184. - Set HP for each enemy by subtracting a multi-random number in the
  185. range [0,(floor(base_HP/4)+1)%256) from the enemy's base HP. (The
  186. mod-256 is relevant only for Zoma, whose base HP is 1023 so HP/4+1
  187. overflows to zero.)
  188. - Choose a random party member as the focus target for each enemy
  189. group (regardless of whether the enemy's data has the focus-attacks
  190. flag set).
  191. - If the battle is not a non-interactive or preset battle:
  192. - If the preemptive/back type (copied to $49 from table at $8ADB
  193. in bank 0) is 1 and a random number is less than 32, the
  194. encounter is a back attack (1 free turn for enemies).
  195. - Otherwise, if the preemptive/back type is not 3 and a random
  196. number is less than 8, the encounter is a back attack.
  197. - Otherwise, if the preemptive/back type is 2 and a random number
  198. is less than 32, the encounter is a preemptive attack (1 free
  199. turn for the party).
  200. - Otherwise, if the preemptive/back type is not 3 and a random
  201. number is less than 8, the encounter is a preemptive attack.
  202.  
  203. - At the beginning of each turn, for each of the 12 battle character
  204. slots (4 party member slots followed by 8 enemy slots), take a
  205. multi-random number in the range [agility/4,agility) to determine
  206. action order for that turn; higher values go sooner, and later slots
  207. win ties over earlier slots. All slots are processed, even if the
  208. slot is empty or the associated character or enemy is dead.
  209.  
  210. - If not a non-interactive battle, then for each party member:
  211. - If the party is ironized, attempting to run, or in a back attack,
  212. skip.
  213. - If the character is asleep, dead, or numb, skip.
  214. - If the character is in BeDragon status, take a random number. If
  215. the number is 0, the character attacks the first enemy group; if
  216. not, the character chooses action 4 if the low bit of the number is
  217. 0, otherwise action 5. (Both of these actions are the breath
  218. attack; it may be that BeDragoned characters were originally
  219. intended to have two actions, but that was changed to just the
  220. breath attack during development.)
  221. - Otherwise, show the character's battle command menu and let the
  222. player enter a command.
  223. - If the player chooses Run on the first character's menu:
  224. - If the battle is a preset encounter, the attempt fails.
  225. - Otherwise, if in the first turn of a preemptive attack or if the
  226. lead party member's level is at least 10 levels higher than the
  227. highest enemy level in the encounter, the attempt succeeds.
  228. - Otherwise, take a random number; the attempt fails if the number
  229. is less than the chance selected by the number of previous
  230. failed run attempts (128, 128, 64, 0 -- so the fourth run
  231. attempt always succeeds).
  232.  
  233. - If an interactive battle, then unless Run was chosen, take a random
  234. number and store the low 4 bits in $6A68 (the multi-random discard
  235. counter).
  236.  
  237. - Choose actions for each enemy:
  238. - If the enemy is dead, do nothing.
  239. - If the AI type (see notes below about enemy data) is 2, do nothing
  240. (actions will be chosen when the enemy actually takes its turn).
  241. - Choose an action and target:
  242. - Choose an action:
  243. - If the action chance selector is 3 (preset action order),
  244. choose the next action in sequence.
  245. - Otherwise, take a multi-random number, and choose an action
  246. based on that number and the chance table for the action
  247. chance selector.
  248. - Choose a target for the action: (note that in non-interactive
  249. battles, party targets are still selected here but will be
  250. changed by the confusion handler at turn resolution)
  251. - If the AI type is 0:
  252. - If the action targets a party member or is "assess the
  253. situation", parry, flee, or "call for help (same enemy)",
  254. choose a random target from all living party members.
  255. - If the action is Vivify or Revive, choose a random target
  256. from all dead enemies.
  257. - Otherwise, choose an appropriate enemy target (logic
  258. omitted for brevity).
  259. - Otherwise:
  260. - If the action is a spell, then:
  261. - If the enemy does not have enough MP for the spell:
  262. - If the AI type is 2, choose no target (try another
  263. command).
  264. - Otherwise, if the enemy has already used the action
  265. in the current battle, choose no target.
  266. - Otherwise, mark the action as having been used and
  267. continue.
  268. - If the enemy is in StopSpell status and the AI type is
  269. 2, choose no target.
  270. - Choose a target based on the action:
  271. - If "assessing the situation", parrying, or using a
  272. damage breath attack, choose a dummy target to cause
  273. the command to be accepted.
  274. - If attacking:
  275. - If the enemy focuses attacks on a single character:
  276. - If the character is alive, choose that target.
  277. - Otherwise, if at least one other party member is
  278. alive, choose a random living party member.
  279. - Otherwise, choose the existing target.
  280. - Otherwise, for each living party member, take a
  281. multi-random number; if it is less than or equal to
  282. the cumulative probability at that party slot, that
  283. character is chosen as the target. (This is the
  284. only case in which party order makes a difference,
  285. aside from a very slightly greater probability to
  286. choose the last party member due to off-by-one and
  287. rounding errors in unweighted random selection.)
  288. - If fleeing, choose a dummy target if the enemy's level
  289. plus 5 is less than the lead party member's level;
  290. otherwise, choose no target. (Thus, enemies who have
  291. the Flee action will not use it unless their level is
  292. at least 6 lower than the lead party member's level.)
  293. - If casting a damage spell:
  294. - If the AI type is 2, choose a random living party
  295. member who is not in Bounce status.
  296. - Otherwise, choose a random living party member.
  297. - If casting Increase:
  298. - If the AI type is 1-3, choose a random enemy target
  299. whose defense is at least 768. (This appears to be
  300. a bug in the code; the branch targets after the
  301. defense check should probably have been switched.
  302. As a result, "smart AI" enemies will never use
  303. Increase unless a Metal Slime or Metal Babble is in
  304. the encounter.)
  305. - Otherwise (AI type 0), choose a random enemy target.
  306. - (Logic for other actions omitted for brevity.)
  307. - If no target could be chosen, retry the action choice, but for
  308. chance selectors other than 3, exclude the previously chosen
  309. action from the set of possible actions and spread its chance
  310. evenly among the chances for all remaining actions in the action
  311. list (rounding down, so that the last action gets all of the
  312. remainder).
  313. - If no target could be chosen for any action, set the action to
  314. a normal attack.
  315. - If the action count selector is 3, choose a second action:
  316. - If the action chance selector is 3, choose the next action in
  317. sequence, just like the first action.
  318. - Otherwise, take a multi-random number and choose an action as for
  319. the first one.
  320. - Choose a target for the action as for the first action.
  321. - If the action count selector is 1, take a random number, and if the
  322. low bit is 1, choose a second action.
  323. - If the action count selector is 2, take a random number. If the
  324. low 2 bits are 0, do nothing (only one action). Otherwise choose a
  325. second action, and if the low 2 bits of the random number were 1 or
  326. 2, choose a third action in the same manner as the second.
  327.  
  328. - Resolve the turn. For each character (party or enemy) in turn order:
  329. - If a party member:
  330. - Skip the turn if the party is ironized or fleeing.
  331. - Skip the turn if the character is not present or dead.
  332. - If numb, print a numbness message and skip the turn.
  333. - If asleep, take a multi-random number and compare against the
  334. chance of waking for the number of sleep turns remaining (255,
  335. 128, 85, 32). If less than or equal to that chance, wake up
  336. the character; in any case, print an appropriate message and
  337. skip the turn.
  338. - If the character has the Noh Mask equipped or has Confused
  339. status, select a random action for confusion (logic omitted here
  340. for brevity).
  341. - If the character is a Goof-off, take a random number; if less
  342. than 65, select a random Goof-off action (logic omitted here for
  343. brevity).
  344. - Resolve the character's action.
  345. - If an enemy:
  346. - If in the first turn of a preemptive attack, skip the turn.
  347. - If the party attempted and failed to run, take a multi-random
  348. number; if at least 192 (1/4 chance), skip the turn.
  349. - If no action was chosen, skip the turn.
  350. - If the Chance time-stop effect is active, skip the turn.
  351. - If the enemy's AI type is 2:
  352. - If the action count selector is 1 or 2, take a multi-random
  353. number in the range [0,2], replace it with 2 if it is 0, and
  354. use that as the number of actions.
  355. - For each action, choose an action as described above, then
  356. evaluate the action as described below; treat the enemy's AI
  357. type as 1 for this purpose.
  358. - Otherwise (the enemy's AI type is not 2), evaluate the action:
  359. - If asleep, take a multi-random number and compare against the
  360. chance of waking for the number of sleep turns remaining
  361. (255, 192, 128, 64). If less than or equal to that chance,
  362. wake up the enemy; in any case, print an appropriate message
  363. and skip the action.
  364. - If the enemy is confused or the battle is non-interactive,
  365. choose a new target (and possibly change the action):
  366. - If the action is any of:
  367. - 0 (assess the situation)
  368. - 1 (parry)
  369. - 4-6 (attack + status effect)
  370. - 7 (flee)
  371. - 8, 59-63 (call for help)
  372. - 16-18 (status effect breath)
  373. - 40 (Chaos)
  374. - 43 (freezing wave)
  375. - 44 (Bounce)
  376. - 47 (Vivify)
  377. - 48 (Revive)
  378. then change it to 2 (normal attack) and continue with the
  379. next step.
  380. - If the action is a single-target action (2, 3, 9, 19-22,
  381. 31, 33, 36, 39, 42, 49, 50, 51, 54, 55, 56):
  382. - If the action targets the party:
  383. - If there is at least one enemy group other than the
  384. attacker's group living enemies, randomly choose one
  385. such group, then randomly choose the target from
  386. that enemy group.
  387. - Otherwise, if there are living enemies other than
  388. the attacker, choose a random enemy from the
  389. attacker's group.
  390. - Otherwise, leave the original target alone.
  391. - Otherwise, if the battle is an interactive battle,
  392. choose a random living party member as the target.
  393. - Otherwise (the battle is a non-interactive battle),
  394. choose the attacker as the target.
  395. - Otherwise (the action is a multi-target action):
  396. - If the action targets the party:
  397. - If there is at least one enemy group other than the
  398. attacker's group living enemies, randomly choose one
  399. such group as the target.
  400. - Otherwise, if there are living enemies other than
  401. the attacker, choose the attacker's group as the
  402. target.
  403. - Otherwise, leave the original target alone.
  404. - Otherwise, if the battle is an interactive battle,
  405. select the party member with the same index as the
  406. index of the originally targeted enemy group.
  407. - Otherwise (the battle is a non-interactive battle),
  408. select the attacker's group as the target.
  409. - Resolve the action.
  410. - If the enemy is not asleep and has a second action:
  411. - Evaluate the second action.
  412. - If the enemy has a third action, evaluate the third
  413. action.
  414.  
  415. - At the end of each turn:
  416. - For each enemy with a nonzero HP regeneration selector, add a
  417. multi-random number in the associated range to the enemy's HP,
  418. capping at the enemy type's base HP (not the initial HP selected
  419. when battle started).
  420.  
  421. - At the end of battle:
  422. - Multiply base experience by 1/3, rounding any fraction up, and add
  423. that amount to the base experience to get the total experience
  424. earned from the battle. Note that the code truncates the addend to
  425. the low 16 bits, so (in theory) if you killed 5 or more Metal
  426. Babbles in one battle, you would lose out on 65536 experience.
  427. - Divide the total experience by the number of living party members,
  428. rounding any fraction up, and add it to each living party member.
  429. - If the enemy can drop an item, then:
  430. - If the drop rate index is 0, the item is always dropped.
  431. - Otherwise, if the drop rate index is not 0, calculate the drop
  432. rate as 1 << (6 - index). The item is dropped if a random
  433. number is less than the drop rate.
  434. - Otherwise, take a random number. If it is 0, then the item is
  435. dropped if a second random number is less than 32.
  436. - Multiply base gold by 1/5, rounding any fraction up, and add that
  437. value to the base gold to get the total gold for the battle.
  438. - Add the total gold to the party's gold.
  439. - If the low 2 bits of a random number are 0 and a living merchant is
  440. in the party, add 1/8 of the total gold + 1 to the party's gold.
  441. (Note that the random number check is performed whether or not a
  442. merchant is in the party.)
  443. - Check each party member for leveling up. If a level up occurs:
  444. - Check the current value of each stat (in the order Strength,
  445. Agility, Vitality, Luck, Intelligence, maximum HP, maximum MP)
  446. against the upper limit for the character's class and current
  447. level. If the current value is greater than (or equal to, for
  448. maximum HP and MP) the limit, take the low bit of a random
  449. number as the level-up bonus. Otherwise:
  450. - For base stats, take a random-16 number, multiply it by the
  451. base increment for the class and current level, and divide by
  452. 110; if the result is zero, take the low bit of a random
  453. number instead.
  454. - For maximum HP and MP, take the bonus applied to Vitality or
  455. Intelligence respectively (but zero if the "low bit of a
  456. random number" method was used). If that value is zero, the
  457. HP or MP bonus is also zero; otherwise, double the value, add
  458. a multi-random number in the range [-2,+2], and use the
  459. result as the bonus.
  460. - For each spell learnable by the character's class:
  461. - Check whether the spell is learned this level (this check is
  462. done whether or not the spell is already known):
  463. - If the spell's learn chance type (*) is 1 and the
  464. character's new level is at least the spell's level, take
  465. a random number and learn the spell if bit 3 ($08) of the
  466. number is set.
  467. - If the spell's learn chance type is 0 and the character's
  468. new level is in the range [L,L+2] (where L is the spell
  469. level), compare the character's new Intelligence against
  470. the Intelligence target for the character's old level and
  471. obtain the learn chance:
  472. - If current < target - 15, the chance is $00 at level L,
  473. $80 at level L+1, and $FF at level L+2.
  474. - Else if current < target + 10, the chance is $80 at
  475. level L and $FF at level L+1 and L+2.
  476. - Else the chance is $FF at all levels.
  477. If the chance is not zero, take a random number; if the
  478. number is less than or equal to the chance, the spell is
  479. learned.
  480. - If the spell is learned this level, iterate over the class's
  481. spell list; if the character's spell bits corresponding to
  482. the spell ID are 0, set them to 1 and display the "learned a
  483. new spell" message. (If any bit is 1, the check stops
  484. immediately, which is why the Luisa registration bug -- a
  485. 1-byte overrun on a new character's inventory which overwrites
  486. the hero's first spell byte when the 12th stored character is
  487. created -- prevents the hero from learning Heal on the field
  488. spell list.)
  489. - Note that the Goof-off's possible random actions are handled
  490. as a set of 36 "spells", each of which is learned with chance
  491. type 1 and a base level equal to the ability index. The
  492. "learned a new spell" message is suppressed for Goof-offs.
  493.  
  494. (*) Each spell has, in addition to its base learning level, a bit
  495. indicating which of two algorithms is used to check whether the
  496. spell has been learned. The following spells are type 1:
  497. Firebal (7), Infermost (36), Beat (22), Sacrifice (41),
  498. Limbo (20), RobMagic (15), SpeedUP (5), Awake (16), Surround (7),
  499. Chaos (27), Transform (37), BeDragon (34), Sap (8), Upper (4),
  500. Increase (9), Bounce (24), Bikill (21), Chance (40)
  501. All others are type 0.
  502.  
  503. Other general notes:
  504.  
  505. - When the battle system needs to choose a random target, it takes a
  506. multi-random number and divides that by (255 / number of possible
  507. targets). If the result is out of range, the last possible target is
  508. chosen.
  509.  
  510. - The standard formula for computing base damage for a physical attack
  511. is as follows:
  512. - Compute the attacker's attack power minus half of the target's
  513. defense power.
  514. - If at least 2, multiply by a random-32 number bounded to [102,153]
  515. and divided by 4, then divide by 64 to get the base damage value.
  516. (This results in an average damage of attack/2 - defense/4, varying
  517. by up to 20% on either side of the average.)
  518. - Otherwise, use the low bit of a multi-random number as the base
  519. damage value.
  520.  
  521. - When a party member attacks an enemy group:
  522. - If the attacker has the Armor of Hades equipped, take a random
  523. number and abort the attack ("Can't move because of a curse!") if
  524. the number is at least 170 (slightly more than 1/3 chance).
  525. - If the attacker has the Sword of Destruction equipped, take a
  526. random number and abort the attack if the number is at least 192
  527. (1/4 chance).
  528. - If the attacker has the Zombie Slasher equipped, perform a
  529. resistance check against holy damage for the targeted enemy.
  530. (There is not an explicit list of zombie enemies in the code;
  531. instead, the Zombie Slasher deals extra damage to any enemy if the
  532. enemy fails a resistance check against the damage.)
  533. - For each non-dead enemy in the selected enemy group:
  534. - Compute the base damage using the standard formula. Then take a
  535. multi-random number in the range 0 through 255 minus the
  536. attacker's intelligence, divide by 4, multiply that by the base
  537. damage, and add the high byte of the product to the base damage
  538. to get the final damage.
  539. - If any enemies took damage greater than their current HP, choose
  540. the enemy with the greatest remaining HP as the target (the enemy
  541. with a greater index wins ties). Otherwise, choose the enemy which
  542. would have the greatest remaining floor(HP/4) after the attack as
  543. the target (again, the greater index wins ties).
  544. - If the attacker is in Surround status, take a multi-random number;
  545. the attack misses if the number is less than 160.
  546. - If the attacker has the Demon Axe equipped, take a multi-random
  547. number; the attack misses if the number is less than 32.
  548. - If the attacker is in Bikill status, double the damage value.
  549. - If the attacker does not have the Poison Needle equipped:
  550. - Check for evasion:
  551. - If on the first turn of a preemptive attack, if the target is
  552. asleep, or if the target's evade rate is zero, the attack
  553. always hits.
  554. - Otherwise, take a multi-random number; the attack misses if
  555. the number is less than the evade rate.
  556. - Check for a critical hit:
  557. - If the attacker is a Fighter, take a multi-random number and
  558. make the attack a critical hit if the number is less than the
  559. attacker's level.
  560. - Otherwise, if the attacker has the Sword of Destruction or
  561. the Demon Axe equipped, the critical rate is 32, otherwise 4.
  562. Take a multi-random number and make the attack a critical hit
  563. if the number is less than the critical rate.
  564. - If the attack is a critical hit, recompute the damage by taking a
  565. multi-random number in the range [54,64], multiplying that value by
  566. the attacker's attack power, dividing by 64, and adding 1.
  567. - If the weapon does bonus damage to the enemy (Zombie Slasher or
  568. Dragon Killer against relevant enemies), take a multi-random number
  569. and add that number plus 16 to the damage.
  570. - If the weapon is the Poison Needle, take a multi-random number; if
  571. less than 32 and the encounter is not a preset encounter, the enemy
  572. is killed, otherwise damage is set to 1. (Note that this implies
  573. the Poison Needle can never do 0 damage -- it will always either
  574. hit for 1 damage or kill the enemy.)
  575. - If the enemy is parrying, halve the damage value and add 1.
  576. - Apply the damage (reduce the target's HP).
  577. - If the Multi-Edge Sword is equipped, apply 1/4 damage + 1 to the
  578. attacker.
  579.  
  580. - When an enemy attacks a party member:
  581. - Compute the base damage using the standard formula, except that if
  582. the value of (attack power - half of defense power) satisfies all
  583. of the following conditions:
  584. - less than 256,
  585. - no greater than 1/8 of the attacker's attack power, and
  586. - greater than 2,
  587. then instead compute base damage as a multi-random number in the
  588. range 0 through (attack power - half of defense power - 1).
  589. - If the target has the Cloak of Evasion equipped, take a random
  590. number; if the number is at least 204 (~20% chance), the attack
  591. misses.
  592. - Take a multi-random number; if less than 4, the attack misses.
  593. - If the attacker is in Surround status, take a multi-random number;
  594. the attack misses if the number is less than 160.
  595. - If the target has the Shield of Sorrow equipped (and does not have
  596. the Cloak of Evasion or Swordedge Armor equipped), reduce the
  597. damage by half.
  598. - If the attacker is in Bikill status, double the damage value.
  599. - Apply the damage (reduce the target's HP).
  600. - If the party member dies, numb and poison statuses are cleared
  601. (confuse and bounce are not cleared).
  602. - Otherwise, if the target has the Swordedge Armor equipped, apply
  603. half the final damage plus 1 to the enemy.
  604. - Otherwise, if the target has the Shield of Sorrow equipped (and
  605. does not have the Cloak of Evasion equipped), choose a random
  606. living party member other than the target and apply the same damage
  607. to that character.
  608. - Apply any special effect of the attack (sleep, confusion, numbness)
  609. if the target is still alive.
  610.  
  611. - When an enemy attacks another enemy:
  612. - Compute the base damage as if the enemy was attacking the party
  613. member whose index is the low 2 bits of the target enemy's index.
  614. - Discard that value and recompute damage using the same algorithm
  615. as for attacking a party member, but using the target enemy's
  616. defense power instead.
  617. - Handle Surround and Bikill status as when attacking a party member.
  618. - If the target is parrying, halve the damage value and add 1.
  619. - Apply damage to the target.
  620.  
  621. - When checking a party member's resistance to a status effect which has
  622. a chance to miss:
  623. - Let the effect's base hit rate (out of 256) be H.
  624. - The chance C (out of 256) that the effect hits the party member is
  625. C = (((384 - luck) / 2) * H) / 128. (Conceptually, the base hit
  626. rate is multiplied by a factor from 0.5 to 1.5 based on the target
  627. character's Luck stat.)
  628. - If C >= 256, the effect hits.
  629. - Otherwise, take a multi-random number; if it is less than C, the
  630. effect hits.
  631. Base hit rates for standard effects are:
  632. - Beat: 32 (16 if Angel's Robe equipped)
  633. - Chaos: 64
  634. - Limbo: 50
  635. - Numb: 32
  636. - Poison: 96
  637. - Sap/Defence: 190
  638. - Sleep: 96
  639. - Slow: 192
  640. - StopSpell: 96
  641. - Surround: 160
  642. - Vivify: 128
  643.  
  644. - When checking an enemy's resistance to a damage spell or status
  645. effect, if the enemy is partially resistant (resistance index 1 or 2),
  646. the enemy resists the damage or effect if a multi-random number is
  647. less than the resistance chance (77 or ~30% for index 1, 179 or ~70%
  648. for index 2).
  649.  
  650. - When any character uses a damage spell on an enemy, damage for each
  651. target is computed as a multi-random number in the appropriate range:
  652. - Blaze: [8,14)
  653. - Blazemore: [70,90)
  654. - Blazemost: [160,200)
  655. - Firebal: [16,24)
  656. - Firebane: [30,42)
  657. - Firevolt: [88,112)
  658. - Bang: [16,24)
  659. - Boom: [52,68)
  660. - Explodet: [120,160)
  661. - IceBolt: [25,35)
  662. - Snowblast: [42,58)
  663. - Snowstorm: [88,112)
  664. - IceSpears: [60,80)
  665. - Infernos: [8,24)
  666. - Infermore: [25,55)
  667. - Infermost: [60,120)
  668. - Zap: [70,90)
  669. - Lightning: [175,225)
  670. Spell resistance is checked after damage is computed.
  671.  
  672. - When an enemy uses a damage spell or breath attack on a party member,
  673. damage for each target is computed as a multi-random number in the
  674. appropriate range:
  675. - Blaze: [7,12)
  676. - Blazemore: [52,62)
  677. - Blazemost: [92,128)
  678. - IceBolt: [16,24)
  679. - Firebal: [10,18)
  680. - Firebane: [22,34)
  681. - Explodet: [60,80)
  682. - Snowblast: [32,42)
  683. - Snowstorm: [55,67)
  684. - Infernos: [6,18)
  685. - Infermore: [14,34)
  686. - Infermost: [30,62)
  687. - Flaming breath (weak): [6,10)
  688. - Flaming breath (medium): [30,40)
  689. - Flaming breath (strong): [80,100)
  690. - Blizzard breath (weak): [9,21)
  691. - Blizzard breath (medium): [40,60)
  692. - Blizzard breath (strong): [100,140)
  693. Damage is reduce to 1/4 + 1 if the attack is a spell and the target
  694. has the Armor of Hades equipped, or to 2/3 if any of the below apply:
  695. - the target has the Armor of Radiance or Water Flying Cloth equipped
  696. - the attack is a breath attack and:
  697. - the target has Barrier status, or
  698. - the target has the Shield of Heroes equipped
  699. - the attack is a fire breath attack and the target has the Dragon
  700. Mail equipped
  701. - the attack is a spell attack and the target has the Magic Armor or
  702. Sacred Robe equipped
  703.  
  704. - When an enemy uses a breath attack on another enemy, damage for each
  705. target is computed as a multi-random number in the appropriate range:
  706. - Flaming breath (weak): [4,10)
  707. - Flaming breath (medium): [10,40)
  708. - Flaming breath (strong): [20,100)
  709. - Blizzard breath (weak): [12,21)
  710. - Blizzard breath (medium): [20,60)
  711. - Blizzard breath (strong): [40,140)
  712. The large damage ranges here appear to be due to a bug: the code that
  713. reads the base and range values ($8DDF in bank 4) gets them backwards,
  714. storing the base damage in the zero-page address used to hold the
  715. random range and vice versa.
  716.  
  717. - When a party member uses a Medical Herb:
  718. - Take a multi-random number in the range [35,50).
  719. - If the target is not Zoma, heal the target by that amount.
  720. - Otherwise, take a multi-random number in the range [0,219), add
  721. 229, and damage Zoma by the low 8 bits of that amount. (This is a
  722. bug in the code to assign damage from healing spells, which is also
  723. used for herbs: it doesn't check for the herb effect code ($41), so
  724. it reads past the end of the damage range table and takes bytes
  725. from the following routine's code as the damage range.)
  726.  
  727. - When a party member casts Beat on an enemy, if the enemy makes a
  728. successful resistance check against death, a second check is
  729. performed. This has the effect of squaring (and thus lowering) the
  730. enemy's resistance rate -- 30% death resistance becomes 9% resistance
  731. to Beat, and 70% death resistance becomes 49% resistance to Beat.
  732. Defeat does not make this second check, so the normal death resistance
  733. rate applies.
  734.  
  735. - When a party member or enemy casts Beat or Defeat on a party member,
  736. if the party member has the Sacred Amulet equipped, the effect always
  737. misses (thus skipping the resistance check).
  738.  
  739. - When using the Wizard's Ring:
  740. - Add a multi-random number in the range [10,25) to the user's MP.
  741. - Take a random number; if it is less than 25 (~10% chance), the
  742. ring breaks.
  743.  
  744. - When using the Chance spell:
  745. - If the encounter is not a preset encounter, take a multi-random
  746. number in the range [0,16] and execute that effect.
  747. - Otherwise (the encounter is a preset encounter), take the low 4
  748. bits of a multi-random number; if that value is at least 12,
  749. execute effect 1, otherwise execute effect 16.
  750. The possible effects are:
  751. - 0: Party sleep / enemy flee ("something unbelievably frightening")
  752. - 1: Healusall
  753. - 2: Revive on all dead party members if any, else Healusall
  754. - 3: Heal all party members for [41,48] HP
  755. - 4: Confuse all party members and enemies
  756. - 5: Kill all enemies ("<enemy> shatters into pieces")
  757. - 6: Kill all enemies (same as effect 5)
  758. - 7: Nullify spells ("fierce darkness")
  759. - 8: All party attacks become criticals ("additional Attack Power")
  760. - 9: Put all party members and enemies to sleep
  761. - 10: Caster gets 3 free turns ("time ceases")
  762. - 11: Randomize party formation ("party changes its formation")
  763. - 12: Enemies "depart"
  764. - 13: Party gets a free turn ("the foe is taken off guard")
  765. - 14: Steal all MP from all enemies
  766. - 15: Cure numbness on all party members
  767. - 16: No effect ("Chance...chance...chance...")
  768.  
  769. - Enemy data can be found at address $B2D3 in bank 0 (also entry $6A in
  770. the BRK #$07 array). The data is a list of 23-byte entries, one per
  771. enemy; corresponding enemy names are stored as two sequences of
  772. strings in bank 2, the first line's text at $B3BC and the second
  773. line's text at $B8BF. The data structure is as follows:
  774. - Byte 0, bits 7-6: bits 4-3 of evade rate
  775. - Byte 0, bits 5-0: level
  776. - Bytes 1-2: experience
  777. - Byte 3: speed
  778. - Byte 4: gold (low 8 bits)
  779. - Byte 5: attack power (low 8 bits)
  780. - Byte 6: defense power (low 8 bits)
  781. - Byte 7: base HP (low 8 bits)
  782. - Byte 8: MP
  783. - Byte 9, bit 7: bit 2 of evade rate (evade rate is a multiple of 4)
  784. - Byte 9, bits 6-0: item dropped ($7F = none)
  785. - Bytes 10-17, bits 5-0: possible actions
  786. - Bytes 10-11, bit 7: AI type selector (byte 11 has the high bit)
  787. - Type 0: random target choice
  788. - Type 1: smart target choice
  789. - Type 2: smart target choice, and action choice is delayed until
  790. enemy acts
  791. - Bytes 12-13, bit 7: action chance selector
  792. - Type 0: equal chance for all 8 actions
  793. - Type 1: $12, $16, $1A, $1E, $22, $26, $2A, $2E (/256)
  794. - Type 2: $02, $04, $06, $08, $0A, $0C, $0E, $C8 (/256)
  795. - Type 3: fixed action sequence
  796. - Bytes 14-15, bit 7: number of actions per turn
  797. - For AI type 2: 1, 1-2, 1-2, 2
  798. - For other AI types: 1, 1-2, 2, 1-3
  799. - Bytes 16-17, bit 7: HP regeneration selector
  800. - Type 0: no regeneration
  801. - Type 1: 16-23 HP/turn
  802. - Type 2: 44-55 HP/turn
  803. - Type 3: 90-109 HP/turn
  804. - Byte 18, bits 7-6: fire damage resistance
  805. - Byte 18, bits 5-4: ice damage resistance
  806. - Byte 18, bits 3-2: wind damage resistance
  807. - Byte 18, bits 1-0: gold (high 2 bits)
  808. - Byte 19, bits 7-6: lightning damage resistance
  809. - Byte 19, bits 5-4: instant death resistance
  810. - Byte 19, bits 3-2: Sacrifice resistance
  811. - Byte 19, bits 1-0: attack power (high 2 bits)
  812. - Byte 20, bits 7-6: Sleep resistance
  813. - Byte 20, bits 5-4: StopSpell resistance
  814. - Byte 20, bits 3-2: Sap resistance
  815. - Byte 20, bits 1-0: defense power (high 2 bits)
  816. - Byte 21, bits 7-6: Surround resistance
  817. - Byte 21, bits 5-4: RobMagic resistance
  818. - Byte 21, bits 3-2: Chaos resistance
  819. - Byte 21, bits 1-0: base HP (high 2 bits)
  820. - Byte 22, bits 7-6: Slow / Limbo resistance
  821. - Byte 22, bits 5-4: Expel / Fairy Water / Zombie Slasher resistance
  822. - Byte 22, bit 3: focus-fire flag (if set, the enemy continually
  823. attacks the same character until they die)
  824. - Byte 22, bits 2-0: item drop chance (100%, 1/8, 1/16, 1/32, 1/64,
  825. 1/128, 1/256, 1/2048)
  826.  
  827.  
  828. Why battle outcomes can differ even with the same RNG seed
  829. ----------------------------------------------------------
  830.  
  831. Battles use the same RNG as the rest of the game, but with a twist:
  832. Many routines that use randomness discard a certain number of random
  833. numbers from the RNG sequence before obtaining the actual random number
  834. to be used. The "certain number" is stored at address $6A68, which is
  835. updated with a random number in the range [0,15] during each turn of
  836. battle, after all characters' commands have been entered. (Attempting
  837. to run does not change this value.)
  838.  
  839. The catch is that $6A68 is _not_ cleared or initialized on reset. Since
  840. that address is within the backup RAM area, the value will be retained
  841. across reset and power-off. This is why, for example, battle outcomes
  842. when battling Metal Slimes near Dhama in a speedrun will differ even
  843. when resetting the RNG with a fixed seed from a separate file on each
  844. reset. $6A68 is not even cleared when initializing backup RAM on a
  845. fresh cart, so the value in that case is unpredictable (unless running
  846. on an emulator, in which case the emulator normally clears backup RAM to
  847. zero when the game is first run).
  848.  
  849.  
  850. Details of the random number generator (and how to break it)
  851. ------------------------------------------------------------
  852.  
  853. Dragon Warrior III has a very nearly high-quality random number
  854. generator for the NES era, using a 16-bit LFSR (linear feedback shift
  855. register) with a period of 65534 and adding the low 8 bits of the LFSR
  856. to an 8-bit counter to produce the final 8-bit random number. This
  857. gives an RNG sequence length of LCM(65534,256) = 8,388,352 values.
  858.  
  859. The random number generator algorithm is:
  860. for (16 iterations) {
  861. seed = LFSR(seed, 1)
  862. }
  863. counter += 1;
  864. return (byte)(seed + counter);
  865. where
  866. LFSR(seed, input) = (seed << 1) ^ ((seed>>15 ^ input) ? $1021 : 0)
  867.  
  868. I say "very nearly" high-quality because there are two initial seeds
  869. which give an LFSR sequence length of just 2: $5FEA and $AFF5. This
  870. property itself is unavoidable in any LFSR equation, but the problem is
  871. that the game does not attempt to avoid these seeds. Since the RNG
  872. algorithm clocks the LFSR 16 times per random number, this effectively
  873. means that if the seed is ever set to one of these two values, the RNG
  874. will simply return the counter plus a constant value (either $EA or
  875. $F5).
  876.  
  877. Now, since those two seeds are not part of the 65534-long sequence, it
  878. should normally be impossible to encounter them in the first place. But
  879. it turns out there's one place in the code which calls the LFSR shift
  880. function with non-constant input bits: the save file checksum routine.
  881. The game calculates a 16-bit checksum for each save file (787 bytes of
  882. data) by setting an initial seed of $3A3A, passing each bit of the data
  883. as the input bit to the LFSR function, and taking the resulting LFSR
  884. value as the checksum (the routine can be found at $ACD0 in bank 7).
  885. The game doesn't check whether that checksum is one of the two values
  886. above that generate a short sequence, so if we can generate a save file
  887. with one of those values as the checksum, we can make the RNG misbehave.
  888.  
  889. When creating a new file, we directly control a total of 10 bytes:
  890. - The hero's name (8 bytes at offset $114)
  891. - The hero's sex (bit 3 of the byte at offset $48)
  892. - The message speed (1 byte at offset $311)
  893. We also indirectly control the names and status of the autogenerated
  894. party characters; the names are picked randomly from a pool of 4 names
  895. for each character, and each stat randomly (50% chance) has 1 added to
  896. the base value. The save file is checksummed after generating each of
  897. the four initial characters; naturally, we need the seed after the
  898. final checksum to be one of the two short-sequence values.
  899.  
  900. There are many name/sex/speed combinations which produce the desired
  901. result in a new save file, which can then be used to reset the RNG seed
  902. on the initial menu screen by changing the message speed for the file
  903. (to the same speed it's already set at). Some short names include:
  904. File: 1 Name: pP Sex: F Speed: 7 Checksum: $5FEA
  905. File: 1 Name: iGa Sex: M Speed: 7 Checksum: $5FEA
  906. File: 2 Name: am Sex: F Speed: 6 Checksum: $AFF5
  907. File: 2 Name: E? Sex: F Speed: 5 Checksum: $5FEA
  908. File: 2 Name: DOg Sex: M Speed: 7 Checksum: $5FEA
  909. File: 2 Name: Ndt Sex: M Speed: 6 Checksum: $AFF5
  910. File: 3 Name: -a Sex: M Speed: 6 Checksum: $AFF5
  911. File: 3 Name: Qg Sex: M Speed: 7 Checksum: $5FEA
  912. File: 3 Name: mop Sex: F Speed: 7 Checksum: $5FEA
  913.  
  914. For reference, the mapping from text characters to name data is:
  915. a...z = $0B...$24
  916. A...Z = $25...$3E
  917. Space = $50
  918. ' = $68
  919. , = $6A
  920. - = $6B
  921. . = $6C
  922. ( = $6D
  923. ) = $6E
  924. ? = $6F
  925. ! = $70
  926. Names are padded with $00 to a length of 8 bytes.
  927.  
  928. One caveat with "breaking" the RNG in this fashion is that it can cause
  929. the game to lock up when starting an encounter. This happens due to
  930. poor design of the core "ranged random number" function ($C3F1) combined
  931. with the lack of a safety valve in one part of the encounter generation
  932. logic. Specifically, in the "Choose a random number from 0 through 2"
  933. item described earlier (at $8573 in bank 0), if the encounter has two
  934. groups and the next RNG output on entry to that step is 1 or 2 (mod 4),
  935. the following will occur:
  936. - The low 2 bits of the first random number returned are nonzero,
  937. so the loop is not terminated.
  938. - The next ranged random number call (to get a group index) will see
  939. a random number outside the requested range of 0 through 1, so it
  940. will consume random numbers until it reaches one whose low 2 bits
  941. are zero, giving group index 0.
  942. - At the next iteration, the low 2 bits of the first random number
  943. will equal 1, so the loop is not terminated.
  944. - The next ranged random call will get group index 0, and so on
  945. ad infinitum.
  946. The code places no limit on the number of loop iterations, so if the
  947. loop enters this state, the game will halt.
  948.  
  949. An interesting consequence of using one of these two seeds is that
  950. physical attacks in battles which use the standard damage formula will
  951. always give either the maximum ($5FEA) or minimum ($AFF5) possible
  952. damage, and level-up bonuses for the five basic stats will be
  953. consistently low ($5FEA) or high ($AFF5).
  954.  
  955.  
  956. Random numbers in other NES Dragon Warrior games
  957. ------------------------------------------------
  958.  
  959. The LFSR function used in Dragon Warrior III's random number generator
  960. dates all the way back to the original Dragon Warrior. There, the
  961. function was used only to compute save file checksums (see $FC2A); the
  962. RNG was seeded from the 16-bit checksum and subsequently updated with
  963. the formula seed <- seed * 3 + 129 (see $C55B), taking the low byte of
  964. the seed as the RNG output. This function produces two independent
  965. sequences of 32768 values depending on the starting seed, and does not
  966. have any "holes" with extremely short sequences. The RNG seed is stored
  967. at $94.
  968.  
  969. Dragon Warrior II was the first game in the series to use the LFSR for
  970. random number generation as well. It uses essentially the same logic
  971. as DW3, except that it does not keep a counter to add to the seed when
  972. generating RNG output, so if the seed falls into one of the holes, the
  973. RNG's output will become constant. The RNG seed is stored at $32.
  974.  
  975. Dragon Warrior IV uses the same RNG as DW3. The RNG seed is stored at
  976. $12, and the output counter is stored at $050D.
RAW Paste Data