Advertisement
Guest User

Random numbers in Dragon Warrior III

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