Skip to content

Free games for graphing calculators: NumWorks, TI-Nspire CX, Casio fx-CG50 and soon TI-84 Plus CE. Balatro, Celeste, Hollow Knight, Minecraft and more.

FNAF World: the map, the party and the battles

Mason3634aceecdfb836
diff --git a/games/fnafworld/.gitignore b/games/fnafworld/.gitignore
new file mode 100644
index 00000000..edd4c316
--- /dev/null
+++ b/games/fnafworld/.gitignore
@@ -0,0 +1,4 @@
+output/
+build/
+ref/
+__pycache__/
diff --git a/games/fnafworld/Makefile b/games/fnafworld/Makefile
new file mode 100644
index 00000000..d530304e
--- /dev/null
+++ b/games/fnafworld/Makefile
@@ -0,0 +1,78 @@
+# FNAF World on the NumWorks calculator.
+# make output/fnafworld.nwa
+# make check link it like the calculator does (output/fnafworld.bin)
+# make host build/rules: the game on a computer, for tests and screenshots
+# make test the game played on a computer (tests/rules.c, with the sanitizers)
+# make data src/data.bin, src/data.h and src/anims.h from the game's app.ccn (CCN=its path; Python + Pillow + NumPy)
+
+Q ?= @
+# the ARM toolchain on the PATH, or in TOOLCHAIN=<its bin folder>
+TOOLCHAIN ?=
+BIN = $(if $(TOOLCHAIN),$(TOOLCHAIN)/)
+CC = $(BIN)arm-none-eabi-gcc
+NWLINK ?= npx --yes -- [email protected]
+STRIP ?= $(BIN)arm-none-eabi-strip --strip-unneeded
+SIZE = $(BIN)arm-none-eabi-size
+BUILD_DIR = output
+CCN ?=
+
+# the pictures are decoded and drawn every frame at -O2; the rest is small at -Os
+HOT = src/pic.c src/gfx.c
+COLD = $(filter-out $(HOT) src/plat_host.c src/plat_eadk.c,$(wildcard src/*.c))
+COLD_OBJ = $(patsubst src/%.c,$(BUILD_DIR)/cold/%.o,$(COLD))
+HEADERS = $(wildcard src/*.h) ../common/epsilon_app.h ../common/epsilon_files.h
+
+CFLAGS = -std=gnu11 $(shell $(NWLINK) eadk-cflags-device) -DEPSILON_XL=1 -DDATA_BIN='"src/data.bin"'
+CFLAGS += -O2 -Wall -Wextra -Wno-unused-parameter -fno-math-errno -fsingle-precision-constant
+CFLAGS += -fno-tree-loop-distribute-patterns -flto -fno-fat-lto-objects -fwhole-program -fvisibility=internal
+CFLAGS += -ffunction-sections -fdata-sections $(EXTRA)
+LDFLAGS = -Wl,--relocatable -nostartfiles --specs=nano.specs
+LDFLAGS += -Wl,-e,main -Wl,-u,eadk_app_name -Wl,-u,eadk_app_icon -Wl,-u,eadk_api_level
+LDFLAGS += -Wl,--gc-sections -flinker-output=nolto-rel
+
+.PHONY: build check clean host test data
+build: $(BUILD_DIR)/fnafworld.nwa
+
+# apps get 133652 bytes of RAM on custom builds of Epsilon 25.2 (148928 or more on official ones)
+check: $(BUILD_DIR)/fnafworld.nwa
+ $(Q) $(NWLINK) nwa-bin --ram-length 133652 $< $(BUILD_DIR)/fnafworld.bin
+ @echo "BIN $(BUILD_DIR)/fnafworld.bin: $$(wc -c < $(BUILD_DIR)/fnafworld.bin) bytes"
+
+$(BUILD_DIR)/data.o: src/data.S src/data.bin | $(BUILD_DIR)
+ $(Q) $(CC) -c -DDATA_BIN='"src/data.bin"' $< -o $@
+
+$(BUILD_DIR)/cold/%.o: src/%.c $(HEADERS)
+ @mkdir -p $(@D)
+ $(Q) $(CC) $(CFLAGS) -Os -c $< -o $@
+
+$(BUILD_DIR)/fnafworld.nwa: $(HOT) src/plat_eadk.c $(COLD_OBJ) $(HEADERS) $(BUILD_DIR)/icon.o $(BUILD_DIR)/data.o
+ @echo "LD $@"
+ $(Q) $(CC) $(CFLAGS) $(LDFLAGS) $(HOT) src/plat_eadk.c $(COLD_OBJ) $(BUILD_DIR)/data.o $(BUILD_DIR)/icon.o -lm -o $@
+ $(Q) $(STRIP) $@
+ $(Q) $(SIZE) $@
+
+$(BUILD_DIR)/icon.o: src/icon.png | $(BUILD_DIR)
+ @echo "ICON $<"
+ $(Q) $(NWLINK) png-icon-o $< $@
+
+$(BUILD_DIR):
+ $(Q) mkdir -p $@
+
+# on a computer: tests/rules.c checks the rules, plays battles, walks, presses random keys, keeps files
+HOST_FLAGS = -std=gnu11 -O1 -g -Wall -Wextra -Wno-unused-parameter -Isrc -DHOST -DDATA_BIN='"src/data.bin"'
+HOST_SAN = -fsanitize=address,undefined -fno-sanitize-recover=undefined
+HOST_SRC = $(filter-out src/plat_eadk.c src/main.c,$(wildcard src/*.c))
+host: build/rules
+
+build/rules: $(HOST_SRC) tests/rules.c src/data.S src/data.bin $(HEADERS)
+ $(Q) mkdir -p $(dir $@)
+ $(Q) cc $(HOST_FLAGS) $(HOST_SAN) $(HOST_SRC) tests/rules.c src/data.S -lm -o $@
+
+test: host
+ ASAN_OPTIONS=detect_leaks=0 UBSAN_OPTIONS=halt_on_error=1 build/rules
+
+data:
+ python3 -I tools/pack.py $(CCN)
+
+clean:
+ $(Q) rm -rf $(BUILD_DIR) build
diff --git a/games/fnafworld/README.md b/games/fnafworld/README.md
new file mode 100644
index 00000000..4260cd90
--- /dev/null
+++ b/games/fnafworld/README.md
@@ -0,0 +1,33 @@
+<p align="center">
+ <img src="src/icon.png" width="84" alt="FNAF World icon">
+</p>
+
+<h1 align="center">FNAF World</h1>
+
+<p align="center">
+ <b>The FNAF World adventure, on the NumWorks calculator.</b><br>
+ Walk the world, battle with a party of eight, find chips, buy bytes, beat the bosses.
+</p>
+
+<p align="center">
+ <a href="https://github.com/Mason363/NumPlay/releases/latest/download/FiveNightsAtFreddysWorld.nwa"><b>Download FiveNightsAtFreddysWorld.nwa</b></a>
+ &nbsp;·&nbsp; <a href="#controls">Controls</a>
+</p>
+
+## Controls
+
+| Key | What it does |
+| --- | --- |
+| Arrows | Walk, pick |
+| OK or EXE | Attack, choose |
+| 1 2 3 | An attack straight away |
+| Backspace | Switch the party's rows in battle |
+| 0 held | Run from a battle |
+| Back | Menu, go back |
+| Home | Save and quit |
+
+## Credits
+
+Inspired by FNAF World by Scott Cawthon, not affiliated with him.
+
+Made by Mason Chen as part of NumPlay.
diff --git a/games/fnafworld/src/anims.h b/games/fnafworld/src/anims.h
new file mode 100644
index 00000000..6c00f692
--- /dev/null
+++ b/games/fnafworld/src/anims.h
@@ -0,0 +1,738 @@
+/* Made by tools/pack.py: the game's animations (AN_*), its own speeds and plays. Included once (anim.c). */
+#ifndef FNAFW_ANIMS_H
+#define FNAFW_ANIMS_H
+#include <stdint.h>
+
+typedef struct {
+ uint16_t first; /* in ANIM_PICS */
+ uint8_t n, speed, plays, back; /* a picture lasts 100 / speed frames; plays 0: for ever */
+} AnimDef;
+
+enum {
+ AN_IDLE1,
+ AN_ATTACK1,
+ AN_IDLE2,
+ AN_ATTACK2,
+ AN_IDLE3,
+ AN_ATTACK3,
+ AN_IDLE4,
+ AN_ATTACK4,
+ AN_IDLE5,
+ AN_ATTACK5,
+ AN_IDLE6,
+ AN_ATTACK6,
+ AN_IDLE7,
+ AN_ATTACK7,
+ AN_IDLE8,
+ AN_ATTACK8,
+ AN_IDLE9,
+ AN_ATTACK9,
+ AN_IDLE10,
+ AN_ATTACK10,
+ AN_IDLE11,
+ AN_ATTACK11,
+ AN_IDLE12,
+ AN_ATTACK12,
+ AN_IDLE13,
+ AN_ATTACK13,
+ AN_IDLE14,
+ AN_ATTACK14,
+ AN_IDLE15,
+ AN_ATTACK15,
+ AN_IDLE16,
+ AN_ATTACK16,
+ AN_IDLE17,
+ AN_ATTACK17,
+ AN_IDLE18,
+ AN_ATTACK18,
+ AN_IDLE19,
+ AN_ATTACK19,
+ AN_IDLE20,
+ AN_ATTACK20,
+ AN_IDLE21,
+ AN_ATTACK21,
+ AN_IDLE22,
+ AN_ATTACK22,
+ AN_IDLE23,
+ AN_ATTACK23,
+ AN_IDLE24,
+ AN_ATTACK24,
+ AN_IDLE25,
+ AN_ATTACK25,
+ AN_IDLE26,
+ AN_ATTACK26,
+ AN_IDLE27,
+ AN_ATTACK27,
+ AN_IDLE28,
+ AN_ATTACK28,
+ AN_IDLE29,
+ AN_ATTACK29,
+ AN_IDLE30,
+ AN_ATTACK30,
+ AN_IDLE31,
+ AN_ATTACK31,
+ AN_IDLE32,
+ AN_ATTACK32,
+ AN_IDLE33,
+ AN_ATTACK33,
+ AN_IDLE34,
+ AN_ATTACK34,
+ AN_IDLE35,
+ AN_ATTACK35,
+ AN_IDLE36,
+ AN_ATTACK36,
+ AN_IDLE37,
+ AN_ATTACK37,
+ AN_IDLE38,
+ AN_ATTACK38,
+ AN_IDLE39,
+ AN_ATTACK39,
+ AN_IDLE40,
+ AN_ATTACK40,
+ AN_IDLE41,
+ AN_ATTACK41,
+ AN_IDLE42,
+ AN_ATTACK42,
+ AN_IDLE43,
+ AN_ATTACK43,
+ AN_IDLE44,
+ AN_ATTACK44,
+ AN_IDLE45,
+ AN_ATTACK45,
+ AN_IDLE46,
+ AN_ATTACK46,
+ AN_IDLE47,
+ AN_ATTACK47,
+ AN_IDLE48,
+ AN_ATTACK48,
+ AN_KO,
+ AN_ENEMY0,
+ AN_ENEMY12,
+ AN_ENEMY13,
+ AN_ENEMY14,
+ AN_ENEMY15,
+ AN_ENEMY16,
+ AN_ENEMY17,
+ AN_ENEMY18,
+ AN_ENEMY19,
+ AN_ENEMY20,
+ AN_ENEMY21,
+ AN_ENEMY22,
+ AN_ENEMY23,
+ AN_ENEMY24,
+ AN_ENEMY25,
+ AN_ENEMY26,
+ AN_ENEMY27,
+ AN_ENEMY28,
+ AN_ENEMY29,
+ AN_ENEMY30,
+ AN_ENEMY31,
+ AN_ENEMY32,
+ AN_ENEMY33,
+ AN_ENEMY34,
+ AN_ENEMY35,
+ AN_ENEMY36,
+ AN_ENEMY37,
+ AN_ENEMY38,
+ AN_ENEMY39,
+ AN_ENEMY40,
+ AN_CHAL9,
+ AN_CHAL10,
+ AN_CHAL11,
+ AN_CHAL12,
+ AN_CHAL13,
+ AN_CHAL14,
+ AN_CHAL15,
+ AN_CHAL16,
+ AN_CHAL17,
+ AN_CHAL18,
+ AN_CHAL19,
+ AN_CHAL20,
+ AN_CHAL21,
+ AN_CHAL22,
+ AN_CHAL23,
+ AN_CHAL24,
+ AN_CHAL25,
+ AN_CHAL26,
+ AN_CHAL27,
+ AN_CHAL28,
+ AN_CHAL29,
+ AN_CHAL30,
+ AN_CHAL31,
+ AN_CHAL32,
+ AN_CHAL33,
+ AN_CHAL34,
+ AN_CHAL35,
+ AN_CHAL36,
+ AN_CHAL37,
+ AN_CHAL38,
+ AN_CHAL39,
+ AN_CHAL40,
+ AN_BOSS51,
+ AN_BOSS52,
+ AN_BOSS53,
+ AN_BOSS54,
+ AN_BOSS55,
+ AN_BOSS56,
+ AN_BOSS57,
+ AN_BOSS58,
+ AN_BOSS59,
+ AN_BOSS60,
+ AN_BOSS61,
+ AN_BOSS62,
+ AN_BOSS63,
+ AN_HIT0,
+ AN_HIT12,
+ AN_HIT13,
+ AN_HIT14,
+ AN_HIT15,
+ AN_HIT16,
+ AN_HIT17,
+ AN_HIT18,
+ AN_HIT19,
+ AN_HIT20,
+ AN_HIT21,
+ AN_SPARK,
+ AN_MICSPIN,
+ AN_PIZZA,
+ AN_PIZZA2,
+ AN_BITE,
+ AN_BITE2,
+ AN_BITE3,
+ AN_MEGABITE,
+ AN_BITE4,
+ AN_TOXICBITE,
+ AN_HOOK,
+ AN_SCARE,
+ AN_NOTE,
+ AN_NOTE2,
+ AN_TORNADO,
+ AN_CLAW,
+ AN_CLAW2,
+ AN_DIZZY,
+ AN_BROKEN,
+ AN_POW,
+ AN_STAR,
+ AN_CLOUD,
+ AN_PRIZE,
+ AN_PRIZE2,
+ AN_POPPER,
+ AN_MUNCHIE,
+ AN_MUNCHIE2,
+ AN_HEAD,
+ AN_FREDDLE,
+ AN_BADPIZZA,
+ AN_ENDO,
+ AN_ENDO2,
+ AN_DAGGER,
+ AN_SAW,
+ AN_JACKO,
+ AN_ANTI,
+ AN_GIFT,
+ AN_MIMIC,
+ AN_MIMIC2,
+ AN_SCREW,
+ AN_DRIP,
+ AN_BADNOTE,
+ AN_SYTH,
+ AN_STINGER,
+ AN_PBUBBLE,
+ AN_SPARKLE,
+ AN_VICTORY,
+ AN_LEVELUP,
+ AN_RUN,
+ AN_CHALLENGER,
+ AN_NEWMEMBER,
+ AN_WALL,
+ AN_BUBBLE,
+ AN_DOWN,
+ AN_DOWN2,
+ AN_DOWN3,
+ AN_BALLOON0,
+ AN_BALLOON1,
+ AN_BALLOON2,
+ AN_BALLOON3,
+ AN_WATER,
+ AN_WATER2,
+ AN_PUDDLE,
+ AN_SHIELD,
+ AN_SPECIAL0,
+ AN_SPECIAL12,
+ AN_SPECIAL13,
+ AN_SPECIAL14,
+ AN_SPECIAL15,
+ AN_SPECIAL16,
+ AN_SPECIAL17,
+ AN_SPECIAL18,
+ AN_SPECIAL19,
+ AN_SPECIAL20,
+ AN_SPECIAL21,
+ AN_BYTE1,
+ AN_BYTE2,
+ AN_BYTE3,
+ AN_BYTE4,
+ AN_BYTE5,
+ AN_BYTE6,
+ AN_BYTE7,
+ AN_BYTE8,
+ AN_BYTE9,
+ AN_BYTE10,
+ AN_BYTE11,
+ AN_BYTE12,
+ AN_BYTE13,
+ AN_BYTE14,
+ AN_BYTE15,
+ AN_BYTE16,
+ AN_BYTE17,
+ AN_BYTE18,
+ AN_BYTE19,
+ AN_BYTE20,
+ AN_BYTE21,
+ AN_COUNT
+};
+
+static const uint16_t ANIM_PICS[] = {
+ 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81,
+ 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97,
+ 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113,
+ 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129,
+ 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145,
+ 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161,
+ 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177,
+ 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193,
+ 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209,
+ 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225,
+ 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241,
+ 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, 256, 257,
+ 258, 259, 260, 261, 262, 263, 264, 265, 266, 267, 268, 269, 270, 271, 272, 273,
+ 274, 275, 276, 277, 278, 279, 280, 281, 282, 283, 284, 285, 286, 287, 288, 289,
+ 290, 291, 292, 293, 294, 295, 296, 297, 298, 299, 300, 301, 302, 303, 304, 305,
+ 306, 307, 308, 309, 310, 311, 312, 313, 314, 315, 316, 317, 318, 319, 320, 321,
+ 322, 323, 324, 325, 326, 327, 328, 329, 330, 331, 332, 333, 334, 335, 336, 337,
+ 338, 339, 340, 341, 342, 343, 344, 345, 346, 347, 348, 349, 350, 351, 352, 353,
+ 354, 355, 356, 357, 358, 359, 360, 361, 362, 363, 364, 365, 366, 367, 368, 369,
+ 370, 371, 372, 373, 374, 375, 376, 377, 378, 379, 380, 381, 382, 383, 384, 385,
+ 386, 387, 388, 389, 390, 391, 392, 393, 394, 395, 396, 397, 398, 399, 400, 401,
+ 402, 403, 404, 405, 406, 407, 408, 409, 410, 411, 412, 413, 414, 415, 416, 417,
+ 418, 419, 420, 421, 422, 423, 424, 425, 426, 427, 428, 429, 430, 431, 432, 433,
+ 434, 435, 436, 437, 438, 439, 440, 441, 442, 443, 444, 445, 446, 447, 448, 449,
+ 450, 451, 452, 453, 454, 455, 456, 457, 458, 459, 460, 461, 462, 463, 464, 465,
+ 466, 467, 468, 469, 470, 471, 472, 473, 474, 475, 476, 477, 478, 479, 480, 481,
+ 482, 483, 484, 485, 486, 487, 488, 489, 490, 491, 492, 493, 494, 495, 496, 497,
+ 498, 499, 500, 501, 502, 503, 504, 505, 506, 507, 508, 509, 510, 511, 512, 513,
+ 514, 515, 516, 517, 518, 519, 520, 521, 522, 523, 524, 525, 526, 527, 528, 529,
+ 530, 531, 532, 533, 534, 535, 536, 537, 538, 539, 540, 541, 542, 543, 544, 545,
+ 546, 547, 548, 549, 550, 551, 552, 553, 554, 555, 556, 557, 558, 559, 560, 561,
+ 562, 563, 564, 565, 566, 567, 568, 569, 570, 571, 572, 573, 574, 575, 576, 577,
+ 578, 579, 580, 581, 582, 583, 584, 585, 586, 587, 588, 589, 590, 591, 592, 593,
+ 594, 595, 596, 597, 598, 599, 600, 601, 602, 603, 604, 605, 606, 607, 608, 609,
+ 610, 611, 612, 613, 614, 615, 616, 617, 618, 619, 620, 621, 622, 623, 624, 625,
+ 626, 627, 628, 629, 630, 631, 632, 633, 634, 635, 636, 637, 638, 639, 640, 641,
+ 642, 643, 644, 645, 646, 647, 648, 649, 650, 651, 652, 653, 654, 655, 656, 657,
+ 658, 659, 660, 661, 662, 663, 664, 665, 666, 667, 668, 669, 670, 671, 672, 673,
+ 674, 675, 676, 677, 678, 679, 680, 681, 682, 683, 684, 685, 686, 687, 688, 689,
+ 690, 691, 692, 693, 694, 695, 696, 697, 698, 699, 700, 701, 702, 703, 704, 705,
+ 706, 707, 708, 709, 710, 711, 712, 713, 714, 715, 716, 717, 718, 719, 720, 721,
+ 722, 723, 724, 725, 726, 727, 728, 729, 730, 731, 732, 733, 734, 735, 736, 737,
+ 738, 739, 740, 741, 742, 743, 744, 745, 746, 747, 748, 749, 750, 751, 752, 753,
+ 754, 755, 756, 757, 758, 759, 760, 761, 762, 763, 764, 765, 766, 767, 768, 769,
+ 770, 771, 772, 773, 774, 775, 776, 777, 778, 779, 780, 781, 782, 783, 784, 785,
+ 786, 787, 788, 789, 790, 791, 792, 793, 794, 795, 796, 797, 798, 799, 800, 801,
+ 802, 803, 804, 805, 806, 807, 808, 809, 810, 811, 812, 813, 814, 815, 816, 817,
+ 818, 819, 820, 821, 822, 823, 824, 825, 826, 827, 828, 829, 830, 831, 832, 833,
+ 834, 835, 836, 837, 838, 839, 840, 841, 842, 843, 844, 845, 846, 847, 848, 849,
+ 850, 851, 852, 853, 854, 855, 856, 857, 858, 859, 860, 861, 862, 863, 864, 865,
+ 866, 867, 868, 869, 870, 871, 872, 873, 874, 875, 876, 877, 878, 879, 880, 881,
+ 882, 883, 884, 885, 886, 887, 888, 889, 890, 891, 892, 893, 894, 895, 896, 897,
+ 898, 899, 900, 901, 902, 903, 904, 905, 906, 907, 908, 909, 910, 911, 912, 913,
+ 914, 915, 916, 917, 918, 919, 920, 921, 922, 923, 924, 925, 926, 927, 928, 929,
+ 930, 931, 932, 933, 934, 935, 936, 937, 938, 939, 940, 941, 942, 943, 944, 945,
+ 946, 947, 948, 949, 950, 951, 952, 953, 954, 955, 956, 957, 958, 959, 960, 961,
+ 962, 963, 964, 965, 966, 967, 968, 969, 970, 971, 972, 973, 974, 975, 976, 977,
+ 978, 979, 980, 981, 982, 983, 984, 985, 986, 987, 988, 989, 990, 991, 992, 993,
+ 994, 995, 996, 997, 998, 999, 1000, 1001, 1002, 1003, 1004, 1005, 1006, 1007, 998, 999,
+ 1000, 1001, 1002, 1003, 1004, 1005, 1006, 1007, 1008, 1009, 1010, 1011, 1012, 1013, 1014, 1015,
+ 1016, 1017, 1018, 1019, 1020, 1021, 1022, 1023, 1024, 1025, 1026, 1027, 1028, 1029, 1030, 1031,
+ 1032, 1033, 1034, 1035, 1036, 1037, 1038, 1039, 1040, 1041, 1042, 1043, 1044, 1045, 1046, 1047,
+ 1048, 1049, 1050, 1051, 1052, 1053, 1054, 1055, 1056, 1057, 1058, 1059, 1060, 1061, 1062, 1063,
+ 1064, 1065, 1066, 1067, 1068, 1069, 1070, 1071, 1072, 1073, 1074, 1075, 1076, 1077, 1078, 1079,
+ 1080, 1081, 1082, 1083, 1084, 1085, 1086, 1087, 1088, 1089, 1090, 1091, 1091, 1091, 1091, 1091,
+ 1092, 1092, 1092, 1092, 1092, 1093, 1094, 1095, 1096, 1097, 1098, 1099, 1100, 1101, 1102, 1103,
+ 1104, 1105, 1106, 1107, 1108, 1109, 1110, 1111, 1112, 1113, 1114, 1115, 1116, 1117, 1118, 1119,
+ 1120, 1121, 1122, 1123, 1124, 1125, 1126, 1127, 1128, 1129, 1130, 1131, 1132, 1133, 1134, 1135,
+ 1136, 1137, 1138, 1139, 1140, 1141, 1142, 1143, 1144, 1145, 1146, 1147, 1148, 1149, 1150, 1151,
+ 1152, 1153, 1154, 1155, 1156, 1157, 1158, 1159, 1160, 1161, 1162, 1163, 1164, 1165, 1166, 1167,
+ 1168, 1169, 1170, 1171, 1172, 1173, 1174, 1175, 1176, 1177, 1178, 1179, 1180, 1181, 1182, 1183,
+ 1184, 1185, 1186, 1187, 1188, 1189, 1190, 1191, 1192, 1193, 1194, 1195, 1196, 1197, 1198, 1199,
+ 1200, 1201, 1202, 1203, 1204, 1205, 1206, 1207, 1208, 1209, 1210, 1211, 1212, 1213, 1214, 1215,
+ 1216, 1217, 1218, 1219, 1220, 1221, 1222, 1223, 1224, 1225, 1226, 1227, 1228, 1229, 1230, 1231,
+ 1232, 1233, 1234, 1235, 1236, 1237, 1238, 1239, 1240, 1241, 1242, 1243, 1244, 1245, 1246, 1247,
+ 1248, 1249, 1250, 1251, 1252, 1253, 1254, 1255, 1256, 1257, 1258, 1259, 1260, 1261, 1262, 1263,
+ 1264, 1265, 1266, 1267, 1268, 1269, 1270, 1271, 1272, 1273, 1274, 1275, 1276, 1277, 1278, 1279,
+ 1280, 1281, 1282, 1283, 1284, 1285, 1286, 1287, 1288, 1289, 1290, 1291, 1292, 1293, 1294, 1295,
+ 1296, 1297, 1298, 1299, 1300, 1301, 1302, 1303, 1304, 1305, 1306, 1307, 1308, 1309, 1310, 1311,
+ 1312, 1313, 1314, 1315, 1316, 1317, 1318, 1319, 1320, 1321, 1322, 1323, 1324, 1325, 1326, 1327,
+ 1328, 1329, 1330, 1331, 1332, 1333, 1334, 1335, 1336, 1337, 1338, 1339, 1340, 1341, 1342, 1343,
+ 1344, 1345, 1346, 1347, 1348, 1349, 1350, 1351, 1352, 1353, 1354, 1355, 1356, 1357, 1358, 1359,
+ 1360, 1361, 1362, 1363, 1364, 1365, 1366, 1367, 1368, 1369, 1370, 1371, 1372, 1373, 1374, 1375,
+ 1376, 1377, 1377, 1377, 1377, 1377, 1377, 1378, 1378, 1378, 1378, 1378, 1378, 1379, 1379, 1379,
+ 1379, 1379, 1379, 1380, 1380, 1380, 1380, 1380, 1380, 1381, 1381, 1381, 1381, 1381, 1381, 1382,
+ 1382, 1382, 1382, 1382, 1382, 1383, 1384, 1385, 1386, 1387, 1388, 1389, 1390, 1391, 1392, 1393,
+ 1394, 1395, 1396, 1397, 1398, 1399, 1400, 1401, 1402, 1403, 1404, 1405, 1406, 1407, 1408, 1409,
+ 1410, 1411, 1412, 1413, 1414, 1415, 1416, 1417, 1418, 1419, 1420, 1421, 1422, 1423, 1424, 1425,
+ 1426, 1427, 1428, 1429, 1430, 1431, 1432, 1433, 1434, 1435, 1436, 1437, 1438, 1439, 1440, 1441,
+ 1442, 1443, 1444, 1445, 1446, 1447, 1448, 1449, 1450, 1451, 1452, 1453, 1454, 1455, 1456, 1457,
+ 1458, 1459, 1460, 1461, 1462, 1463, 1464, 1465, 1466, 1467, 1468, 1469, 1470, 1471, 1472, 1473,
+ 1474, 1475, 1476, 1477, 1478, 1479, 1480, 1481, 1482, 1483, 1484, 1485, 1486, 1487, 1488, 1489,
+ 1490, 1491, 1492, 1493, 1494, 1495, 1496, 1497, 1498, 1499, 1500, 1501, 1502, 1503, 1504, 1505,
+ 1506, 1507, 1508, 1509, 1510, 1511, 1512, 1513, 1514, 1515, 1516, 1517, 1518, 1519, 1520, 1521,
+ 1522, 1523, 1524, 1525, 1526, 1527, 1528, 1529, 1530, 1531, 1532, 1533, 1534, 1535, 1536, 1537,
+ 1538, 1539, 1540, 1541, 1542, 1543, 1544, 1545, 1546, 1547, 1548, 1549, 1550, 1551, 1552, 1553,
+ 1554, 1555, 1556, 1557, 1558, 1559, 1560, 1561, 1562, 1563, 1564, 1565, 1566, 1567, 1568, 1569,
+ 1570, 1571, 1572, 1573, 1574, 1575, 1576, 1577, 1578, 1579, 1580, 1581, 1582, 1583, 1584, 1585,
+ 1586, 1587, 1588, 1589, 1590, 1591, 1592, 1593, 1594, 1595, 1596, 1597, 1598, 1599, 1600, 1601,
+ 1602, 1603, 1604, 1605, 1606, 1607, 1608, 1609, 1610, 1611, 1612, 1613, 1614, 1615, 1616, 1617,
+ 1618, 1619, 1620, 1621, 1622, 1623, 1624, 1625, 1626, 1627, 1628, 1629, 1630, 1631, 1632, 1633,
+ 1634, 1635, 1636, 1637, 1638, 1639, 1640, 1641, 1642, 1643, 1644, 1645, 1646, 1647, 1648, 1649,
+ 1650, 1651, 1652, 1653, 1654, 1655, 1656, 1657, 1658, 1659, 1660, 1661, 1662, 1663, 1664, 1665,
+ 1666, 1667, 1668, 1669, 1670, 1671, 1672, 1673, 1674, 1675, 1676, 1677, 1678, 1679, 1680, 1681,
+ 1682, 1683, 1684, 1685, 1686, 1687, 1688, 1689, 1690, 1691, 1692, 1693, 1694, 1695, 1696, 1697,
+ 1698, 1699, 1700, 1701, 1702, 1703, 1704, 1705, 1706, 1707, 1708, 1709, 1710, 1711, 1712, 1713,
+ 1714, 1715, 1716, 1717, 1718, 1719, 1720, 1721, 1722, 1723, 1724, 1725, 1726, 1727, 1728, 1729,
+ 1730, 1731, 1732, 1733, 1734, 1735, 1736, 1737, 1738, 1739, 1740, 1741, 1742, 1743, 1744, 1745,
+ 1746, 1747, 1748, 1749, 1750, 1751, 1752, 1753, 1754, 1755, 1756, 1757, 1758, 1759, 1760, 1761,
+ 1762, 1763, 1764, 1765, 1766, 1767, 1768, 1769, 1770, 1771, 1772, 1773, 1774, 1775, 1776, 1777,
+ 1778, 1779, 1780, 1781, 1782, 1783, 1784, 1785, 1786, 1787, 1788, 1789, 1790, 1791, 1792, 1793,
+ 1794, 1795, 1796, 1797, 1798, 1799, 1800, 1801, 1802, 1803, 1804, 1805, 1806, 1807, 1808, 1809,
+ 1810, 1811, 1812, 1813, 1814, 1815, 1816, 1817, 1818, 1819, 1820, 1821, 1822, 1823, 1824, 1825,
+ 1826, 1827, 1828, 1829, 1830, 1831, 1832, 1833, 1834, 1835, 1836, 1837, 1838, 1839, 1840, 1841,
+ 1842, 1843, 1844, 1845, 1846, 1847, 1848, 1849, 1850, 1851, 1862, 1863, 1864, 1865, 1866, 1867,
+ 1868, 1869, 1870, 1871, 1872, 1873, 1874, 1875, 1876, 1877, 1878, 1879, 1880, 1881, 1882, 1883,
+ 1884, 1885, 1886, 1887, 1888, 1889, 1890, 1891, 1892, 1893, 1894, 1895, 1896, 1897, 1898, 1899,
+ 1900, 1901, 1902, 1903, 1904, 1905, 1906, 1907, 1908, 1909, 1910, 1911, 1912, 1913, 1914, 1915,
+ 1916, 1917, 1918, 1919, 1920, 1921, 1922, 1923, 1924, 1925, 1926, 1927, 1928, 1929, 1930, 1931,
+ 1932, 1933, 1934, 1935, 1936, 1937, 1938, 1939, 1940, 1941, 1942, 1943, 1944, 1945, 1946, 1947,
+ 1948, 1949, 1950, 1951, 1952, 1953, 1954, 1955, 1956, 1957, 1958, 1959, 1960, 1961, 1962, 1963,
+ 1964, 1866, 1965, 1867, 1966, 1868, 1967, 1869, 1968, 1870, 1969, 1871, 1970, 1872, 1971, 1873,
+ 1972, 1874, 1973, 1974, 1975, 1976, 1977, 1978, 1979, 1980, 1981, 1982, 1983, 1984, 1985, 1986,
+ 1987, 1988, 1989, 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002,
+ 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 1875, 2011, 1876, 2012, 1877, 2013, 1878, 2014,
+ 1879, 2015, 1880, 2016, 2017, 2018, 2019, 2020, 2021, 2022, 2023, 2024, 2025, 2026, 2027, 2028,
+ 2029, 2030, 2031, 2032, 2033, 2034, 2035, 2036, 2037, 2038, 2039, 2040, 2041, 2042, 2043, 2044,
+ 2045, 2046, 2047, 2048, 2049, 2050, 2051, 2052, 2053, 2054, 2055, 2056, 2057, 2058, 2059, 2060,
+ 2061, 2062, 2063, 2064, 2065, 2066, 2067, 2068, 2069, 2070, 2071, 2072, 2073, 2074, 2075, 2076,
+ 2077, 2078, 2079, 2080, 2081, 2082, 2083, 2084, 2085, 2086, 2087, 2088, 2089, 2090, 2091, 2092,
+ 2093, 2094, 2095, 2096, 2097, 2098, 2099, 2100, 2101, 2102, 2103, 2104, 2105, 2106, 2107, 2108,
+ 2109, 2110, 2111, 2112, 2113, 2114, 2115, 2116, 2117, 2118, 2119, 2120, 2121, 2122, 2123, 2124,
+ 2125, 2126, 2127, 2128, 2129, 2130, 2131, 2132, 2133, 2134, 2135, 2136, 2137, 2138, 2139, 2140,
+ 2141, 2142, 2143, 2144, 2145, 2146, 2147, 2148, 2149, 2150, 2151, 2152, 2153, 2154, 2155, 2156,
+ 2157, 2158, 2159, 2160, 2161, 2162, 2163, 2164, 2165, 2166, 2167, 2168, 2169, 2170, 2171, 2172,
+ 2173, 2174, 2175, 2176, 2177, 2178, 2179, 2180, 2181, 2182, 2183, 2184, 2185, 2186, 2187, 2188,
+ 2189, 2190, 2191, 2192, 2193, 2194, 2195, 2196, 2197, 2198, 2199, 2200, 2201, 2202, 2203, 2204,
+ 2205, 2206, 2207, 2208, 2209, 2210, 2211, 2212, 2213, 2214, 2215, 2216, 2217, 2218, 2219, 2220,
+ 2221, 2222, 2223, 2224, 2225, 2226, 2227, 2228, 2229, 2230, 2231, 2232, 2233, 2234, 2235, 2236,
+ 2237, 2238, 2239, 2240, 2241, 2242, 2243, 2244, 2245, 2246, 2247, 2248, 2249, 2250, 2251, 2252,
+ 2253, 2254, 2255, 2256, 2257, 2258, 2259, 2260, 2261, 2262, 2263, 2264, 2265, 2266, 2267, 2268,
+ 2269, 2270, 2271, 2272, 2273, 2274, 2275, 2276, 2277, 2278, 2279, 2280, 2281, 2282, 2283, 2284,
+ 2285, 2286, 2287, 2288, 2289, 2290, 2291, 2292, 2293, 2294, 2295, 2296, 2297, 2298, 2299, 2300,
+ 2301, 2302, 2303, 2304, 2305, 2306, 2307, 2308, 2309, 2310, 2311, 2312, 2313, 2314, 2315, 2316,
+ 2317, 2318, 2319, 2320, 2321, 2322, 2323, 2324, 2325, 2326, 2327, 2328, 2329, 2330, 2331, 2332,
+ 2333, 2334, 2335, 2336, 2337, 2338, 2339, 2340, 2341, 2342, 2343, 2344, 2345, 2346, 2347, 2348,
+ 2349, 2350, 2351, 2352, 2353, 2354, 2355, 2356, 2357, 2358, 2359, 2360, 2361, 2362, 2363, 2364,
+ 2365, 2366, 2367, 2368, 2369, 2370, 2371, 2372, 2373, 2374, 2375, 2376, 2377, 2378, 2379, 2380,
+ 2381, 2382, 2383, 2384, 2385, 2386, 2387, 2388, 2389, 2390, 2391, 2392, 2393, 2394, 2395, 2396,
+ 2397, 2398, 2399, 2400, 2401, 2402, 2403, 2404, 2405, 2406, 2407, 2408, 2409, 2410, 2411, 2412,
+ 2413, 2414, 2415, 2416, 2417, 2418, 2419, 2420, 2421, 2422, 2423, 2424, 2425, 2426, 2427, 2428,
+ 2429, 2430, 2431, 2432, 2433, 2434, 2435, 2436, 2437, 2438, 2439, 2440, 2441, 2442, 2443, 2444,
+ 2445, 2446, 2447, 2448, 2449, 2450, 2451, 2452, 2453, 2454, 2455, 2454, 2456, 2457, 2458, 2459,
+ 2460, 2461, 2462, 2463, 2464, 2465, 2466, 2467, 2468, 2469, 2470, 2471, 2472, 2473, 2474, 2475,
+ 2476, 2477, 2478, 2479, 2480, 2481, 2482, 2483, 2484, 2485, 2486, 2487, 2488, 2489, 2490, 2491,
+ 2492, 2493, 2494, 2495, 2496, 2497, 2498, 2499, 2500, 2501, 2502, 2503, 2504, 2505, 2506, 2507,
+ 2508, 2509, 2510, 2511, 2512, 2513, 2514, 2515, 2516, 2517, 2518, 2519, 2520, 2521, 2522, 2523,
+ 2524, 2525, 2526, 2527, 2528, 2529, 2530, 2531, 2532, 2533, 2534, 2535, 2536, 2537, 2538, 2539,
+ 2540, 2541, 2542, 2543, 2544, 2545, 2546, 2547, 2548, 2549, 2550, 2551, 2552, 2553, 2554,
+};
+
+static const AnimDef ANIMS[AN_COUNT] = {
+ {0, 11, 50, 0, 0}, /* IDLE1 */
+ {11, 11, 50, 10, 10}, /* ATTACK1 */
+ {22, 11, 50, 0, 0}, /* IDLE2 */
+ {33, 11, 50, 10, 10}, /* ATTACK2 */
+ {44, 11, 50, 0, 0}, /* IDLE3 */
+ {55, 11, 50, 10, 10}, /* ATTACK3 */
+ {66, 11, 50, 0, 0}, /* IDLE4 */
+ {77, 11, 50, 10, 10}, /* ATTACK4 */
+ {88, 11, 50, 0, 0}, /* IDLE5 */
+ {99, 11, 50, 10, 10}, /* ATTACK5 */
+ {110, 11, 50, 0, 0}, /* IDLE6 */
+ {121, 11, 50, 10, 10}, /* ATTACK6 */
+ {132, 11, 50, 0, 0}, /* IDLE7 */
+ {143, 11, 50, 10, 10}, /* ATTACK7 */
+ {154, 11, 50, 0, 0}, /* IDLE8 */
+ {165, 11, 50, 10, 10}, /* ATTACK8 */
+ {176, 11, 50, 0, 0}, /* IDLE9 */
+ {187, 11, 50, 10, 10}, /* ATTACK9 */
+ {198, 11, 50, 0, 0}, /* IDLE10 */
+ {209, 16, 50, 5, 15}, /* ATTACK10 */
+ {225, 11, 50, 0, 0}, /* IDLE11 */
+ {236, 11, 50, 10, 10}, /* ATTACK11 */
+ {247, 11, 50, 0, 0}, /* IDLE12 */
+ {258, 11, 50, 10, 10}, /* ATTACK12 */
+ {269, 10, 50, 0, 0}, /* IDLE13 */
+ {279, 11, 50, 10, 10}, /* ATTACK13 */
+ {290, 11, 50, 0, 0}, /* IDLE14 */
+ {301, 11, 50, 10, 10}, /* ATTACK14 */
+ {312, 12, 50, 0, 0}, /* IDLE15 */
+ {324, 11, 50, 10, 10}, /* ATTACK15 */
+ {335, 11, 50, 0, 0}, /* IDLE16 */
+ {346, 11, 50, 10, 10}, /* ATTACK16 */
+ {357, 10, 50, 0, 0}, /* IDLE17 */
+ {367, 11, 50, 10, 10}, /* ATTACK17 */
+ {378, 10, 50, 0, 0}, /* IDLE18 */
+ {388, 11, 50, 10, 10}, /* ATTACK18 */
+ {399, 10, 50, 0, 0}, /* IDLE19 */
+ {409, 11, 50, 10, 10}, /* ATTACK19 */
+ {420, 10, 50, 0, 0}, /* IDLE20 */
+ {430, 11, 50, 10, 10}, /* ATTACK20 */
+ {441, 10, 50, 0, 0}, /* IDLE21 */
+ {451, 11, 50, 10, 10}, /* ATTACK21 */
+ {462, 10, 50, 0, 0}, /* IDLE22 */
+ {472, 11, 50, 10, 10}, /* ATTACK22 */
+ {483, 10, 50, 0, 0}, /* IDLE23 */
+ {493, 11, 50, 10, 10}, /* ATTACK23 */
+ {504, 10, 50, 0, 0}, /* IDLE24 */
+ {514, 11, 50, 10, 10}, /* ATTACK24 */
+ {525, 11, 50, 0, 0}, /* IDLE25 */
+ {536, 11, 50, 10, 10}, /* ATTACK25 */
+ {547, 11, 50, 0, 0}, /* IDLE26 */
+ {558, 11, 50, 10, 10}, /* ATTACK26 */
+ {569, 11, 50, 0, 0}, /* IDLE27 */
+ {580, 12, 50, 10, 11}, /* ATTACK27 */
+ {592, 11, 50, 0, 0}, /* IDLE28 */
+ {603, 12, 50, 10, 11}, /* ATTACK28 */
+ {615, 10, 50, 0, 0}, /* IDLE29 */
+ {625, 11, 50, 10, 10}, /* ATTACK29 */
+ {636, 10, 50, 0, 0}, /* IDLE30 */
+ {646, 11, 50, 10, 10}, /* ATTACK30 */
+ {657, 10, 50, 0, 0}, /* IDLE31 */
+ {667, 11, 50, 10, 10}, /* ATTACK31 */
+ {678, 12, 50, 0, 0}, /* IDLE32 */
+ {690, 11, 50, 10, 10}, /* ATTACK32 */
+ {701, 12, 50, 0, 0}, /* IDLE33 */
+ {713, 11, 50, 10, 10}, /* ATTACK33 */
+ {724, 12, 50, 0, 0}, /* IDLE34 */
+ {736, 11, 50, 10, 10}, /* ATTACK34 */
+ {747, 11, 50, 0, 0}, /* IDLE35 */
+ {758, 11, 50, 10, 10}, /* ATTACK35 */
+ {769, 12, 50, 0, 0}, /* IDLE36 */
+ {781, 11, 50, 10, 10}, /* ATTACK36 */
+ {792, 12, 50, 0, 0}, /* IDLE37 */
+ {804, 11, 50, 10, 10}, /* ATTACK37 */
+ {815, 12, 50, 0, 0}, /* IDLE38 */
+ {827, 13, 50, 11, 12}, /* ATTACK38 */
+ {840, 10, 50, 0, 0}, /* IDLE39 */
+ {850, 11, 50, 10, 10}, /* ATTACK39 */
+ {861, 12, 50, 0, 0}, /* IDLE40 */
+ {873, 13, 50, 10, 12}, /* ATTACK40 */
+ {886, 11, 50, 0, 0}, /* IDLE41 */
+ {897, 12, 50, 10, 11}, /* ATTACK41 */
+ {909, 11, 50, 0, 0}, /* IDLE42 */
+ {920, 12, 50, 10, 11}, /* ATTACK42 */
+ {932, 10, 50, 0, 0}, /* IDLE43 */
+ {942, 10, 50, 10, 9}, /* ATTACK43 */
+ {952, 10, 50, 0, 0}, /* IDLE44 */
+ {962, 11, 50, 10, 10}, /* ATTACK44 */
+ {973, 10, 50, 0, 0}, /* IDLE45 */
+ {983, 10, 50, 10, 9}, /* ATTACK45 */
+ {993, 10, 50, 0, 0}, /* IDLE46 */
+ {1003, 11, 50, 10, 10}, /* ATTACK46 */
+ {1014, 10, 50, 0, 0}, /* IDLE47 */
+ {1024, 11, 50, 10, 10}, /* ATTACK47 */
+ {1035, 10, 50, 0, 0}, /* IDLE48 */
+ {1045, 11, 50, 10, 10}, /* ATTACK48 */
+ {1056, 1, 50, 0, 0}, /* KO */
+ {1057, 10, 50, 0, 0}, /* ENEMY0 */
+ {1067, 10, 50, 0, 0}, /* ENEMY12 */
+ {1077, 10, 50, 0, 0}, /* ENEMY13 */
+ {1087, 10, 50, 0, 0}, /* ENEMY14 */
+ {1097, 10, 50, 0, 0}, /* ENEMY15 */
+ {1107, 10, 50, 0, 0}, /* ENEMY16 */
+ {1117, 10, 50, 0, 0}, /* ENEMY17 */
+ {1127, 10, 50, 0, 0}, /* ENEMY18 */
+ {1137, 10, 50, 0, 0}, /* ENEMY19 */
+ {1147, 10, 50, 0, 0}, /* ENEMY20 */
+ {1157, 10, 50, 0, 0}, /* ENEMY21 */
+ {1167, 10, 50, 0, 0}, /* ENEMY22 */
+ {1177, 10, 50, 0, 0}, /* ENEMY23 */
+ {1187, 10, 50, 0, 0}, /* ENEMY24 */
+ {1197, 10, 50, 0, 0}, /* ENEMY25 */
+ {1207, 10, 50, 0, 0}, /* ENEMY26 */
+ {1217, 10, 50, 0, 0}, /* ENEMY27 */
+ {1227, 10, 50, 0, 0}, /* ENEMY28 */
+ {1237, 10, 50, 0, 0}, /* ENEMY29 */
+ {1247, 10, 50, 0, 0}, /* ENEMY30 */
+ {1257, 10, 50, 0, 0}, /* ENEMY31 */
+ {1267, 10, 50, 0, 0}, /* ENEMY32 */
+ {1277, 10, 50, 0, 0}, /* ENEMY33 */
+ {1287, 10, 50, 0, 0}, /* ENEMY34 */
+ {1297, 10, 50, 0, 0}, /* ENEMY35 */
+ {1307, 10, 50, 0, 0}, /* ENEMY36 */
+ {1317, 12, 50, 0, 0}, /* ENEMY37 */
+ {1329, 12, 50, 0, 0}, /* ENEMY38 */
+ {1341, 12, 50, 0, 0}, /* ENEMY39 */
+ {1353, 12, 50, 0, 0}, /* ENEMY40 */
+ {1365, 11, 50, 0, 0}, /* CHAL9 */
+ {1376, 11, 50, 0, 0}, /* CHAL10 */
+ {1387, 11, 50, 0, 0}, /* CHAL11 */
+ {1398, 11, 50, 0, 0}, /* CHAL12 */
+ {1409, 10, 50, 0, 0}, /* CHAL13 */
+ {1419, 11, 50, 0, 0}, /* CHAL14 */
+ {1430, 12, 50, 0, 0}, /* CHAL15 */
+ {1442, 11, 50, 0, 0}, /* CHAL16 */
+ {1453, 10, 50, 0, 0}, /* CHAL17 */
+ {1463, 10, 50, 0, 0}, /* CHAL18 */
+ {1473, 10, 50, 0, 0}, /* CHAL19 */
+ {1483, 10, 50, 0, 0}, /* CHAL20 */
+ {1493, 10, 50, 0, 0}, /* CHAL21 */
+ {1503, 10, 50, 0, 0}, /* CHAL22 */
+ {1513, 10, 50, 0, 0}, /* CHAL23 */
+ {1523, 10, 50, 0, 0}, /* CHAL24 */
+ {1533, 11, 50, 0, 0}, /* CHAL25 */
+ {1544, 11, 50, 0, 0}, /* CHAL26 */
+ {1555, 11, 50, 0, 0}, /* CHAL27 */
+ {1566, 11, 50, 0, 0}, /* CHAL28 */
+ {1577, 10, 50, 0, 0}, /* CHAL29 */
+ {1587, 10, 50, 0, 0}, /* CHAL30 */
+ {1597, 10, 50, 0, 0}, /* CHAL31 */
+ {1607, 12, 50, 0, 0}, /* CHAL32 */
+ {1619, 12, 50, 0, 0}, /* CHAL33 */
+ {1631, 12, 50, 0, 0}, /* CHAL34 */
+ {1643, 11, 50, 0, 0}, /* CHAL35 */
+ {1654, 12, 50, 0, 0}, /* CHAL36 */
+ {1666, 12, 50, 0, 0}, /* CHAL37 */
+ {1678, 12, 50, 0, 0}, /* CHAL38 */
+ {1690, 10, 50, 0, 0}, /* CHAL39 */
+ {1700, 12, 50, 0, 0}, /* CHAL40 */
+ {1712, 10, 50, 0, 0}, /* BOSS51 */
+ {1722, 10, 50, 0, 0}, /* BOSS52 */
+ {1732, 10, 40, 0, 0}, /* BOSS53 */
+ {1742, 10, 50, 0, 0}, /* BOSS54 */
+ {1752, 10, 50, 0, 0}, /* BOSS55 */
+ {1762, 10, 50, 0, 0}, /* BOSS56 */
+ {1772, 10, 40, 0, 0}, /* BOSS57 */
+ {1782, 10, 40, 0, 0}, /* BOSS58 */
+ {1792, 10, 50, 0, 0}, /* BOSS59 */
+ {1802, 10, 25, 0, 0}, /* BOSS60 */
+ {1812, 10, 25, 0, 0}, /* BOSS61 */
+ {1822, 10, 40, 0, 0}, /* BOSS62 */
+ {1832, 2, 5, 0, 0}, /* BOSS63 */
+ {1834, 4, 50, 1, 0}, /* HIT0 */
+ {1838, 5, 25, 1, 0}, /* HIT12 */
+ {1843, 4, 25, 1, 0}, /* HIT13 */
+ {1847, 6, 25, 1, 0}, /* HIT14 */
+ {1853, 6, 25, 1, 0}, /* HIT15 */
+ {1859, 6, 25, 1, 0}, /* HIT16 */
+ {1865, 6, 25, 1, 0}, /* HIT17 */
+ {1871, 6, 25, 1, 0}, /* HIT18 */
+ {1877, 6, 25, 1, 0}, /* HIT19 */
+ {1883, 11, 50, 1, 0}, /* HIT20 */
+ {1894, 11, 50, 1, 0}, /* HIT21 */
+ {1905, 9, 50, 0, 0}, /* SPARK */
+ {1914, 11, 50, 0, 0}, /* MICSPIN */
+ {1925, 6, 50, 0, 0}, /* PIZZA */
+ {1931, 6, 50, 0, 0}, /* PIZZA2 */
+ {1937, 9, 50, 2, 8}, /* BITE */
+ {1946, 9, 50, 1, 0}, /* BITE2 */
+ {1955, 9, 50, 1, 0}, /* BITE3 */
+ {1964, 9, 50, 1, 0}, /* MEGABITE */
+ {1973, 9, 50, 1, 0}, /* BITE4 */
+ {1982, 9, 50, 1, 0}, /* TOXICBITE */
+ {1991, 13, 100, 1, 0}, /* HOOK */
+ {2004, 11, 100, 0, 0}, /* SCARE */
+ {2015, 13, 50, 0, 0}, /* NOTE */
+ {2028, 13, 50, 0, 0}, /* NOTE2 */
+ {2041, 13, 50, 0, 0}, /* TORNADO */
+ {2054, 1, 50, 1, 0}, /* CLAW */
+ {2055, 1, 50, 0, 0}, /* CLAW2 */
+ {2056, 11, 50, 0, 0}, /* DIZZY */
+ {2067, 6, 25, 1, 0}, /* BROKEN */
+ {2073, 21, 35, 1, 0}, /* POW */
+ {2094, 5, 50, 0, 0}, /* STAR */
+ {2099, 11, 50, 0, 0}, /* CLOUD */
+ {2110, 9, 50, 1, 8}, /* PRIZE */
+ {2119, 9, 50, 1, 0}, /* PRIZE2 */
+ {2128, 6, 100, 0, 0}, /* POPPER */
+ {2134, 9, 50, 0, 0}, /* MUNCHIE */
+ {2143, 13, 50, 1, 0}, /* MUNCHIE2 */
+ {2156, 1, 50, 1, 0}, /* HEAD */
+ {2157, 7, 75, 0, 0}, /* FREDDLE */
+ {2164, 6, 50, 0, 0}, /* BADPIZZA */
+ {2170, 11, 30, 0, 0}, /* ENDO */
+ {2181, 5, 50, 1, 0}, /* ENDO2 */
+ {2186, 6, 99, 0, 0}, /* DAGGER */
+ {2192, 5, 90, 0, 0}, /* SAW */
+ {2197, 11, 50, 0, 0}, /* JACKO */
+ {2208, 12, 50, 1, 0}, /* ANTI */
+ {2220, 1, 50, 1, 0}, /* GIFT */
+ {2221, 11, 50, 0, 0}, /* MIMIC */
+ {2232, 6, 100, 0, 0}, /* MIMIC2 */
+ {2238, 21, 50, 0, 0}, /* SCREW */
+ {2259, 10, 50, 0, 0}, /* DRIP */
+ {2269, 13, 50, 0, 0}, /* BADNOTE */
+ {2282, 10, 50, 0, 0}, /* SYTH */
+ {2292, 1, 50, 1, 0}, /* STINGER */
+ {2293, 11, 90, 0, 0}, /* PBUBBLE */
+ {2304, 8, 50, 0, 0}, /* SPARKLE */
+ {2312, 12, 50, 0, 0}, /* VICTORY */
+ {2324, 12, 50, 0, 0}, /* LEVELUP */
+ {2336, 2, 50, 0, 0}, /* RUN */
+ {2338, 11, 50, 0, 0}, /* CHALLENGER */
+ {2349, 11, 75, 0, 0}, /* NEWMEMBER */
+ {2360, 1, 50, 1, 0}, /* WALL */
+ {2361, 1, 50, 1, 0}, /* BUBBLE */
+ {2362, 11, 25, 0, 10}, /* DOWN */
+ {2373, 11, 25, 0, 10}, /* DOWN2 */
+ {2384, 11, 25, 0, 10}, /* DOWN3 */
+ {2395, 7, 25, 0, 0}, /* BALLOON0 */
+ {2402, 7, 50, 0, 0}, /* BALLOON1 */
+ {2409, 7, 50, 0, 0}, /* BALLOON2 */
+ {2416, 7, 50, 0, 0}, /* BALLOON3 */
+ {2423, 3, 100, 0, 0}, /* WATER */
+ {2426, 3, 90, 0, 0}, /* WATER2 */
+ {2429, 11, 50, 1, 0}, /* PUDDLE */
+ {2440, 4, 50, 0, 0}, /* SHIELD */
+ {2444, 1, 50, 0, 0}, /* SPECIAL0 */
+ {2445, 1, 50, 0, 0}, /* SPECIAL12 */
+ {2446, 1, 50, 0, 0}, /* SPECIAL13 */
+ {2447, 1, 50, 0, 0}, /* SPECIAL14 */
+ {2448, 1, 50, 0, 0}, /* SPECIAL15 */
+ {2449, 1, 50, 0, 0}, /* SPECIAL16 */
+ {2450, 1, 50, 0, 0}, /* SPECIAL17 */
+ {2451, 1, 50, 0, 0}, /* SPECIAL18 */
+ {2452, 1, 50, 0, 0}, /* SPECIAL19 */
+ {2453, 1, 50, 0, 0}, /* SPECIAL20 */
+ {2454, 1, 50, 0, 0}, /* SPECIAL21 */
+ {2455, 3, 100, 0, 0}, /* BYTE1 */
+ {2458, 3, 99, 0, 0}, /* BYTE2 */
+ {2461, 3, 99, 0, 0}, /* BYTE3 */
+ {2464, 3, 50, 0, 0}, /* BYTE4 */
+ {2467, 3, 50, 0, 0}, /* BYTE5 */
+ {2470, 3, 50, 0, 0}, /* BYTE6 */
+ {2473, 5, 25, 0, 0}, /* BYTE7 */
+ {2478, 5, 50, 0, 0}, /* BYTE8 */
+ {2483, 5, 25, 0, 0}, /* BYTE9 */
+ {2488, 4, 50, 0, 0}, /* BYTE10 */
+ {2492, 4, 50, 0, 0}, /* BYTE11 */
+ {2496, 4, 50, 0, 0}, /* BYTE12 */
+ {2500, 5, 50, 0, 0}, /* BYTE13 */
+ {2505, 5, 50, 0, 0}, /* BYTE14 */
+ {2510, 5, 50, 0, 0}, /* BYTE15 */
+ {2515, 4, 50, 0, 0}, /* BYTE16 */
+ {2519, 4, 50, 0, 0}, /* BYTE17 */
+ {2523, 5, 50, 0, 0}, /* BYTE18 */
+ {2528, 5, 25, 0, 0}, /* BYTE19 */
+ {2533, 5, 25, 0, 0}, /* BYTE20 */
+ {2538, 5, 25, 0, 0}, /* BYTE21 */
+};
+
+#endif
diff --git a/games/fnafworld/src/battle.c b/games/fnafworld/src/battle.c
new file mode 100644
index 00000000..af1d1261
--- /dev/null
+++ b/games/fnafworld/src/battle.c
@@ -0,0 +1,1562 @@
+/* FNAF World: a battle, as the overworld frame's events run it (their numbers in the comments), 60 steps a second.
+ *
+ * The party: two rows of four ("load row"), each member's charge fills a point a second (0.7 s with a speed boost)
+ * while nobody else in the row is full; a full member shows its three attacks. The enemies ("target") fill their own
+ * speed and hit a random member. Positions are the game's (its battle is the 800 x 480 view from 23, 14), drawn at
+ * 0.4. */
+#include <string.h>
+#include "anims.h"
+#include "data.h"
+#include "game.h"
+#include "gfx.h"
+
+#define B g.b
+#define VIEW_X 23
+#define VIEW_Y 14
+#define SX(x) (((x) - VIEW_X) * 2 / 5)
+#define SY(y) (((y) - VIEW_Y) * 2 / 5)
+#define FIELD_H 192
+
+/* ------------------------------------------------------------------ the game's paths (their nodes: dx, dy) */
+static const int8_t PATH_IN[39][2] = { /* "character" movement 1: the hop in */
+ {-6, -19}, {-1, -1}, {-5, -7}, {-4, -6}, {-12, -16}, {-10, -10}, {-11, -8}, {-8, -8}, {-14, -9}, {-17, -7},
+ {-16, -6}, {-17, -6}, {-19, -4}, {-16, -3}, {-19, -1}, {-18, 0}, {-21, 3}, {-19, 4}, {-18, 5}, {-15, 4}, {-19, 5},
+ {-14, 3}, {-15, 5}, {-13, 6}, {-14, 6}, {-5, 5}, {-10, 7}, {-7, 7}, {-10, 7}, {0, 1}, {-5, 6}, {-2, 2}, {-2, 2},
+ {-3, 6}, {-1, 1}, {-2, 2}, {-3, 5}, {-3, 3}, {0, 1}};
+static const int8_t ENEMY_IN[27][2] = { /* "target" movement 1 */
+ {-1, -3}, {0, -2}, {9, -22}, {6, -16}, {21, -31}, {19, -23}, {24, -18}, {27, -13}, {23, -6}, {34, 1}, {22, 6},
+ {11, 4}, {24, 12}, {19, 12}, {17, 14}, {6, 8}, {16, 24}, {6, 12}, {5, 13}, {4, 11}, {0, 1}, {0, 1}, {1, 4}, {1, 3},
+ {0, 3}, {0, 1}, {0, 1}};
+static const int8_t ENEMY_LUNGE[12][2] = { /* "target" movement 2 ("Movement" 1), back at its end */
+ {0, -6}, {0, -1}, {6, -5}, {8, -7}, {14, -8}, {15, -3}, {16, -1}, {18, 2}, {16, 6}, {11, 8}, {8, 7}, {5, 9}};
+/* where they come from: "make character" 1-4, "spawn enemy" 1-4 */
+static const int16_t MAKE[4][2] = {{991, 291}, {1104, 363}, {931, 423}, {1057, 501}};
+static const int16_t SPAWN[4][2] = {{-80, 279}, {-173, 352}, {26, 340}, {-64, 430}};
+static const int16_t STOP[4][2] = {{623, 263}, {737, 339}, {549, 399}, {677, 476}}; /* "stop spot" 1-4 */
+#define PATH_STEP 12 /* (a path's speed 100: about 12 pixels a frame) */
+
+/* ------------------------------------------------------------------ time */
+/* the game's "every N ms": each its own timer (T_*), the clock in thirds of a millisecond (50 a step) */
+enum {
+ T_CHARGE, T_CHARGE_FAST, T_SPEED, T_SPEED_SLOW, T_ENEMY_GO, T_WHO, T_STRENGTH, T_SECOND, T_SPECIAL, T_ROLL,
+ T_SCREW, T_CHEESE, T_4000, T_CONFUSE, T_5000, T_POISON, T_COMET, T_PFURY, T_FURY, T_PIZZA, T_PIZZA2, T_FREDDLE,
+ T_STARS, T_DRIP, T_PUDDLE, T_POPPER, T_CLOUDS, T_FAVORS, T_MYSTERY, T_HOCUS, T_VIRUS, T_UNSCREW, T_LAVA, T_EXP,
+ T_TOKENS, T_RUN, T_COUNT
+};
+static uint32_t ms3; /* the battle's clock */
+static bool every(int id, int ms) {
+ if (!B.timers[id]) { /* (the first after a whole period) */
+ B.timers[id] = ms3 + (uint32_t)ms * 3;
+ return false;
+ }
+ if (ms3 < B.timers[id]) return false;
+ B.timers[id] += (uint32_t)ms * 3;
+ if (B.timers[id] <= ms3) B.timers[id] = ms3 + (uint32_t)ms * 3;
+ return true;
+}
+/* each byte has its own timer */
+static uint32_t byte_t[4];
+static bool byte_every(int k, int ms) {
+ if (ms3 < byte_t[k]) return false;
+ byte_t[k] = ms3 + (uint32_t)ms * 3;
+ return true;
+}
+
+/* ------------------------------------------------------------------ helpers */
+static int field_char(int k) { return g.f.slot[(B.row - 1) * 4 + k]; } /* the member in field place k (0-3) */
+static int32_t *life_of(int k) { return &B.life[(B.row - 1) * 4 + k]; }
+static int enemies_alive(void) {
+ int n = 0;
+ for (int i = 0; i < 4; i++) n += B.en[i].alive;
+ return n;
+}
+static int pick_enemy(void) { /* Clickteam's "pick one at random" */
+ int n = enemies_alive();
+ if (!n) return -1;
+ int k = rnd_n(n);
+ for (int i = 0; i < 4; i++)
+ if (B.en[i].alive && k-- == 0) return i;
+ return -1;
+}
+static int32_t max_life(void) { return B.boss ? B.boss_life : B.enemy_max; }
+static int level_of(int k) { return g.f.lv[field_char(k)]; }
+
+static Fx *fx_new(int kind, int an, int x, int y) {
+ for (int i = 0; i < NFX; i++)
+ if (!B.fx[i].kind) {
+ Fx *f = &B.fx[i];
+ memset(f, 0, sizeof *f);
+ f->kind = (uint8_t)kind, f->an = (uint8_t)an, f->x = (int16_t)x, f->y = (int16_t)y, f->target = -1;
+ f->plays = ANIMS[an].plays;
+ return f;
+ }
+ return NULL;
+}
+/* an animation's step: its speed counter; true when it ends (it plays a set number of times) */
+static bool anim_step(uint8_t an, uint8_t *img, uint8_t *cnt, uint8_t *plays) {
+ const AnimDef *a = &ANIMS[an];
+ int c = *cnt + a->speed;
+ bool end = false;
+ while (c >= 100) {
+ c -= 100;
+ if (*img + 1 < a->n) (*img)++;
+ else if (a->plays == 0) *img = a->back;
+ else if (*plays > 1) (*plays)--, *img = a->back;
+ else end = true;
+ }
+ *cnt = (uint8_t)c;
+ return end;
+}
+static int pic_of(int an, int img) { return ANIM_PICS[ANIMS[an].first + (img < ANIMS[an].n ? img : ANIMS[an].n - 1)]; }
+
+/* floating numbers: a hit (white), a heal (green), a member's hurt (red) */
+enum { NUM_HIT, NUM_HEAL, NUM_HURT };
+static struct { int16_t x, y, t; int32_t v; uint8_t kind; } nums[12];
+static void number(int x, int y, int32_t v, int kind) {
+ int best = 0;
+ for (int i = 0; i < 12; i++)
+ if (nums[i].t <= 0 || nums[i].t < nums[best].t) best = i;
+ nums[best].x = (int16_t)x, nums[best].y = (int16_t)y, nums[best].v = v, nums[best].t = 60, nums[best].kind = (uint8_t)kind;
+}
+
+static void sparks(int x, int y) {
+ for (int k = 0; k < 3; k++) {
+ Fx *f = fx_new(1, AN_SPARK, x + rnd_n(60) - 30, y + rnd_n(50) - 40);
+ if (f) f->vy = (int16_t)(16 + rnd_n(32)), f->img = (uint8_t)rnd_n(4);
+ }
+}
+
+/* ------------------------------------------------------------------ effects (FX_*: their behaviour) */
+enum {
+ FX_NONE, FX_SPARK, FX_SHOW, /* a picture that plays once where it is */
+ FX_MIC, FX_PIZZA, FX_BITE, FX_HOOK, FX_CLAW, FX_TORNADO, FX_BALLOON, FX_HEAD, FX_TOXICBITE, FX_TBALLOON,
+ FX_BADPIZZA, FX_GLOOM, FX_CLOUD, FX_RAIN, FX_STAR, FX_DRIP, FX_PUDDLE, FX_MUNCHIE, FX_FREDDLE, FX_POPPER,
+ FX_PRIZE, FX_HAUNT, FX_ENDO, FX_DAGGER, FX_WALL, FX_JACKO, FX_SAW, FX_ENEMY_BALLOON, FX_STINGER, FX_SYTH,
+ FX_LASER, FX_NOTE, FX_SCREW, FX_HIT
+};
+
+/* ------------------------------------------------------------------ the start */
+static void party_enter(void) {
+ for (int k = 0; k < 4; k++) {
+ B.pm[k].x = MAKE[k][0], B.pm[k].y = MAKE[k][1];
+ B.pm[k].state = 1, B.pm[k].node = 0, B.pm[k].t = (int16_t)(5 * k); /* (made 5 frames apart: 22-29) */
+ B.pm[k].img = 0, B.pm[k].cnt = 0;
+ }
+ B.moving = 1;
+}
+
+static int enemy_an(int type, int alt) {
+ static const uint8_t A[30] = {0, 0, 12, 14, 16, 20, 15, 18, 25, 30, 29, 28, 23, 21, 24, 17, 22, 13, 19, 26, 27, 31,
+ 32, 33, 13, 33, 15, 35, 36, 37};
+ int a;
+ if (type >= 51) a = 38 + (type - 51);
+ else if (alt && type == 24) a = 14;
+ else if (alt && type == 25) a = 12;
+ else if (alt && type == 26) a = 17;
+ else a = A[type < 30 ? type : 1];
+ return a == 0 ? AN_ENEMY0 : AN_ENEMY12 + (a - 12);
+}
+
+void battle_start(int boss) {
+ World *w = &g.w;
+ memset(&B, 0, sizeof B);
+ memset(nums, 0, sizeof nums);
+ ms3 = 0;
+ for (int k = 0; k < 4; k++) byte_t[k] = 0;
+ B.on = 1, B.boss = (uint8_t)boss, B.row = 1, B.stage = 1, B.ready_turn = 1;
+ int area = w->area, diff = g.f.diff ? g.f.diff : 1;
+ B.etype = (uint8_t)(area == 50 ? 51 + rnd_n(3) : area + rnd_n(3) + 1); /* 939 */
+ B.chal_roll = (uint8_t)(rnd_n(5) + 1); /* 940 */
+ for (int c = 0; c < 4; c++)
+ if (g.f.chip[c] == 14) B.chal_roll = 1; /* 942: Find: Characters */
+ for (int k = 0; k < 8; k++) {
+ int c = g.f.slot[k];
+ B.life_max[k] = B.life[k] = life_max(c, g.f.lv[c]); /* 1017 */
+ B.charge[k] = (uint8_t)(rnd_n(5) + 5); /* 107 */
+ }
+ /* the enemies (943-948) */
+ if (g.w.note == 99) { /* (a challenger, after the banner: 1202) */
+ g.w.note = 0;
+ }
+ if (B.chal || boss) B.count = 1;
+ else B.count = (uint8_t)(rnd_n(4) + 1);
+ for (int i = 0; i < B.count; i++) {
+ Enemy *e = &B.en[i];
+ e->alive = 1;
+ e->x = SPAWN[i][0], e->y = (int16_t)(SPAWN[i][1] + (B.count == 1 && (B.chal || boss) ? 43 : 0));
+ e->path = 1, e->node = 0;
+ e->speed = (int16_t)(boss ? 1 : rnd_n(75)); /* 1007-1008 */
+ e->an = (uint8_t)enemy_an(B.etype, B.etype >= 24 && B.etype <= 26 && rnd_n(3) == 1);
+ e->img = (uint8_t)rnd_n(ANIMS[e->an].n);
+ }
+ B.enemy_max = enemy_life(B.etype, diff);
+ B.special = (uint8_t)enemy_special(B.etype);
+ if (boss) {
+ int sp, an;
+ boss_info(boss, diff, &B.boss_life, &B.boss_speed, &B.boss_strength, &sp, &an);
+ B.special = (uint8_t)sp;
+ B.en[0].an = (uint8_t)(AN_BOSS51 + (an - 51));
+ }
+ party_enter();
+ /* the chips worn (1505-1540): applied as the game cycles through them in its first second */
+ for (int c = 0; c < 4; c++) {
+ switch (g.f.chip[c]) {
+ case 1: B.def_boost = 15; break;
+ case 2: B.atk_boost = 15; break;
+ case 3: B.spd_boost = 15; break;
+ case 4: B.comet = B.comet > 1 ? B.comet : 1; break;
+ case 5:
+ for (int k = 0; k < 8; k++) B.charge[k] = (uint8_t)(7 + rnd_n(2));
+ B.quick_t = 200;
+ break;
+ case 6: B.block_confuse = 1; break;
+ case 7: B.run_luck = 1; break;
+ case 11: B.comet = 3; break;
+ case 12: for (int k = 0; k < 4; k++) B.gift[k] = 100; break;
+ case 13: B.regen = 120; break;
+ case 15: B.pwr_down = B.spd_down = B.spd_down2 = 45; break;
+ case 16: B.freddle_fury = 1; break;
+ case 17: B.shield = 30; break;
+ case 18: B.mimic = 30; B.mimic_attack = 49; break;
+ case 19: B.counter_bite = 1; break;
+ case 20: B.pizza_fury = 1; break;
+ case 21: B.block_unscrew = 1; break;
+ }
+ }
+ B.attacked_who = 1;
+ B.team_ok[0] = B.team_ok[1] = 1;
+ memcpy(B.slots, g.f.slot, 8);
+ w->grace = 500; /* 1195 */
+ world_save_pos();
+}
+
+/* a challenger after a won battle (1198, 1202): its own battle */
+void battle_challenger(int c) {
+ battle_start(0);
+ B.chal = 2, B.chal_c = (uint8_t)c;
+ B.count = 1;
+ memset(&B.en[1], 0, sizeof B.en[1] * 3);
+ Enemy *e = &B.en[0];
+ e->y = SPAWN[0][1] + 43;
+ e->an = (uint8_t)(AN_CHAL9 + (c - 9));
+ e->img = 0;
+ B.enemy_max = challenger_life(c, g.f.diff); /* 1004 */
+ /* 1205-1236: its special */
+ static const uint8_t SP[41] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 2, 3, 2, 7, 6, 3, 0, 5, 4, 3, 5, 7, 7, 0, 0, 0,
+ 0, 8, 4, 0, 0, 6, 8, 0, 0, 0, 0, 0, 0, 0};
+ B.special = c <= 40 ? SP[c] : 0;
+}
+
+/* ------------------------------------------------------------------ hits */
+static void hit_enemy(int i, int32_t d) { /* "target" A = d (the game sets it; 479 takes it) */
+ if (i >= 0 && i < 4 && B.en[i].alive && d > 0) B.en[i].dmg = d;
+}
+static void hit_all(int32_t base, int r) { /* each its own roll */
+ for (int i = 0; i < 4; i++)
+ if (B.en[i].alive) hit_enemy(i, base + rnd_n(r));
+}
+static void kill_enemy(int i) { /* 741, 827: "broken", the flash */
+ Enemy *e = &B.en[i];
+ if (!e->alive) return;
+ e->alive = 0;
+ B.flash = 200;
+ Fx *f = fx_new(FX_SHOW, AN_BROKEN, e->x, e->y - 96);
+ (void)f;
+ if (B.boss) {
+ fx_new(FX_SHOW, AN_POW, e->x, e->y - 100);
+ B.shake = 10;
+ }
+}
+
+static void apply_hits(void) { /* 479: each target's A taken from its life */
+ for (int i = 0; i < 4; i++) {
+ Enemy *e = &B.en[i];
+ if (!e->alive || e->dmg <= 0) continue;
+ e->hurt -= e->dmg;
+ e->s5 = 20;
+ B.shake = 10;
+ number(e->x + 25, e->y - 67, e->dmg, NUM_HIT);
+ sparks(e->x, e->y - 100);
+ B.flash = 100;
+ e->dmg = 0;
+ }
+ for (int i = 0; i < 4; i++) { /* 960-962: out of life */
+ Enemy *e = &B.en[i];
+ if (e->alive && e->hurt < -max_life() && !e->s17) {
+ e->s17 = 1, e->s25 = 1;
+ if (B.boss == 19) g.f.resetpos = 1;
+ }
+ /* 740-741: the roll of an instant end (Esc Key, Unscrew) or the end of its life */
+ if (e->alive && e->s25 > 0) {
+ int r = e->s25;
+ e->s25 = 0;
+ if (r <= 10) kill_enemy(i);
+ else fx_new(FX_SHOW, AN_SPARK, e->x - 54, e->y - 92);
+ }
+ }
+}
+
+static void party_hit(int k, int32_t d) { /* "damage p N" (1025-1037), k 0-3 */
+ if (d <= 0 || B.shield2 > 0) return;
+ int32_t *l = life_of(k);
+ if (*l <= 0) return;
+ *l -= d;
+ if (*l < 0) *l = 0;
+ number(STOP[k][0], STOP[k][1] - 125, d, NUM_HURT);
+ B.pm[k].t = 30; /* "character" F: blinks */
+ B.shake = 10, B.flash = 100;
+ B.hit_slot = (uint8_t)k;
+ if (B.counter_bite) { /* 1536: Counter: Bite */
+ int t = pick_enemy();
+ if (t >= 0) {
+ Fx *f = fx_new(FX_BITE, AN_BITE2, B.en[t].x - 6, B.en[t].y - 85);
+ if (f) f->target = (int8_t)t, f->a = (int16_t)(200 + B.cur_level * B.multiplier), f->b = 50;
+ }
+ }
+}
+
+static void party_heal(int32_t amount) { /* "healed amount" -> "heal p 1" to 4 (632, 594-597) */
+ for (int k = 0; k < 4; k++) {
+ int32_t *l = life_of(k);
+ if (*l <= 0) continue;
+ int32_t h = amount + rnd_n(5);
+ *l += h;
+ int32_t m = B.life_max[(B.row - 1) * 4 + k];
+ if (*l > m) *l = m;
+ number(STOP[k][0] - 44, STOP[k][1] - 102, h, NUM_HEAL);
+ }
+}
+
+/* ------------------------------------------------------------------ the attacks (467-476, 600-608, 659-675, 844-908,
+ * 2041-2049): what each does at its picture */
+static int attack_frame(int a) {
+ switch (a) {
+ case 6: case 7: case 43: return 1;
+ case 8: return 2;
+ case 32: return 3;
+ case 3: case 4: case 11: case 13: case 15: return 8;
+ case 9: case 17: case 21: case 22: case 23: case 24: case 25: case 31: case 35: case 36: case 37: case 38:
+ case 39: case 40: case 41: case 42: return 7;
+ default: return 6;
+ }
+}
+
+static void do_attack(int a) {
+ int power = B.cur_level * B.multiplier; /* 587: "current attack power" */
+ int level = B.cur_level;
+ int att_x = B.pm[B.att_slot - 1].x, att_y = B.pm[B.att_slot - 1].y;
+ int t;
+ Fx *f;
+ switch (a) {
+ case 1: /* Mic Toss: the mic flies to a target (478) */
+ t = pick_enemy();
+ if (t >= 0 && (f = fx_new(FX_MIC, AN_MICSPIN, att_x, att_y - 71))) f->target = (int8_t)t, f->a = (int16_t)power;
+ break;
+ case 2: case 5: case 19: case 51: /* Bite, Bite 2, Toxic Bite 2, Mega Bite (468, 844-851) */
+ t = pick_enemy();
+ if (t < 0) break;
+ f = fx_new(FX_BITE, a == 2 ? AN_BITE : a == 5 ? AN_BITE2 : a == 19 ? AN_BITE3 : AN_MEGABITE, B.en[t].x, B.en[t].y - 83);
+ if (!f) break;
+ f->target = (int8_t)t;
+ f->a = (int16_t)(a == 2 ? 20 + power : a == 5 ? 200 + power : a == 19 ? 150 + power : 300 + power * 2);
+ f->b = (int16_t)(a == 2 ? 5 : a == 51 ? 100 : 50);
+ if (a == 19) f->t = 1; /* (poisons) */
+ B.shake = a == 51 ? 50 : 10;
+ break;
+ case 16: /* Toxic Bite (469, 558) */
+ t = pick_enemy();
+ if (t >= 0 && (f = fx_new(FX_TOXICBITE, AN_TOXICBITE, B.en[t].x, B.en[t].y - 71))) f->target = (int8_t)t;
+ break;
+ case 3: /* Hook (603, 634) */
+ t = pick_enemy();
+ if (t >= 0 && (f = fx_new(FX_HOOK, AN_HOOK, B.en[t].x, B.en[t].y - 72))) f->target = (int8_t)t, f->a = (int16_t)power;
+ break;
+ case 4: /* Eye Beam: the beam over them all (604, 635) */
+ if ((f = fx_new(FX_CLAW, AN_CLAW, att_x - 47, att_y - 156))) f->a = (int16_t)(power * 2);
+ break;
+ case 6: case 43: /* Pizza Wheel, Pizza Wheel 2 (470, 471) */
+ if (a == 6) B.pizzas = (int16_t)(3 + rnd_n(4)), B.pizza_pow = (int16_t)power;
+ else B.pizzas2 = (int16_t)(3 + rnd_n(4)), B.pizza2_pow = (int16_t)(power + 20);
+ B.shake = 100;
+ break;
+ case 7: /* Bash Jam (472, 562) */
+ if ((f = fx_new(FX_TORNADO, AN_TORNADO, 379 + 335, 319 + 189))) f->a = (int16_t)(power + rnd_n(20));
+ B.shake = 100;
+ break;
+ case 8: /* Jumpscare (605-606) */
+ B.stunned = (int16_t)(B.boss ? 1 + rnd_n(3) : 2 + rnd_n(7));
+ B.shake = 50;
+ for (int i = 0; i < 4; i++)
+ if (B.en[i].alive) fx_new(FX_SHOW, AN_SCARE, B.en[i].x, B.en[i].y - 177);
+ break;
+ case 9: /* Balloons (664) */
+ for (int k = 0; k < 3; k++)
+ if ((f = fx_new(FX_BALLOON, AN_BALLOON0, att_x - 48, att_y - 186))) {
+ f->b = (int16_t)rnd_n(4), f->an = (uint8_t)(AN_BALLOON0 + f->b), f->a = (int16_t)power;
+ f->vx = (int16_t)(-20 - rnd_n(40)), f->vy = (int16_t)(-60 - rnd_n(40));
+ }
+ break;
+ case 10: /* Springlocks (899, 905) */
+ t = pick_enemy();
+ if (t >= 0 && (f = fx_new(FX_HEAD, AN_HEAD, B.en[t].x, B.en[t].y - 113))) f->target = (int8_t)t, f->a = (int16_t)power;
+ break;
+ case 11: /* Cupcake (600, 617) */
+ B.cup_t = 100, B.cup_level = (int16_t)level;
+ for (int k = 0; k < 4; k++) fx_new(FX_SHOW, AN_SPARKLE, STOP[k][0], STOP[k][1] - 100);
+ break;
+ case 12: case 14: /* Happy Jam, Happy Jam 2 (473, 857, 590) */
+ B.hj_t = 60, B.hj_level = (int16_t)(a == 12 ? level : level + 75), B.hj_kind = (int16_t)(a == 12 ? 1 : 2);
+ break;
+ case 13: /* Party Favors (601, 623) */
+ B.favors_t = 15, B.favors_level = (int16_t)level;
+ break;
+ case 15: /* Regen Song (602, 630) */
+ B.regen_n = 10;
+ for (int k = 0; k < 4; k++) fx_new(FX_NOTE, AN_NOTE, STOP[k][0], STOP[k][1] - 120);
+ break;
+ case 17: /* Toxic Balloon (665, 715) */
+ if ((f = fx_new(FX_TBALLOON, AN_BALLOON2, att_x - 57, att_y - 144))) f->vx = -30, f->vy = -60;
+ break;
+ case 20: /* Bad Pizza (847, 856) */
+ if ((f = fx_new(FX_BADPIZZA, AN_BADPIZZA, 215 + 200, 7 + 200))) f->a = (int16_t)power;
+ B.shake = 100;
+ break;
+ case 21: /* Gloom Balloon (666, 784) */
+ if ((f = fx_new(FX_GLOOM, AN_BALLOON3, att_x - 58, att_y - 109))) f->vx = -40, f->vy = -40;
+ break;
+ case 22: /* Gloom Song (669, 748) */
+ B.pwr_cloud_t = 20;
+ for (int k = 0; k < 3; k++) fx_new(FX_NOTE, AN_BADNOTE, att_x - 62 - 30 * k, att_y - 142);
+ B.shake = 50;
+ break;
+ case 23: /* Sludge (670) */
+ B.spd_down = 30;
+ for (int i = 0; i < 4; i++)
+ if (B.en[i].alive) fx_new(FX_SHOW, AN_DRIP, B.en[i].x, B.en[i].y - 60);
+ break;
+ case 24: case 25: /* Rainy Day, Rainy Day 2 (671-672, 793-794, 821) */
+ B.pwr_cloud = 2, B.pwr_cloud_t = (int16_t)(a == 24 ? 30 : 60);
+ fx_new(FX_CLOUD, AN_CLOUD, 214 + 120, 155);
+ B.stars2 = (int16_t)(a == 25 ? 1 : 0);
+ break;
+ case 26: /* Birthday (474) */
+ B.atk_boost += 10, B.def_boost += 10, B.spd_boost += 10;
+ break;
+ case 27: B.atk_boost = 60, B.shake = 100; break; /* Power Song (858) */
+ case 28: B.def_boost = 60; break; /* Armor Song (848) */
+ case 29: B.spd_boost = 60; break; /* Speed Song (659) */
+ case 30: /* Cosmic Song (866, 873-874) */
+ B.stars = (int16_t)(7 + rnd_n(5)), B.star_pow = (int16_t)power;
+ B.shake = 100;
+ break;
+ case 31: case 35: /* Hot Cheese (607, 608, 644-649) */
+ B.cheese_pow = (int16_t)(a == 31 ? level + 2 : level + 50);
+ B.cheese_t = (int16_t)(a == 31 ? 3 : 7);
+ break;
+ case 32: /* Munchies (661, 683-687) */
+ for (int i = 0; i < 4; i++)
+ if (B.en[i].alive) B.en[i].s12 = 1;
+ B.pizza_pow = (int16_t)power;
+ break;
+ case 33: /* Freddles (906, 909-918) */
+ B.freddles = (int16_t)(5 + rnd_n(10)), B.freddle_pow = (int16_t)power;
+ B.shake = 100;
+ break;
+ case 34: /* Poppers (660, 676-681) */
+ B.popper_n = (int16_t)(3 + rnd_n(6)), B.popper_pow = (int16_t)(power + 50 + rnd_n(50));
+ break;
+ case 36: case 37: /* Prize Ball, Prize Ball 2 (662-663, 690-704, 815-825) */
+ if ((f = fx_new(FX_PRIZE, a == 36 ? AN_PRIZE : AN_PRIZE2, 273 + 3, 82 - 97 + 150))) f->b = (int16_t)(a == 36 ? 0 : 2);
+ break;
+ case 38: case 39: /* Mystery Box, Mystery Box 2 (674-675, 837-838) */
+ if (B.team_ok[0] && B.team_ok[1]) B.mystery = 20, B.mystery_kind = (uint8_t)(a - 37);
+ break;
+ case 40: /* Esc Key (673, 831-832) */
+ B.dark = 100, B.dark_kind = 1;
+ break;
+ case 41: case 42: /* Unscrew, Unscrew 2 (667-668, 717-739) */
+ t = pick_enemy();
+ if (t >= 0) {
+ if (a == 41) B.en[t].s20 = (int16_t)(10 + rnd_n(5));
+ else B.en[t].s21 = (int16_t)(10 + rnd_n(5));
+ }
+ break;
+ case 44: case 45: /* Waterhose, Waterhose 2 (475-476, 1005-1006) */
+ f = fx_new(FX_SHOW, a == 44 ? AN_WATER : AN_WATER2, 400, 231);
+ B.hose = (int16_t)(a == 44 ? 60 : -100);
+ B.shake = 50;
+ break;
+ case 46: /* Haunting (907, 921) */
+ if ((f = fx_new(FX_HAUNT, AN_PBUBBLE, 868, 6 + 150))) f->vx = -80, f->vy = 30;
+ break;
+ case 47: /* Endo Army (867, 879-885) */
+ if (!B.endo_t) {
+ B.endo_t = 1;
+ for (int k = 0; k < 3; k++)
+ if ((f = fx_new(FX_ENDO, AN_ENDO, 619 - 125 - 140 * k, 261 + 27 + 30 * k))) f->t = (int16_t)(30 * k);
+ }
+ break;
+ case 48: B.shield = 30, B.flash = 200; break; /* Neon Wall (898) */
+ case 49: B.mimic = 10, B.mimic_attack = 49; break; /* Mimic Ball (868) */
+ case 50: /* Gift Boxes (908) */
+ for (int k = 0; k < 4; k++) B.gift[k] = 100;
+ break;
+ case 52: /* Slasher (2041, 2050-2051) */
+ if ((f = fx_new(FX_DAGGER, AN_DAGGER, att_x - 52, att_y - 123))) f->a = (int16_t)(rnd_n(10) + 1);
+ break;
+ case 53: /* 4th Wall (2042, 2052) */
+ fx_new(FX_WALL, AN_WALL, 379 + 49, 319 + 132);
+ break;
+ case 54: /* Jack-O-Bomb (2043, 2053-2054) */
+ if ((f = fx_new(FX_JACKO, AN_JACKO, 300 + rnd_n(200), 150))) f->vy = 0;
+ break;
+ case 55: B.newnums0 += (int16_t)(30 + rnd_n(30)); break; /* Bubble Breath (2044) */
+ case 56: /* Balloons 2 (2045, 2060) */
+ for (int k = 0; k < 9; k++)
+ if ((f = fx_new(FX_BALLOON, AN_BALLOON0, att_x - 2, att_y - 115))) {
+ f->b = (int16_t)rnd_n(4), f->an = (uint8_t)(AN_BALLOON0 + f->b), f->a = (int16_t)(power * 2 + 50);
+ f->vx = (int16_t)(-20 - rnd_n(60)), f->vy = (int16_t)(-40 - rnd_n(60));
+ }
+ break;
+ case 57: /* Buzzsaw (2046, 2063) */
+ if ((f = fx_new(FX_SAW, AN_SAW, att_x - 37, att_y - 123))) f->vx = -120;
+ break;
+ case 58: B.newnums1 += 60; break; /* Mega Virus (2047, 2085) */
+ case 59: B.newnums2 = 15, B.mystery_t = (uint8_t)rnd_n(2); break; /* Hocus Pocus (2048, 2071) */
+ case 60: B.shield2 = 5, B.flash = 200; break; /* Neon Wall 2 (2049) */
+ }
+}
+
+/* ------------------------------------------------------------------ the effects' steps */
+static bool near(Fx *f, Enemy *e, int r) {
+ int dx = f->x - e->x, dy = f->y - (e->y - 80);
+ return dx * dx + dy * dy < r * r;
+}
+static void home(Fx *f, int tx, int ty, int sp) { /* toward (tx, ty) at sp/16 pixels a frame */
+ int dx = tx - f->x, dy = ty - f->y;
+ int ad = (dx < 0 ? -dx : dx) + (dy < 0 ? -dy : dy);
+ if (!ad) return;
+ f->vx = (int16_t)(dx * sp / ad), f->vy = (int16_t)(dy * sp / ad);
+}
+
+static void fx_step(void) {
+ for (int i = 0; i < NFX; i++) {
+ Fx *f = &B.fx[i];
+ if (!f->kind) continue;
+ bool end = anim_step(f->an, &f->img, &f->cnt, &f->plays);
+ Enemy *e = f->target >= 0 ? &B.en[f->target] : NULL;
+ if (e && !e->alive) { /* its target gone: another one */
+ int t = pick_enemy();
+ f->target = (int8_t)t;
+ e = t >= 0 ? &B.en[t] : NULL;
+ }
+ f->t++;
+ switch (f->kind) {
+ case FX_SPARK: /* "Active 5": falls, gone at its end (493-494) */
+ f->y += f->vy / 16;
+ if (end) f->kind = 0;
+ break;
+ case FX_SHOW: case FX_NOTE: case FX_HIT:
+ f->y += f->vy / 16;
+ if (end || f->t > 180) f->kind = 0;
+ break;
+ case FX_MIC: /* 478: the mic flies to its target */
+ if (!e) { f->kind = 0; break; }
+ home(f, e->x, e->y - 80, 16 * 18);
+ f->x += f->vx / 16, f->y += f->vy / 16;
+ if (near(f, e, 40)) {
+ hit_enemy(f->target, f->a + 10 + rnd_n(5));
+ f->kind = 0;
+ }
+ break;
+ case FX_PIZZA: /* 483, 486: faster and faster to a target */
+ if (!e) { f->kind = 0; break; }
+ if (f->b < 100) f->b += 2;
+ home(f, e->x, e->y - 80, f->b * 4 + 64);
+ f->x += f->vx / 16, f->y += f->vy / 16;
+ if (near(f, e, 40)) {
+ hit_enemy(f->target, f->a + rnd_n(2) + 1);
+ f->kind = 0;
+ }
+ break;
+ case FX_BITE: /* 557, 849-851: at the end of the bite */
+ if (end) {
+ if (e) {
+ hit_enemy(f->target, f->a + rnd_n(f->b));
+ if (f->t && e) e->s15 = (int16_t)(5 + rnd_n(4));
+ }
+ f->kind = 0;
+ }
+ break;
+ case FX_TOXICBITE: /* 558 */
+ if (end) {
+ if (e) {
+ e->s15 = (int16_t)(5 + rnd_n(6)), e->s3 = 20;
+ hit_enemy(f->target, 25 + rnd_n(25));
+ for (int k = 0; k < 4; k++) fx_new(FX_SHOW, AN_PBUBBLE, e->x + rnd_n(80) - 40, e->y - 60 - rnd_n(60));
+ }
+ f->kind = 0;
+ }
+ break;
+ case FX_HOOK: /* 634 */
+ if (end) {
+ if (e) hit_enemy(f->target, f->a + 15 + rnd_n(5));
+ f->kind = 0;
+ }
+ break;
+ case FX_CLAW: /* 635: the beam crosses them all */
+ f->x -= 24;
+ for (int k = 0; k < 4; k++)
+ if (B.en[k].alive && !(f->b & 1 << k) && f->x < B.en[k].x) {
+ f->b |= (int16_t)(1 << k);
+ hit_enemy(k, f->a + 50 + rnd_n(30) + rnd_n(11) / 10 * 1000);
+ }
+ if (f->x < -100) f->kind = 0;
+ break;
+ case FX_TORNADO: /* 561-562: after 20 frames, each of them */
+ f->x -= 6;
+ if (f->t > 20 && !f->b) {
+ f->b = 1;
+ for (int k = 0; k < 4; k++)
+ if (B.en[k].alive) hit_enemy(k, f->a + rnd_n(6) + 10);
+ }
+ if (f->t > 60) f->kind = 0;
+ break;
+ case FX_BALLOON: /* 705-716: up, then to a target */
+ if (f->t < 40) {
+ f->x += f->vx / 16, f->y += f->vy / 16;
+ break;
+ }
+ if (!e) {
+ int t = pick_enemy();
+ if (t < 0) { f->kind = 0; break; }
+ f->target = (int8_t)t, e = &B.en[t];
+ }
+ home(f, e->x, e->y - 102, 16 * 10);
+ f->x += f->vx / 16, f->y += f->vy / 16;
+ if (near(f, e, 36)) {
+ hit_enemy(f->target, (f->a + rnd_n(3) + 5) * f->b + 1); /* 714 */
+ f->kind = 0;
+ }
+ break;
+ case FX_TBALLOON: /* 715: poison */
+ if (f->t < 40) { f->x += f->vx / 16, f->y += f->vy / 16; break; }
+ if (!e) {
+ int t = pick_enemy();
+ if (t < 0) { f->kind = 0; break; }
+ f->target = (int8_t)t, e = &B.en[t];
+ }
+ home(f, e->x, e->y - 88, 16 * 8);
+ f->x += f->vx / 16, f->y += f->vy / 16;
+ if (near(f, e, 36)) {
+ e->s3 = 20, e->s15 += (int16_t)(5 + rnd_n(6));
+ B.shake = 10;
+ f->kind = 0;
+ }
+ break;
+ case FX_HEAD: /* 905: after 100 frames */
+ if (f->t > 100) {
+ if (e) hit_enemy(f->target, f->a + 1 + rnd_n(1000) + 200);
+ B.shake = 100, B.flash = 200;
+ f->kind = 0;
+ }
+ break;
+ case FX_BADPIZZA: /* 856: after 25 frames, each */
+ if (f->t > 25) {
+ for (int k = 0; k < 4; k++)
+ if (B.en[k].alive) B.en[k].s3 = 20, hit_enemy(k, f->a + rnd_n(700) + 1);
+ f->kind = 0;
+ }
+ break;
+ case FX_GLOOM: /* 784: then their power down */
+ f->x += f->vx / 16, f->y += f->vy / 16;
+ if (f->t > 40) B.pwr_down = 30, f->kind = 0;
+ break;
+ case FX_CLOUD:
+ f->x -= 2;
+ if (f->t > 150) f->kind = 0;
+ if (B.stars2 && f->t % 16 == 0 && rnd_n(2) == 1) { /* 821: Rainy Day 2's rain */
+ int t = pick_enemy();
+ if (t >= 0) hit_enemy(t, B.cur_level * B.multiplier + rnd_n(5) + 5);
+ }
+ break;
+ case FX_STAR: { /* 874: from the sky to its target */
+ if (!e) { f->kind = 0; break; }
+ home(f, e->x, e->y - 80, 16 * 14);
+ f->x += f->vx / 16, f->y += f->vy / 16;
+ if (near(f, e, 40)) {
+ hit_enemy(f->target, 25 + rnd_n(10) + f->a);
+ f->kind = 0;
+ }
+ break;
+ }
+ case FX_FREDDLE: /* 909-918: runs at them, bites now and then */
+ f->x -= 4;
+ if (f->t % 6 == 0)
+ for (int k = 0; k < 4; k++)
+ if (B.en[k].alive && f->x < B.en[k].x + 60 && f->x > B.en[k].x - 60 && rnd_n(3) == 1) {
+ Fx *b = fx_new(FX_BITE, AN_BITE4, B.en[k].x + 2, B.en[k].y - 95);
+ if (b) b->target = (int8_t)k, b->a = (int16_t)(f->a + 20), b->b = 10;
+ }
+ if (f->x < -100) f->kind = 0;
+ break;
+ case FX_MUNCHIE: /* 683-687: three bites */
+ if (!e) { f->kind = 0; break; }
+ if (f->an == AN_MUNCHIE && f->t % 30 == 0 && rnd_n(2) == 1) f->an = AN_MUNCHIE2, f->img = 0, f->cnt = 0, f->plays = 1;
+ else if (f->an == AN_MUNCHIE2 && end) {
+ hit_enemy(f->target, f->a + 5 + rnd_n(5));
+ f->an = AN_MUNCHIE, f->img = 0;
+ if (++f->b > 2) f->kind = 0;
+ }
+ break;
+ case FX_PRIZE: /* 692-704, 815-825 */
+ if (f->t == 31) {
+ f->an = (uint8_t)(f->b ? AN_PRIZE2 : AN_PRIZE), f->img = 0, f->cnt = 0;
+ f->a = (int16_t)(f->b ? rnd_n(9) + 1 : rnd_n(100) + 1);
+ }
+ if (f->t > 31 && end) {
+ int power = B.cur_level * B.multiplier;
+ B.flash = 100;
+ if (!f->b) {
+ int s = f->a;
+ if (s == 1) hit_all(99, 99);
+ else if (s < 15) B.cup_t = 100, B.cup_level = (int16_t)rnd_n(50);
+ else if (s < 30) B.hose = 60;
+ else if (s < 45) { for (int k = 0; k < 4; k++) if (B.en[k].alive) B.en[k].s12 = 1; B.pizza_pow = (int16_t)power; }
+ else if (s < 65) B.stunned = (int16_t)(2 + rnd_n(6)), B.shake = 50;
+ else if (s < 85) B.atk_boost = (int16_t)(10 + rnd_n(10)), B.def_boost = (int16_t)(10 + rnd_n(10)), B.spd_boost = (int16_t)(10 + rnd_n(10));
+ else B.cheese_pow = (int16_t)(rnd_n(20) + 20), B.cheese_t = 5;
+ } else {
+ int s = f->a;
+ Fx *n;
+ if (s == 1)
+ for (int k = 0; k < 6; k++) {
+ if ((n = fx_new(FX_BALLOON, AN_BALLOON0, f->x, f->y - 109))) {
+ n->b = (int16_t)rnd_n(4), n->an = (uint8_t)(AN_BALLOON0 + n->b), n->a = (int16_t)power;
+ n->vx = (int16_t)(rnd_n(80) - 40), n->vy = (int16_t)(-40 - rnd_n(40));
+ }
+ }
+ else if (s == 2) { if ((n = fx_new(FX_TBALLOON, AN_BALLOON2, f->x, f->y - 109))) n->vy = -60; }
+ else if (s == 3) B.pwr_cloud = 2, B.pwr_cloud_t = 60, B.stars2 = 1, fx_new(FX_CLOUD, AN_CLOUD, 334, 155);
+ else if (s == 4) { if ((n = fx_new(FX_GLOOM, AN_BALLOON3, f->x, f->y - 71))) n->vx = -40; }
+ else if (s == 5) { int t = pick_enemy(); if (t >= 0) B.en[t].s21 = 10; }
+ else if (s == 6) hit_all(99, 99);
+ else if (s == 7) B.pizzas2 = (int16_t)(3 + rnd_n(4)), B.pizza2_pow = (int16_t)(power + 5);
+ else if (s == 8) B.hose = -100;
+ else B.freddles = (int16_t)(5 + rnd_n(10)), B.freddle_pow = (int16_t)power;
+ }
+ f->kind = 0;
+ }
+ break;
+ case FX_HAUNT: /* 921: the ghost over them makes them wait */
+ f->x += f->vx / 16, f->y += f->vy / 16;
+ if (f->t % 15 == 0)
+ for (int k = 0; k < 4; k++)
+ if (B.en[k].alive && !B.en[k].s18 && f->x < B.en[k].x + 80 && f->x > B.en[k].x - 80 && rnd_n(2) == 1)
+ B.en[k].s18 = (int16_t)(5 + rnd_n(25));
+ if (f->x < -100) f->kind = 0;
+ break;
+ case FX_ENDO: /* 879-885: they claw now and then, about 25 s */
+ if (f->t > 50 && f->t % 15 == 0 && rnd_n(2) == 1) {
+ Fx *c = fx_new(FX_CLAW, AN_CLAW2, f->x - 85, f->y - 122);
+ if (c) c->a = 0, c->b = 0;
+ f->an = AN_ENDO2, f->img = 0;
+ }
+ if (f->t > 1500) f->kind = 0, B.endo_t = 0;
+ break;
+ case FX_DAGGER: /* 2051: one in ten ends them all */
+ f->x -= 10;
+ if (end || f->t > 60) {
+ if (f->a == 1) hit_all(99999, 1);
+ f->kind = 0;
+ }
+ break;
+ case FX_WALL: /* 2052 */
+ if (end || f->t > 60) {
+ hit_all(3000, 3000);
+ B.shake = 100;
+ f->kind = 0;
+ }
+ break;
+ case FX_JACKO: /* 2054: falls, then pow */
+ f->y += 8;
+ if (end || f->t > 50) {
+ fx_new(FX_SHOW, AN_POW, f->x, f->y);
+ for (int k = 0; k < 4; k++)
+ if (B.en[k].alive) hit_enemy(k, rnd_n(1000));
+ B.shake = 100;
+ f->kind = 0;
+ }
+ break;
+ case FX_SAW: /* 2063: each it meets */
+ f->x += f->vx / 16;
+ for (int k = 0; k < 4; k++)
+ if (B.en[k].alive && !(f->b & 1 << k) && f->x < B.en[k].x + 40 && f->x > B.en[k].x - 40) {
+ f->b |= (int16_t)(1 << k);
+ hit_enemy(k, 999 * rnd_n(10));
+ }
+ if (f->x < -100) f->kind = 0;
+ break;
+ case FX_ENEMY_BALLOON: /* 1316, 1325: an enemy's balloon to a member */
+ home(f, STOP[f->b][0], STOP[f->b][1] - 90, 16 * 8);
+ f->x += f->vx / 16, f->y += f->vy / 16;
+ if ((f->x - STOP[f->b][0]) * (f->x - STOP[f->b][0]) + (f->y - STOP[f->b][1] + 90) * (f->y - STOP[f->b][1] + 90) < 1600) {
+ party_hit(f->b, g.w.area * 2 + rnd_n(11)); /* 1317-1324 */
+ f->kind = 0;
+ }
+ break;
+ case FX_STINGER: case FX_LASER: case FX_SYTH: /* the bytes' shots (484-485, 1743-1744) */
+ if (!e) { f->kind = 0; break; }
+ home(f, e->x, e->y - 70, 16 * 16);
+ f->x += f->vx / 16, f->y += f->vy / 16;
+ if (near(f, e, 40)) {
+ if (f->kind == FX_STINGER) hit_enemy(f->target, 15 + rnd_n(10));
+ else if (f->kind == FX_LASER) hit_enemy(f->target, 100 + rnd_n(50));
+ else if (g.w.area != 50 && ((!B.boss && rnd_n(10) == 1) || (B.boss && rnd_n(2000) == 1))) kill_enemy(f->target);
+ f->kind = 0;
+ }
+ break;
+ case FX_POPPER:
+ if (f->t > 600 || !enemies_alive()) f->kind = 0;
+ break;
+ case FX_SCREW:
+ f->y += 6;
+ if (f->t > 30) f->kind = 0;
+ break;
+ case FX_DRIP: case FX_PUDDLE:
+ if (f->t > 600) f->kind = 0;
+ break;
+ default:
+ if (end) f->kind = 0;
+ }
+ }
+}
+
+/* ------------------------------------------------------------------ a step */
+static void row_switch(int to) { /* 83-86: the other row comes */
+ B.row = (uint8_t)to;
+ for (int k = 0; k < 4; k++) B.pm[k].state = 3; /* (they leave: 89-90) */
+ B.ready = 0, B.att_slot = 0, B.used = 0;
+ B.leave_t = 20;
+}
+
+static void enemy_attack_step(void) {
+ int diff = g.f.diff ? g.f.diff : 1;
+ int div = divisor(B.def_boost > 0, B.shield > 0, B.pwr_down > 0);
+ int block = 0, armor = g.f.armor;
+ for (int k = 0; k < 4; k++) {
+ int b = g.f.bytes[k];
+ block += b == 13 ? 5 : b == 14 ? 20 : b == 15 ? 50 : 0; /* 1752-1755 */
+ }
+ if (every(T_STRENGTH, 250)) { /* 1061, 1238, 1560 */
+ if (B.boss) {
+ int32_t s;
+ boss_info(B.boss, diff, NULL, NULL, &s, NULL, NULL);
+ B.strength = s * diff / div - block - armor * 10;
+ } else if (B.chal) {
+ B.strength = (B.chal_c * 5 * diff + rnd_n(5)) / div - block - armor * 10;
+ } else {
+ B.strength = enemy_strength(B.etype, diff, div, block, armor);
+ }
+ B.special_strength = (B.special == 4 ? 20 : B.special == 10 ? 1000 : 10) + rnd_n(5) / div - block; /* 1331-1341 */
+ }
+ if (every(T_WHO, 200)) B.attacked_who = (uint8_t)(rnd_n(4) + 1); /* 1038 */
+ for (int n = 0; n < 4 && B.attacked_who; n++) { /* 1276-1279: past the ones out */
+ if (*life_of(B.attacked_who - 1) > 0) break;
+ B.attacked_who = (uint8_t)(B.attacked_who % 4 + 1);
+ }
+ /* their speed (1009-1010), stopped while stunned, haunted or waiting (Quickstart) */
+ bool tick = B.spd_down > 0 ? every(T_SPEED_SLOW, 100) : every(T_SPEED, 70);
+ for (int i = 0; i < 4; i++) {
+ Enemy *e = &B.en[i];
+ if (!e->alive) continue;
+ if (B.quick_t > 0 || e->s18 > 0) { /* 1521-1522 */
+ e->speed = (int16_t)(rnd_n(10) + 1);
+ continue;
+ }
+ if (tick && !B.stunned) e->speed += (int16_t)(1 + rnd_n(2));
+ }
+ int32_t go = B.boss ? B.boss_speed : 100;
+ if (every(T_ENEMY_GO, 500)) { /* 1011-1012: one of the ready ones attacks */
+ int cand[4], n = 0;
+ for (int i = 0; i < 4; i++)
+ if (B.en[i].alive && B.en[i].speed >= go && !B.en[i].s4) cand[n++] = i;
+ if (n) {
+ Enemy *e = &B.en[cand[rnd_n(n)]];
+ e->s4 = 1, e->s9 = 1, e->path = 2, e->node = 0, e->node_t = 0;
+ }
+ }
+ for (int i = 0; i < 4; i++) {
+ Enemy *e = &B.en[i];
+ if (!e->alive) continue;
+ if (e->s4 > 0 && ++e->s4 > 30) e->s4 = 0, e->speed = 1; /* 1013-1014 */
+ if (e->speed >= go + 5 && e->s9 && B.attacked_who) { /* 1015-1024 */
+ e->s9 = 0;
+ int k = B.attacked_who - 1;
+ B.attacked_who = 0;
+ int fxk = B.boss ? boss_info(B.boss, diff, NULL, NULL, NULL, NULL, NULL) : enemy_hit_effect(B.etype);
+ fx_new(FX_HIT, fxk == 1 ? AN_HIT0 : AN_HIT12 + (fxk - 2), STOP[k][0], STOP[k][1] - 91);
+ party_hit(k, B.strength);
+ }
+ }
+}
+
+static void special_step(void) {
+ /* 1300: every 10 s, one in "special chance" */
+ static const uint8_t CHANCE[12] = {0, 2, 2, 3, 3, 4, 3, 3, 3, 2, 4, 2};
+ int sp = B.special;
+ if (B.boss == 11 && !B.special_t && every(T_ROLL, 500)) sp = B.special = (uint8_t)(rnd_n(5) + 5);
+ if (B.boss == 15 && !B.special_t && every(T_ROLL, 500)) sp = B.special = (uint8_t)(rnd_n(6) + 5);
+ if (B.boss == 12 && !B.special_t && every(T_ROLL, 500)) sp = B.special = (uint8_t)(rnd_n(3) + 3);
+ if (!B.boss && g.w.area == 50 && !B.special_t && every(T_ROLL, 500)) sp = B.special = (uint8_t)(rnd_n(7) + 5);
+ if (sp && enemies_alive() && B.stage < 2 && every(T_SPECIAL, 10000) && rnd_n(CHANCE[sp]) == 1) B.special_t = 60;
+ if (B.special_t > 0 && --B.special_t == 0 && enemies_alive()) { /* 1299, 1301-1314 */
+ int k;
+ switch (sp) {
+ case 1: /* balloons at the party */
+ for (int n = 0; n < 4; n++) {
+ Fx *f = fx_new(FX_ENEMY_BALLOON, AN_BALLOON0 + rnd_n(3) + 1, B.en[0].x + 5, B.en[0].y - 215);
+ if (f) f->b = (int16_t)rnd_n(4);
+ }
+ break;
+ case 2: /* the bad note: the party's boosts and gifts gone */
+ B.shield = 0, B.atk_boost = B.def_boost = B.spd_boost = 0;
+ for (k = 0; k < 4; k++) B.gift[k] = 0;
+ fx_new(FX_SHOW, AN_BADNOTE, B.en[0].x + 25, B.en[0].y - 116);
+ break;
+ case 3: /* unscrew a member */
+ if (!B.block_unscrew) B.screw_t = 20, B.screw_who = (int16_t)(rnd_n(4) + 1);
+ break;
+ case 4: B.cheese = 5; break; /* cheese */
+ case 5: if (!B.block_unscrew) B.dark = 100, B.dark_kind = 2; break;
+ case 6: B.poison_all = (int16_t)(5 + rnd_n(6)); break; /* toxic */
+ case 7: if (!B.block_confuse) B.confuse = (int16_t)(5 + rnd_n(10)); break;
+ case 8: B.hose = 75, B.shake = 100; break; /* waterhose */
+ case 9: B.special18 = 20, B.shake = 100; break;
+ case 10: B.wall_t = 60, B.shake = 100; break;
+ case 11: B.screw_t = 20, B.screw_who = (int16_t)(rnd_n(4) + 1); break;
+ }
+ }
+ /* the specials playing */
+ if (B.screw_t > 0 && every(T_SCREW, 100)) { /* 1345-1356 */
+ fx_new(FX_SCREW, AN_SCREW, STOP[B.screw_who - 1][0], STOP[B.screw_who - 1][1] - 160);
+ if (--B.screw_t == 1) {
+ *life_of(B.screw_who - 1) = 0;
+ B.screw_t = 0;
+ }
+ }
+ if (B.cheese > 0 && every(T_CHEESE, 1000)) { /* 1357-1365 */
+ B.cheese--;
+ if (rnd_n(2) == 1 && B.attacked_who && *life_of(B.attacked_who - 1) > 0) party_hit(B.attacked_who - 1, B.special_strength);
+ }
+ if (B.poison_all > 0 && every(T_4000, 4000)) { /* 1374-1375 */
+ B.poison_all--;
+ for (int n = 0; n < 4; n++) party_hit(n, B.special_strength + rnd_n(10));
+ }
+ if (B.confuse > 0) { /* 1377-1382 */
+ for (int n = 0; n < 4; n++) B.charge[(B.row - 1) * 4 + n] = (uint8_t)(1 + rnd_n(5));
+ if (every(T_CONFUSE, 1000)) B.confuse--;
+ }
+ if (B.hose > 0 && sp == 8 && B.stage < 2) { /* 1383-1392: half life or less: out */
+ if (--B.hose == 1)
+ for (int n = 0; n < 4; n++) {
+ int32_t *l = life_of(n);
+ if (*l < B.life_max[(B.row - 1) * 4 + n] / 2) *l = 0;
+ }
+ }
+ if (B.dark > 0 && --B.dark == 1) { /* 831-834 */
+ if (B.dark_kind == 1) {
+ for (int i = 0; i < 4; i++)
+ if (B.en[i].alive && g.w.area != 50) B.en[i].s25 = (int16_t)(B.boss ? rnd_n(1000) + 1 : rnd_n(60) + 1);
+ } else {
+ for (int n = 0; n < 4; n++) {
+ int32_t *l = life_of(n);
+ *l -= 5000 * rnd_n(2);
+ if (*l < 0) *l = 0;
+ }
+ }
+ }
+ if (B.wall_t > 0 && --B.wall_t == 1)
+ for (int n = 0; n < 4; n++) party_hit(n, B.special_strength);
+}
+
+void battle_step(void) {
+ ms3 += 50;
+ B.step++;
+ int diff = g.f.diff ? g.f.diff : 1;
+ (void)diff;
+ /* the members' places */
+ B.moving = 0;
+ for (int k = 0; k < 4; k++) {
+ if (B.pm[k].state == 1) { /* coming in (22-29, "character" movement 1) */
+ if (B.pm[k].t > 0) { B.pm[k].t--; B.moving = 1; continue; }
+ int step = PATH_STEP;
+ while (step > 0 && B.pm[k].node < 39) {
+ B.pm[k].x += PATH_IN[B.pm[k].node][0] * 0, B.pm[k].y += 0;
+ int dx = PATH_IN[B.pm[k].node][0], dy = PATH_IN[B.pm[k].node][1];
+ B.pm[k].x += (int16_t)dx, B.pm[k].y += (int16_t)dy;
+ int len = (dx < 0 ? -dx : dx) > (dy < 0 ? -dy : dy) ? (dx < 0 ? -dx : dx) : (dy < 0 ? -dy : dy);
+ step -= len ? len : 1;
+ B.pm[k].node++;
+ }
+ if (B.pm[k].node >= 39) B.pm[k].state = 2;
+ B.moving = 1;
+ } else if (B.pm[k].state == 3) { /* leaving (89) */
+ B.pm[k].x += 15;
+ B.moving = 1;
+ if (B.pm[k].x > 1100) B.pm[k].state = 0;
+ }
+ if (B.pm[k].state == 2 && B.pm[k].t > 0) B.pm[k].t--;
+ }
+ if (B.leave_t > 0 && --B.leave_t == 0) party_enter(); /* 87-88: the new row comes */
+ if (B.att_slot) B.moving = 1;
+ if (B.mimic_t > 0) B.moving = 1;
+ for (int k = 0; k < 4; k++) {
+ if (B.pm[k].state) anim_step(*life_of(k) > 0 ? AN_IDLE1 + 2 * (field_char(k) - 1) : AN_KO, &B.pm[k].img, &B.pm[k].cnt, &(uint8_t){0});
+ }
+ /* the enemies' places */
+ for (int i = 0; i < 4; i++) {
+ Enemy *e = &B.en[i];
+ if (!e->alive) continue;
+ uint8_t p = 1;
+ anim_step(e->an, &e->img, &e->cnt, &p);
+ if (e->path == 1 && e->node < 27) {
+ int step = PATH_STEP;
+ while (step > 0 && e->node < 27) {
+ int dx = ENEMY_IN[e->node][0], dy = ENEMY_IN[e->node][1];
+ e->x += (int16_t)dx, e->y += (int16_t)dy;
+ int len = (dx < 0 ? -dx : dx) > (dy < 0 ? -dy : dy) ? (dx < 0 ? -dx : dx) : (dy < 0 ? -dy : dy);
+ step -= len ? len : 1;
+ e->node++;
+ }
+ } else if (e->path == 2) { /* the lunge and back */
+ int n = e->node;
+ if (n < 12) {
+ e->x += ENEMY_LUNGE[n][0] / 2, e->y += ENEMY_LUNGE[n][1] / 2;
+ } else if (n < 24) {
+ e->x -= ENEMY_LUNGE[23 - n][0] / 2, e->y -= ENEMY_LUNGE[23 - n][1] / 2;
+ } else
+ e->path = 0;
+ e->node++;
+ }
+ if (e->s5 > 0) e->s5--;
+ if (e->s3 > 0) e->s3--;
+ }
+ /* charges (91-106): one point a second (0.7 with a speed boost) while nobody else in the row is full */
+ bool fast = B.spd_boost > 0;
+ if (B.stage < 2 && (fast ? every(T_CHARGE_FAST, 700) : every(T_CHARGE, 1000))) {
+ uint8_t *c = &B.charge[(B.row - 1) * 4];
+ for (int k = 0; k < 4; k++) {
+ bool other_full = false;
+ for (int j = 0; j < 4; j++)
+ if (j != k && c[j] == 10) other_full = true;
+ if (c[k] < 10 && !other_full) c[k]++;
+ }
+ }
+ for (int k = 0; k < 8; k++)
+ if (B.charge[k] > 10) B.charge[k] = 10;
+ for (int k = 0; k < 8; k++)
+ if (B.life[k] <= 0) B.charge[k] = 0; /* 1268-1275 */
+ /* the attack buttons (117-151, 1520) */
+ B.ready_turn = !B.ready && !B.att_slot && B.mimic_t <= 0;
+ if (!B.ready && !B.moving && B.stage < 2 && !B.mystery)
+ for (int k = 0; k < 4; k++)
+ if (B.charge[(B.row - 1) * 4 + k] >= 10 && *life_of(k) > 0) {
+ B.ready = (uint8_t)(k + 1), B.sel = 0;
+ break;
+ }
+ if (B.ready && (*life_of(B.ready - 1) <= 0 || B.stage >= 2)) B.ready = 0;
+ /* the attack playing (419-466, 509-556) */
+ if (B.att_slot) {
+ int prev = B.att_img;
+ bool end = anim_step(B.att_an, &B.att_img, &B.att_cnt, &B.att_plays);
+ if (B.att_img != prev && B.att_img == attack_frame(B.used) && !B.att_frame_done) {
+ B.att_frame_done = 1;
+ do_attack(B.used);
+ if (B.mimic > 0 && B.used != 49 && B.used != B.mimic_attack) B.mimic_attack = B.used; /* 889-890 */
+ }
+ if (end) {
+ if (!B.att_frame_done) do_attack(B.used);
+ B.att_slot = 0;
+ if (B.mimic > 0 && B.mimic_attack != 49 && B.used != 49) B.mimic_t = 175; /* 890: the mimic does it again */
+ }
+ }
+ if (B.mimic_t > 0 && --B.mimic_t == 0 && B.mimic > 0 && enemies_alive()) { /* 892 */
+ B.mimic--;
+ do_attack(B.mimic_attack);
+ }
+ /* attack power (587, 809-812) */
+ B.multiplier = (int16_t)((B.atk_boost > 0 ? 2 : 1) * (B.spd_down2 > 0 ? 2 : 1));
+ /* the timed parts of attacks */
+ if (B.cup_t > 0 && --B.cup_t == 0) party_heal(B.cup_level * 2 + 30 + rnd_n(10)); /* 617 */
+ if (B.hj_t > 0) { /* 590-592 */
+ if (B.hj_t % 3 == 0) fx_new(FX_NOTE, B.hj_kind == 1 ? AN_NOTE : AN_NOTE2, 672 - 61 + rnd_n(120) - 60, 471 + 105 - 200 - rnd_n(80));
+ if (--B.hj_t == 0) party_heal(B.hj_level * 2 + 30 + rnd_n(20));
+ }
+ if (B.favors_t > 0 && every(T_FAVORS, 70) && --B.favors_t == 1) { /* 623 */
+ B.favors_t = 0;
+ party_heal(B.favors_level + 1);
+ hit_all(B.favors_level + 1 + 1, 5);
+ }
+ if (B.regen_n > 0 && B.regen <= 0) B.regen = B.regen_n, B.regen_n = 0, party_heal(g.w.area + 1); /* 630 */
+ if (B.regen > 0 && every(T_5000, 5000)) B.regen--, party_heal(g.w.area + 1); /* 631 */
+ if (B.pizzas > 0 && every(T_PIZZA, 200)) { /* 481 */
+ B.pizzas--;
+ Fx *f = fx_new(FX_PIZZA, AN_PIZZA, 870, 158 + 100);
+ if (f) f->target = (int8_t)pick_enemy(), f->a = B.pizza_pow;
+ }
+ if (B.pizzas2 > 0 && every(T_PIZZA2, 200)) { /* 482 */
+ B.pizzas2--;
+ Fx *f = fx_new(FX_PIZZA, AN_PIZZA2, 870, 158 + 100);
+ if (f) f->target = (int8_t)pick_enemy(), f->a = B.pizza2_pow;
+ }
+ if (B.freddles > 0 && every(T_FREDDLE, 200)) { /* 909 */
+ B.freddles--;
+ Fx *f = fx_new(FX_FREDDLE, AN_FREDDLE, 870 + 1, 158 + 62 + 150);
+ if (f) f->a = B.freddle_pow;
+ }
+ if (B.stars > 0 && every(T_STARS, 250)) { /* 873 */
+ int t = pick_enemy();
+ if (t >= 0) {
+ B.stars--;
+ Fx *f = fx_new(FX_STAR, AN_STAR, B.en[t].x + 267, B.en[t].y - 279);
+ if (f) f->target = (int8_t)t, f->a = B.star_pow;
+ }
+ }
+ if (B.cheese_t > 0 && every(T_DRIP, 200)) { /* 644-645: the drips, then puddles */
+ B.cheese_t--;
+ fx_new(FX_PUDDLE, AN_PUDDLE, 100 + rnd_n(250), 330 + rnd_n(90));
+ B.cheese_pow = B.cheese_pow;
+ }
+ if (every(T_PUDDLE, 250)) {
+ bool puddle = false;
+ for (int i = 0; i < NFX; i++) puddle |= B.fx[i].kind == FX_PUDDLE;
+ if (puddle && rnd_n(5) == 1) { /* 649 */
+ int t = pick_enemy();
+ hit_enemy(t, B.cheese_pow + rnd_n(4) + 3);
+ }
+ for (int i = 0; i < 4; i++) /* 683: munchies */
+ if (B.en[i].alive && B.en[i].s12) {
+ B.en[i].s12 = 0;
+ Fx *f = fx_new(FX_MUNCHIE, AN_MUNCHIE, B.en[i].x + 69, B.en[i].y - 193 + 100);
+ if (f) f->target = (int8_t)i, f->a = B.pizza_pow;
+ break;
+ }
+ }
+ if (B.popper_n > 0 && every(T_POPPER, 100)) { /* 676 */
+ B.popper_n--;
+ fx_new(FX_POPPER, AN_POPPER, 200 + rnd_n(250), 300 + rnd_n(120));
+ B.poppers_on = 1;
+ }
+ if (B.poppers_on && !B.popper_n && ++B.poppers_wait > 600) { /* 678-681 */
+ B.poppers_on = 0, B.poppers_wait = 0;
+ for (int i = 0; i < NFX; i++)
+ if (B.fx[i].kind == FX_POPPER) B.fx[i].kind = 0;
+ hit_all(B.popper_pow, 5);
+ B.shake = 50;
+ }
+ if (B.pwr_cloud > 0 && every(T_CLOUDS, 750)) { /* 793-794: three clouds, then the curse */
+ fx_new(FX_CLOUD, AN_CLOUD, 214 + rnd_n(300), 120 + rnd_n(60));
+ if (--B.pwr_cloud == 0) B.spd_down2 = B.pwr_cloud_t;
+ }
+ if (B.pwr_cloud_t > 0 && B.pwr_cloud == 0 && !B.spd_down2 && !B.stars2) { /* Gloom Song (746-748) */
+ if (--B.pwr_cloud_t == 1) B.pwr_down = 30, B.pwr_cloud_t = 0;
+ }
+ if (B.hose != 0 && !B.boss) { /* 1005-1006, 650-651 */
+ int32_t m = B.enemy_max;
+ for (int i = 0; i < 4; i++) {
+ Enemy *e = &B.en[i];
+ if (!e->alive) continue;
+ if ((B.hose > 0 && e->hurt < -(m - m / 3)) || (B.hose < 0 && e->hurt < -(m - m / 2))) e->hurt = -m - 1;
+ }
+ if (B.hose > 0) B.hose--;
+ else B.hose++;
+ }
+ if (B.mystery > 0 && every(T_MYSTERY, 70) && --B.mystery == 1) { /* 837-838: a new party, for this battle */
+ B.mystery = 0;
+ int extra = rnd_n(5) + 1;
+ int base = B.mystery_kind == 1 ? 1 : 9;
+ for (int k = 0; k < 8; k++) {
+ int c = rnd_n(4) + base + 4 * (k & 3) + extra;
+ g.f.slot[k] = (uint8_t)(c > NCHAR ? NCHAR : c);
+ }
+ B.team_ok[0] = B.team_ok[1] = 1;
+ row_switch(B.row == 1 ? 2 : 1);
+ }
+ if (B.newnums2 > 0 && every(T_HOCUS, 70) && --B.newnums2 == 1) { /* 2071: Hocus Pocus */
+ B.newnums2 = 0;
+ if (B.mystery_t) B.etype = (uint8_t)(B.etype / (rnd_n(5) + 2));
+ }
+ if (B.newnums1 > 0 && every(T_VIRUS, 250) && rnd_n(2) == 1) hit_enemy(pick_enemy(), 99 * rnd_n(10)); /* 2085 */
+ /* unscrews (717-741) */
+ if (every(T_UNSCREW, 100))
+ for (int i = 0; i < 4; i++) {
+ Enemy *e = &B.en[i];
+ if (!e->alive) continue;
+ if (e->s20 > 0) {
+ fx_new(FX_SCREW, AN_SCREW, e->x - 2, e->y - 160);
+ if (--e->s20 == 1 && g.w.area != 50) e->s25 = (int16_t)(B.boss ? rnd_n(600) + 1 : rnd_n(30) + 1);
+ }
+ if (e->s21 > 0) {
+ fx_new(FX_SCREW, AN_SCREW, e->x - 5, e->y - 160);
+ if (--e->s21 == 1 && g.w.area != 50) e->s25 = (int16_t)(B.boss ? rnd_n(500) + 1 : rnd_n(20) + 1);
+ }
+ }
+ /* poison (776): every 500 ms one in eight, a poisoned one */
+ if (every(T_POISON, 500) && rnd_n(8) == 0) {
+ int cand[4], n = 0;
+ for (int i = 0; i < 4; i++)
+ if (B.en[i].alive && B.en[i].s15 > 0) cand[n++] = i;
+ if (n) {
+ int i = cand[rnd_n(n)];
+ B.en[i].s15--;
+ hit_enemy(i, g.w.area * 2 + 10 + rnd_n(20));
+ }
+ }
+ /* chips in battle: Evercomet (1519), Freddle: Fury (1532), Pizza: Fury (1538) */
+ if (B.stage < 2 && B.comet && every(T_COMET, 1000) && rnd_n(10) < B.comet) {
+ int t = pick_enemy();
+ Fx *f = t >= 0 ? fx_new(FX_STAR, AN_STAR, B.en[t].x + 267, B.en[t].y - 279) : NULL;
+ if (f) f->target = (int8_t)t, f->a = (int16_t)(B.cur_level * B.multiplier);
+ }
+ if (B.stage < 2 && B.freddle_fury && every(T_FURY, 250) && rnd_n(5) == 1) B.freddles++;
+ if (B.stage < 2 && B.pizza_fury && every(T_PFURY, 1000) && rnd_n(3) == 1)
+ B.pizzas = (int16_t)(rnd_n(3) + 3), B.pizza_pow = (int16_t)(B.cur_level * B.multiplier + rnd_n(3));
+ /* bytes (1731-1759) */
+ if (B.stage < 2 && enemies_alive())
+ for (int k = 0; k < 4; k++) {
+ int b = g.f.bytes[k];
+ static const uint16_t PERIOD[22] = {0, 2000, 1000, 500, 5050, 5550, 6050, 5000, 2910, 890, 1000, 600, 400,
+ 0, 0, 0, 500, 410, 670, 0, 0, 0};
+ if (!b) continue;
+ if (b >= 19) { /* BossDrain: a boss's life a frame */
+ if (B.boss) B.en[0].hurt -= b - 18;
+ continue;
+ }
+ if (!PERIOD[b] || !byte_every(k, PERIOD[b])) continue;
+ int bx = 100 + 60 * k, by = 40;
+ Fx *f;
+ int t;
+ switch (b) {
+ case 1: case 2: case 3:
+ if (rnd_n(3) == 1 && (t = pick_enemy()) >= 0 && (f = fx_new(FX_STINGER, AN_STINGER, bx, by))) f->target = (int8_t)t;
+ break;
+ case 4: party_heal(5 + rnd_n(6)); break;
+ case 5: party_heal(10 + rnd_n(6)); break;
+ case 6: party_heal(25 + rnd_n(6)); break;
+ case 7: case 8: case 9:
+ if (rnd_n(2) == 1 && (t = pick_enemy()) >= 0 && (f = fx_new(FX_SYTH, AN_SYTH, bx, by))) f->target = (int8_t)t;
+ break;
+ case 10: case 11: case 12:
+ if (rnd_n(3) == 1 && (t = pick_enemy()) >= 0 && (f = fx_new(FX_LASER, AN_STINGER, bx, by))) f->target = (int8_t)t;
+ break;
+ case 16: case 17: case 18:
+ if (!(B.bomb_used & 1 << k) && rnd_n(10) == 1) {
+ B.bomb_used |= (uint8_t)(1 << k);
+ fx_new(FX_SHOW, AN_POW, bx + 46, by + 49 + 100);
+ if (b == 16) hit_all(100, 100);
+ else if (b == 17) hit_all(200, 900);
+ else hit_all(1000, 4000);
+ }
+ break;
+ }
+ }
+ /* the second's countdowns (584-586, 758-760, 779, 902, 2059, 2066, 2074) */
+ if (every(T_SECOND, 1000)) {
+ if (B.atk_boost > 0) B.atk_boost--;
+ if (B.def_boost > 0) B.def_boost--;
+ if (B.spd_boost > 0) B.spd_boost--;
+ if (B.pwr_down > 0) B.pwr_down--;
+ if (B.spd_down > 0) B.spd_down--;
+ if (B.spd_down2 > 0) B.spd_down2--;
+ if (B.stunned > 0) B.stunned--;
+ if (B.shield > 0) B.shield--;
+ if (B.shield2 > 0) B.shield2--;
+ if (B.newnums0 > 0) B.newnums0--;
+ if (B.newnums1 > 0) B.newnums1--;
+ for (int i = 0; i < 4; i++)
+ if (B.en[i].s18 > 0) B.en[i].s18--;
+ }
+ if (B.quick_t > 0) B.quick_t--;
+ /* the enemies */
+ if (B.stage < 2) {
+ enemy_attack_step();
+ special_step();
+ }
+ fx_step();
+ apply_hits();
+ /* Bubble Breath's lava (2090): area 50 drains life */
+ if (g.w.area == 50 && B.stage < 2 && B.newnums0 <= 0 && every(T_LAVA, 30))
+ for (int n = 0; n < 4; n++)
+ if (*life_of(n) > 0) --*life_of(n);
+ /* gift boxes (1244-1251) */
+ for (int n = 0; n < 4; n++)
+ if (*life_of(n) <= 0 && B.gift[n] > 0) {
+ *life_of(n) += 1000;
+ int32_t m = B.life_max[(B.row - 1) * 4 + n];
+ if (*life_of(n) > m) *life_of(n) = m;
+ B.gift[n] = 0;
+ B.flash = 100;
+ }
+ /* the rows (1280-1284, 84-85) */
+ for (int r = 0; r < 2; r++) {
+ B.team_ok[r] = 0;
+ for (int n = 0; n < 4; n++) B.team_ok[r] |= B.life[r * 4 + n] > 0;
+ }
+ if (!B.team_ok[0] && !B.team_ok[1] && B.stage < 2) { /* 1283-1284: lost */
+ B.lost++;
+ if (B.lost > 6) {
+ g.f.resetpos = 1;
+ B.on = 0;
+ g.scene = SC_GAMEOVER, g.t = 0;
+ return;
+ }
+ }
+ if (!B.moving && B.leave_t == 0 && B.stage < 2 && !B.team_ok[B.row - 1] && B.team_ok[2 - B.row]) row_switch(3 - B.row);
+ /* victory (964-965, 1076-1132) */
+ if (B.stage == 1 && !enemies_alive()) {
+ B.stage = 2;
+ B.ready = 0;
+ for (int k = 0; k < 8; k++) B.charge[k] = 0;
+ int diff2 = g.f.diff ? g.f.diff : 1;
+ B.exp = victory_exp(B.count, B.etype, B.boss, g.w.area, diff2);
+ B.tokens = victory_tokens(B.count, B.etype, B.boss, g.w.area, diff2);
+ if (B.chal) B.chal_won = 1;
+ B.vt0 = B.vt1 = B.vt2 = 0;
+ }
+ if (B.stage == 2) {
+ if (++B.vt0 > 50 && B.exp > 0 && every(T_EXP, 50)) { /* 1086-1107 */
+ int k = exp_tick(B.exp);
+ B.exp -= k;
+ for (int s = 0; s < 8; s++) {
+ int c = g.f.slot[s];
+ g.f.next[c] += (uint32_t)k;
+ if ((int32_t)g.f.next[c] > exp_needed(c, g.f.lv[c])) {
+ if (g.f.lv[c] < 255) g.f.lv[c]++;
+ g.f.next[c] = 0;
+ B.life[s] += 1000;
+ if (B.life[s] > (B.life_max[s] = life_max(c, g.f.lv[c]))) B.life[s] = B.life_max[s];
+ if (s / 4 == B.row - 1) B.leveled[s & 3] = 60;
+ }
+ }
+ }
+ if (B.vt0 > 50 && B.exp <= 0) B.vt1++;
+ if (B.vt1 > 50 && B.tokens > 0 && every(T_TOKENS, 50)) { /* 1095-1098 */
+ for (int t = 0; t < 4; t++) {
+ static const int32_t over[4] = {0, 10, 20, 50};
+ if (B.tokens > over[t]) B.tokens--, g.f.tokens++;
+ }
+ }
+ if (B.vt1 > 50 && B.tokens <= 0 && ++B.vt2 > 100) { /* 1131-1132 */
+ B.won = 1;
+ B.on = 0;
+ }
+ }
+ for (int k = 0; k < 4; k++)
+ if (B.leveled[k] > 0) B.leveled[k]--;
+ for (int i = 0; i < 12; i++)
+ if (nums[i].t > 0) nums[i].t--, nums[i].y -= 1;
+ if (B.shake > 0) B.shake--;
+ if (B.flash > 0) B.flash = (int16_t)(B.flash > 10 ? B.flash - 10 : 0); /* 689 */
+}
+
+/* ------------------------------------------------------------------ keys */
+void battle_keys(uint32_t pressed, uint32_t held) {
+ if (B.ready && !B.att_slot) {
+ if (pressed & (K_UP | K_DIGIT(8))) B.sel = (uint8_t)((B.sel + 2) % 3);
+ if (pressed & (K_DOWN | K_DIGIT(2))) B.sel = (uint8_t)((B.sel + 1) % 3);
+ int pick = -1;
+ if (pressed & (K_OK | K_EXE)) pick = B.sel;
+ for (int k = 1; k <= 3; k++)
+ if (pressed & K_DIGIT(k)) pick = k - 1;
+ if (pick >= 0) { /* 240-247 */
+ int k = B.ready - 1, c = field_char(k);
+ B.charge[(B.row - 1) * 4 + k] = 0;
+ B.used = CHAR_ATTACKS[c][pick];
+ B.att_slot = (uint8_t)(k + 1);
+ B.att_an = (uint8_t)(AN_ATTACK1 + 2 * (c - 1));
+ B.att_img = 0, B.att_cnt = 0, B.att_plays = ANIMS[B.att_an].plays, B.att_frame_done = 0;
+ B.cur_level = (int16_t)level_of(k);
+ B.ready = 0;
+ }
+ }
+ /* SWITCH (83, 86) */
+ if ((pressed & K_DEL) && !B.moving && B.stage < 2 && !B.mystery && B.leave_t == 0 && B.team_ok[2 - B.row])
+ row_switch(3 - B.row);
+ /* hold 0 to run (1602-1605) */
+ B.running = (held & K_DIGIT(0)) && !B.boss && B.stage < 2 && !B.moving;
+ if (B.running) {
+ if (every(T_RUN, B.run_luck ? 100 : 200)) {
+ int n = B.run_luck ? 5 + g.w.area : 10 + g.w.area * 2;
+ if (rnd_n(n) == 1) B.on = 0, B.won = 0;
+ }
+ for (int k = 0; k < 8; k++) B.charge[k] = (uint8_t)(3 + rnd_n(5));
+ B.ready = 0;
+ }
+}
+
+/* ------------------------------------------------------------------ drawing */
+static int shake_x, shake_y;
+
+static void draw_actor_pic(int pic, int gx, int gy, int fade) {
+ pic_fade(pic, SX(gx) + shake_x, SY(gy) + shake_y, fade);
+}
+
+static void bar(int x, int y, int w, int h, int32_t v, int32_t m, uint16_t c) {
+ gfx_fill(x - 1, y - 1, w + 2, h + 2, BLACK);
+ gfx_fill(x, y, w, h, RGB(0x303040));
+ if (m > 0 && v > 0) gfx_fill(x, y, (int)(v * w / m < w ? v * w / m : w), h, c);
+}
+
+static const uint16_t CAP[8] = {0xFC00, 0xF800, 0xF81F, 0x07E0, 0x801F, 0xFFFF, 0xFFE0, 0x2104};
+
+static void draw_button(int x, int y, int w, int a, bool sel) {
+ gfx_fill(x, y, w, 18, sel ? RGB(0x5A78C8) : RGB(0x34488C));
+ gfx_fill(x, y, 6, 18, CAP[ATTACK_COLOUR[a]]);
+ gfx_frame_rect(x - 1, y - 1, w + 2, 20, sel ? WHITE : RGB(0x1A2448));
+ if (sel) gfx_frame_rect(x - 2, y - 2, w + 4, 22, RGB(0xFFD040));
+ gfx_text_c(FONT_SMALL, x + 3 + w / 2, y + 2, ATTACK_NAME[a], WHITE);
+}
+
+void battle_draw_band_dim(void) {
+ int bg = 0;
+ switch (g.w.area) {
+ case 2: bg = PIC_BG3; break;
+ case 5: bg = PIC_BG2; break;
+ case 8: bg = PIC_BG4; break;
+ case 11: case 17: bg = PIC_BG5; break;
+ case 14: bg = PIC_BG6; break;
+ case 20: bg = PIC_BG7; break;
+ case 23: bg = PIC_BG8; break;
+ case 26: bg = PIC_BG9; break;
+ case 50: bg = PIC_BG11; break;
+ default: bg = PIC_BG0;
+ }
+ if (gfx_y0 < FIELD_H) {
+ pic_part(bg, shake_x - 2, shake_y - 2, 0, 0, 324, 196);
+ /* actors by their feet */
+ int order[8], n = 0;
+ for (int i = 0; i < 4; i++)
+ if (B.en[i].alive) order[n++] = i;
+ for (int k = 0; k < 4; k++)
+ if (B.pm[k].state) order[n++] = 4 + k;
+ for (int i = 1; i < n; i++)
+ for (int j = i; j > 0; j--) {
+ int ya = order[j - 1] < 4 ? B.en[order[j - 1]].y : B.pm[order[j - 1] - 4].y;
+ int yb = order[j] < 4 ? B.en[order[j]].y : B.pm[order[j] - 4].y;
+ if (ya > yb) { int t = order[j]; order[j] = order[j - 1]; order[j - 1] = t; }
+ }
+ for (int i = 0; i < n; i++) {
+ if (order[i] < 4) {
+ Enemy *e = &B.en[order[i]];
+ if (e->s5 && (e->s5 / 3) & 1) continue; /* 487-488: blinks when hit */
+ int fade = e->s18 > 0 ? 16 : 32;
+ draw_actor_pic(pic_of(e->an, e->img), e->x, e->y, fade);
+ } else {
+ int k = order[i] - 4;
+ if (B.att_slot == k + 1) {
+ draw_actor_pic(pic_of(B.att_an, B.att_img), B.pm[k].x, B.pm[k].y, 32);
+ continue;
+ }
+ if (B.pm[k].t > 0 && (B.pm[k].t / 3) & 1 && B.pm[k].state == 2) continue;
+ int an = *life_of(k) > 0 ? AN_IDLE1 + 2 * (field_char(k) - 1) : AN_KO;
+ draw_actor_pic(pic_of(an, *life_of(k) > 0 ? B.pm[k].img : 0), B.pm[k].x, B.pm[k].y, 32);
+ }
+ }
+ for (int i = 0; i < NFX; i++) {
+ Fx *f = &B.fx[i];
+ if (!f->kind) continue;
+ draw_actor_pic(pic_of(f->an, f->img), f->x, f->y, f->kind == FX_PUDDLE ? 24 : 32);
+ }
+ if (B.shield > 0) gfx_blend(SX(375), 0, 320 - SX(375), FIELD_H, RGB(0xC040FF), 5);
+ if (B.shield2 > 0) gfx_blend(SX(375), 0, 320 - SX(375), FIELD_H, RGB(0x40FFFF), 6);
+ if (B.dark > 0) gfx_dim(0, 0, 320, FIELD_H, 8);
+ if (B.flash > 0) gfx_blend(0, 0, 320, FIELD_H, WHITE, B.flash > 255 ? 12 : B.flash * 12 / 255);
+ for (int i = 0; i < 12; i++)
+ if (nums[i].t > 0) {
+ char s[12];
+ int32_t v = nums[i].v;
+ int p = 11;
+ s[p] = 0;
+ do s[--p] = (char)('0' + v % 10), v /= 10; while (v && p > 0);
+ uint16_t c = nums[i].kind == NUM_HEAL ? RGB(0x60FF60) : nums[i].kind == NUM_HURT ? RGB(0xFF5050) : WHITE;
+ gfx_text_s(FONT_TEXT, SX(nums[i].x) + shake_x, SY(nums[i].y) + shake_y, s + p, c);
+ }
+ /* the enemies' name, a boss's life */
+ if (enemies_alive() && B.boss != 10) {
+ const char *name = B.chal ? (B.chal_c >= 34 ? "???" : CHAR_NAME[B.chal_c]) : B.boss ? BOSS_NAME[B.boss] : ENEMY_NAME[B.etype];
+ gfx_text_s(FONT_TEXT, 4, 3, name, WHITE);
+ if (B.boss && B.boss != 15 && B.boss != 19) {
+ int32_t l = B.boss_life + B.en[0].hurt;
+ bar(110, 6, 120, 6, l, B.boss_life, RGB(0xE03030));
+ }
+ }
+ if (B.special_t > 0 && B.special) { /* the special's name ("enemy attack") */
+ int an = B.special == 1 ? AN_SPECIAL0 : AN_SPECIAL12 + (B.special - 2);
+ pic_draw(pic_of(an, 0), 160, 40);
+ }
+ if (B.stunned > 0)
+ for (int i = 0; i < 4; i++)
+ if (B.en[i].alive) pic_draw(pic_of(AN_DIZZY, (B.step / 3) % ANIMS[AN_DIZZY].n), SX(B.en[i].x + 4), SY(B.en[i].y - 118));
+ /* the attacks of the member that is ready (137-151) */
+ if (B.ready && !B.att_slot) {
+ int k = B.ready - 1, c = field_char(k);
+ int bx = SX(B.pm[k].x) - 150, by = SY(B.pm[k].y) - 80;
+ if (bx < 4) bx = 4;
+ if (by < 22) by = 22;
+ if (by > FIELD_H - 70) by = FIELD_H - 70;
+ for (int i = 0; i < 3; i++) draw_button(bx + 4 * i, by + 23 * i, 112, CHAR_ATTACKS[c][i], B.sel == i);
+ gfx_img(IMG_UP, SX(B.pm[k].x) - 4, SY(B.pm[k].y - 260) + 2, RGB(0xFFD040));
+ }
+ if (B.stage == 2) { /* VICTORY! Exp earned, Faz Tokens */
+ int vp = pic_of(AN_VICTORY, ANIMS[AN_VICTORY].n - 1);
+ pic_draw(vp, 160 - 50 + pic_hx(vp), 30 + pic_hy(vp));
+ char s[16];
+ int32_t v = B.exp;
+ int p = 15;
+ s[p] = 0;
+ do s[--p] = (char)('0' + v % 10), v /= 10; while (v && p > 0);
+ gfx_text_c(FONT_BIG, 160, 30 + 50, s + p, WHITE);
+ v = B.tokens, p = 15;
+ do s[--p] = (char)('0' + v % 10), v /= 10; while (v && p > 0);
+ gfx_text_c(FONT_BIG, 160, 30 + 80, s + p, WHITE);
+ for (int k = 0; k < 4; k++)
+ if (B.leveled[k]) pic_draw(pic_of(AN_LEVELUP, 0), SX(B.pm[k].x + 4), SY(B.pm[k].y - 181));
+ }
+ if (B.running) pic_draw(pic_of(AN_RUN, (B.step / 4) & 1), 160, 90);
+ }
+ /* the party's panel */
+ if (gfx_y0 + BAND_H > FIELD_H) {
+ gfx_fill(0, FIELD_H, 320, 48, RGB(0x10183A));
+ gfx_fill(0, FIELD_H, 320, 1, RGB(0x6080D0));
+ for (int k = 0; k < 4; k++) {
+ int x = 2 + 80 * k, c = field_char(k);
+ int32_t l = *life_of(k), m = B.life_max[(B.row - 1) * 4 + k];
+ bool ready = B.ready == k + 1;
+ if (ready) gfx_fill(x - 1, FIELD_H + 2, 78, 30, RGB(0x2A4A9A));
+ char name[24];
+ int n = 0;
+ for (const char *s = CHAR_NAME[c]; *s && n < 23; s++) name[n++] = *s;
+ name[n] = 0;
+ while (gfx_text_w(FONT_SMALL, name) > 74 && n > 0) name[--n] = 0;
+ gfx_text(FONT_SMALL, x + 1, FIELD_H + 3, name, l > 0 ? WHITE : RGB(0x707070));
+ bar(x + 1, FIELD_H + 18, 72, 5, l, m, l > m / 3 ? RGB(0x40E040) : RGB(0xE04040));
+ bar(x + 1, FIELD_H + 26, 72, 3, B.charge[(B.row - 1) * 4 + k], 10, RGB(0xFFD040));
+ }
+ const char *keys = B.stage == 2 ? "" : B.ready ? "OK attack 1 2 3 Back pause" : "Back pause";
+ gfx_text(FONT_SMALL, 3, FIELD_H + 34, keys, RGB(0xB0C0E0));
+ if (B.stage < 2 && B.team_ok[2 - B.row] && !B.moving) {
+ gfx_text_r(FONT_SMALL, 317, FIELD_H + 34, "switch hold 0 run", RGB(0xB0C0E0));
+ gfx_img(IMG_DEL, 317 - gfx_text_w(FONT_SMALL, "switch hold 0 run") - 16, FIELD_H + 36, RGB(0xB0C0E0));
+ }
+ else if (B.stage < 2 && !B.boss) gfx_text_r(FONT_SMALL, 317, FIELD_H + 34, "hold 0 run", RGB(0xB0C0E0));
+ }
+}
+
+void battle_prepare_view(void) { shake_x = shake_y = 0; }
+
+void battle_draw(void) {
+ shake_x = shake_y = 0;
+ if (B.shake > 0) shake_x = rnd_n(5) - 2, shake_y = rnd_n(5) - 2; /* "follow 2": the camera shakes */
+ gfx_frame(battle_draw_band_dim);
+}
diff --git a/games/fnafworld/src/data.S b/games/fnafworld/src/data.S
new file mode 100644
index 00000000..466e293a
--- /dev/null
+++ b/games/fnafworld/src/data.S
@@ -0,0 +1,19 @@
+/* data.bin (tools/pack.py) in the app's read-only data */
+#ifdef __APPLE__
+ .const_data
+ .p2align 2
+ .globl _fnafw_data
+_fnafw_data:
+ .incbin DATA_BIN
+ .p2align 2
+#else
+ .section .rodata.fnafw_data,"a"
+ .balign 4
+ .global fnafw_data
+fnafw_data:
+ .incbin DATA_BIN
+ .balign 4
+#endif
+#ifdef __ELF__
+ .section .note.GNU-stack,"",%progbits
+#endif
diff --git a/games/fnafworld/src/data.bin b/games/fnafworld/src/data.bin
new file mode 100644
index 00000000..4637973f
Binary files /dev/null and b/games/fnafworld/src/data.bin differ
diff --git a/games/fnafworld/src/data.h b/games/fnafworld/src/data.h
new file mode 100644
index 00000000..cad73efb
--- /dev/null
+++ b/games/fnafworld/src/data.h
@@ -0,0 +1,84 @@
+/* Made by tools/pack.py: what is in data.bin. */
+#ifndef FNAFW_DATA_H
+#define FNAFW_DATA_H
+
+#define SEC_HUFF 0
+#define SEC_QUANT 1
+#define SEC_PICS 2
+#define SEC_TABLE 3
+#define SEC_BANK 4
+#define SEC_MASK 5
+#define SEC_FONTS 6
+#define SEC_IMGS 7
+#define SEC_SPRS 8
+#define SEC_WORLD 9
+#define PIC_COUNT 2555
+#define FONT_SMALL 0
+#define FONT_TEXT 1
+#define FONT_BIG 2
+#define FONT_NUM 3
+#define FONT_HUGE 4
+#define PIC_TITLE 0
+#define PIC_MENU 1
+#define PIC_B_NEWGAME 2
+#define PIC_B_CONTINUE 3
+#define PIC_B_YES 4
+#define PIC_B_NO 5
+#define PIC_B_ADVENTURE 6
+#define PIC_B_FIXED 7
+#define PIC_B_NORMAL 8
+#define PIC_B_HARD 9
+#define PIC_B_SLOT 10
+#define PIC_FACE1 11
+#define PIC_TROPHY1 59
+#define PIC_TROPHY2 60
+#define PIC_TROPHY3 61
+#define PIC_TROPHY4 62
+#define PIC_TROPHY5 63
+#define PIC_TROPHY6 64
+#define PIC_TROPHY7 65
+#define PIC_BG0 1852
+#define PIC_BG2 1853
+#define PIC_BG3 1854
+#define PIC_BG4 1855
+#define PIC_BG5 1856
+#define PIC_BG6 1857
+#define PIC_BG7 1858
+#define PIC_BG8 1859
+#define PIC_BG9 1860
+#define PIC_BG11 1861
+#define IMG_UP 0
+#define IMG_DOWN 1
+#define IMG_DEL 2
+#define SPR_WALK 101
+#define WALK_N 15
+#define SPR_STAND 61
+#define SPR_LILLY 161
+#define LILLY_N 10
+#define HIT_W 23
+#define HIT_H 23
+#define HIT_HX 11
+#define HIT_HY 11
+#define FEEL_TOP_W 23
+#define FEEL_TOP_H 10
+#define FEEL_TOP_HX 11
+#define FEEL_TOP_HY 5
+#define FEEL_BOTTOM_W 23
+#define FEEL_BOTTOM_H 12
+#define FEEL_BOTTOM_HX 11
+#define FEEL_BOTTOM_HY 6
+#define FEEL_LEFT_W 9
+#define FEEL_LEFT_H 23
+#define FEEL_LEFT_HX 4
+#define FEEL_LEFT_HY 11
+#define FEEL_RIGHT_W 9
+#define FEEL_RIGHT_H 23
+#define FEEL_RIGHT_HX 4
+#define FEEL_RIGHT_HY 11
+#define START_X 1827
+#define START_Y 1023
+#define MAP_W 6000
+#define MAP_H 4000
+#define CELL 10
+
+#endif
diff --git a/games/fnafworld/src/game.c b/games/fnafworld/src/game.c
new file mode 100644
index 00000000..87360ac5
--- /dev/null
+++ b/games/fnafworld/src/game.c
@@ -0,0 +1,663 @@
+/* FNAF World: the scenes around the map, the keys and the saves.
+ *
+ * As the game: the title, the files (three, each Adventure or Fixed Party, Normal or Hard: the frame "file setup"),
+ * the party (eight of the characters you have: "character select"), the map and its battles, the chips and bytes
+ * worn ("chips", "Bytes"), Lolbit's byte store ("shop") and Mendo's armor ("armor shop"), game over. */
+#include <string.h>
+#include "anims.h"
+#include "data.h"
+#include "game.h"
+#include "gfx.h"
+#include "plat.h"
+
+Game g;
+void world_after_battle(void);
+
+static uint32_t seed = 0x2545F491u;
+uint32_t rnd(void) {
+ seed ^= seed << 13, seed ^= seed >> 17, seed ^= seed << 5;
+ return seed;
+}
+int rnd_n(int n) { return n > 0 ? (int)(rnd() % (uint32_t)n) : 0; }
+
+#define OKS (K_OK | K_EXE)
+#define UPS (K_UP | K_DIGIT(8))
+#define DOWNS (K_DOWN | K_DIGIT(2))
+#define LEFTS (K_LEFT | K_DIGIT(4))
+#define RIGHTS (K_RIGHT | K_DIGIT(6))
+static bool pressed(uint32_t k) { return (g.pressed & k) != 0; }
+static const uint16_t HILITE = 0xFE88, KEYS = 0xC67C;
+
+static void go(int scene) { g.scene = (uint8_t)scene, g.t = 0, g.menu = 0, g.sub = 0; }
+
+void game_init(void) {
+ memset(&g, 0, sizeof g);
+ g.running = true;
+ seed ^= plat_millis() * 2654435761u + 1;
+ save_restore_copy();
+ go(SC_TITLE);
+}
+
+static void num(char *out, int32_t v) {
+ char t[12];
+ int p = 11;
+ bool neg = v < 0;
+ if (neg) v = -v;
+ t[p] = 0;
+ do t[--p] = (char)('0' + v % 10), v /= 10; while (v && p > 1);
+ if (neg) t[--p] = '-';
+ strcpy(out, t + p);
+}
+
+/* ------------------------------------------------------------------ the title and the files */
+static void start_play(void) {
+ if (!g.f.locked && g.f.mode != 2) { /* the party first (the character select after a new game) */
+ g.pick = 0, g.pick_slot = 0, g.pick_mode = 0;
+ go(SC_PARTY);
+ g.back = SC_WORLD;
+ return;
+ }
+ world_enter();
+ go(SC_WORLD);
+}
+
+static void files_step(void) {
+ /* menu stages (2-31): 0 the files, 1 new/continue, 2 erase?, 4 the mode, 5 the difficulty */
+ int n = g.sub == 0 ? 3 : 2;
+ if (pressed(UPS)) g.menu = (uint8_t)((g.menu + n - 1) % n);
+ if (pressed(DOWNS)) g.menu = (uint8_t)((g.menu + 1) % n);
+ if (pressed(K_BACK)) {
+ if (g.sub == 0) go(SC_TITLE);
+ else g.sub = 0, g.menu = (uint8_t)(g.slot - 1);
+ return;
+ }
+ if (!pressed(OKS)) return;
+ switch (g.sub) {
+ case 0:
+ g.slot = (uint8_t)(g.menu + 1);
+ g.sub = 1, g.menu = 0;
+ if (!load_file(g.slot, &g.f)) memset(&g.f, 0, sizeof g.f);
+ break;
+ case 1:
+ if (g.menu == 0) g.sub = 2, g.menu = 1;
+ else if (g.f.started) start_play();
+ break;
+ case 2:
+ if (g.menu == 0) g.sub = 4, g.menu = 0; /* 17: YES */
+ else g.sub = 0, g.menu = (uint8_t)(g.slot - 1);
+ break;
+ case 4: /* 23-25 */
+ memset(&g.f, 0, sizeof g.f);
+ g.f.mode = (uint8_t)(g.menu + 1);
+ for (int c = 1; c <= (g.f.mode == 2 ? 16 : 8); c++) g.f.have[c] = 1;
+ for (int k = 0; k < 8; k++) g.f.slot[k] = (uint8_t)(k + 1); /* 42 */
+ if (g.f.mode == 2) {
+ for (int k = 0; k < 8; k++) g.f.slot[k] = (uint8_t)(k + 9);
+ g.f.locked = 1;
+ }
+ g.sub = 5, g.menu = 0;
+ break;
+ case 5: /* 28-29 */
+ g.f.diff = (uint8_t)(g.menu + 1);
+ g.f.started = 1;
+ save_new(g.slot);
+ start_play();
+ break;
+ }
+}
+
+static void button_pic(int pic, int cx, int y, bool sel) {
+ pic_draw(pic, cx, y);
+ if (sel) {
+ int w = pic_w(pic), h = pic_h(pic), x0 = cx - pic_hx(pic), y0 = y - pic_hy(pic);
+ gfx_frame_rect(x0 - 2, y0 - 2, w + 4, h + 2, HILITE);
+ gfx_frame_rect(x0 - 3, y0 - 3, w + 6, h + 4, HILITE);
+ }
+}
+
+static struct { uint8_t mode, diff, h, m; bool st; } summary[3];
+static void files_band(void) {
+ pic_part(PIC_MENU, 0, 0, 0, 0, 320, 240);
+ static const char *const MODE[3] = {"Empty", "Adventure", "Fixed Party"};
+ if (g.sub == 0) {
+ gfx_text_c(FONT_BIG, 160, 14, "Pick a file", WHITE);
+ for (int i = 0; i < 3; i++) {
+ uint8_t mode = summary[i].mode, diff = summary[i].diff, h = summary[i].h, m = summary[i].m;
+ bool st = summary[i].st;
+ int y = 50 + 52 * i;
+ gfx_fill(40, y, 240, 42, g.menu == i ? RGB(0x5A3A9A) : RGB(0x2A1A5A));
+ gfx_frame_rect(40, y, 240, 42, g.menu == i ? HILITE : WHITE);
+ char s[48], t[8];
+ strcpy(s, "File ");
+ s[5] = (char)('1' + i), s[6] = 0;
+ gfx_text(FONT_BIG, 52, y + 4, s, WHITE);
+ if (st) {
+ strcpy(s, MODE[mode < 3 ? mode : 0]);
+ strcat(s, diff == 2 ? ", Hard " : ", Normal ");
+ num(t, h);
+ strcat(s, t);
+ strcat(s, m < 10 ? ":0" : ":");
+ num(t, m);
+ strcat(s, t);
+ } else
+ strcpy(s, "Empty");
+ gfx_text(FONT_SMALL, 52, y + 26, s, RGB(0xD0C8F0));
+ }
+ } else if (g.sub == 1) {
+ gfx_text_c(FONT_BIG, 160, 30, "File", WHITE);
+ button_pic(PIC_B_NEWGAME, 160, 100, g.menu == 0);
+ button_pic(PIC_B_CONTINUE, 160, 150, g.menu == 1);
+ if (!g.f.started) gfx_blend(160 - 70, 150 - 18, 140, 36, BLACK, 18);
+ } else if (g.sub == 2) {
+ gfx_text_c(FONT_BIG, 160, 30, "Erase this file?", WHITE);
+ button_pic(PIC_B_YES, 160, 100, g.menu == 0);
+ button_pic(PIC_B_NO, 160, 150, g.menu == 1);
+ } else if (g.sub == 4) {
+ gfx_text_c(FONT_BIG, 160, 22, "Game mode", WHITE);
+ button_pic(PIC_B_ADVENTURE, 160, 80, g.menu == 0);
+ gfx_text_c(FONT_SMALL, 160, 100, "Find new characters as you play.", WHITE);
+ button_pic(PIC_B_FIXED, 160, 148, g.menu == 1);
+ gfx_text_c(FONT_SMALL, 160, 168, "Start with two fixed teams.", WHITE);
+ gfx_text_c(FONT_SMALL, 160, 181, "(more difficult)", WHITE);
+ } else {
+ gfx_text_c(FONT_BIG, 160, 22, "Difficulty", WHITE);
+ button_pic(PIC_B_NORMAL, 160, 90, g.menu == 0);
+ button_pic(PIC_B_HARD, 160, 150, g.menu == 1);
+ }
+ gfx_blend(0, 226, 320, 14, BLACK, 18);
+ gfx_text(FONT_SMALL, 4, 227, "Arrows pick OK choose Back go back", KEYS);
+}
+
+static void title_band(void) {
+ pic_part(PIC_TITLE, 0, 0, 0, 0, 320, 240);
+ if ((g.t / 30) & 1) gfx_frame_rect(160 - 49, 240 - 33, 98, 27, HILITE);
+ gfx_blend(0, 0, 320, 13, BLACK, 14);
+ gfx_text(FONT_SMALL, 3, 0, "OK start Back quit", KEYS);
+}
+
+/* ------------------------------------------------------------------ the party (character select) */
+static void party_step(void) {
+ if (g.pick_mode == 0) { /* the slots: which of the eight to change */
+ if (pressed(LEFTS)) g.pick_slot = (uint8_t)((g.pick_slot + 7) % 8);
+ if (pressed(RIGHTS)) g.pick_slot = (uint8_t)((g.pick_slot + 1) % 8);
+ if (pressed(UPS) || pressed(DOWNS)) g.pick_slot ^= 4;
+ if (pressed(OKS) && !g.f.locked) {
+ g.pick_mode = 1;
+ g.pick = (uint8_t)(g.f.slot[g.pick_slot] ? g.f.slot[g.pick_slot] - 1 : 0);
+ }
+ if (pressed(K_DIGIT(0)) || pressed(K_BACK)) { /* Done (34): all eight there */
+ bool full = true;
+ for (int k = 0; k < 8; k++) full &= g.f.slot[k] != 0;
+ if (!full) return;
+ g.f.started = 1;
+ if (g.f.mode != 2) g.f.locked = 0;
+ g.dirty = 1;
+ save_file();
+ if (g.back == SC_WORLD && g.w.x == 0) world_enter();
+ go(SC_WORLD);
+ }
+ return;
+ }
+ /* the characters: 8 x 6 */
+ if (pressed(LEFTS)) g.pick = (uint8_t)((g.pick + 47) % 48);
+ if (pressed(RIGHTS)) g.pick = (uint8_t)((g.pick + 1) % 48);
+ if (pressed(UPS)) g.pick = (uint8_t)((g.pick + 40) % 48);
+ if (pressed(DOWNS)) g.pick = (uint8_t)((g.pick + 8) % 48);
+ if (pressed(K_BACK)) g.pick_mode = 0;
+ if (pressed(OKS)) { /* 23-30: one you have, not in the party yet */
+ int c = g.pick + 1;
+ bool in = false;
+ for (int k = 0; k < 8; k++) in |= g.f.slot[k] == c && k != g.pick_slot;
+ if (g.f.have[c] && !in) {
+ g.f.slot[g.pick_slot] = (uint8_t)c;
+ g.pick_mode = 0;
+ g.pick_slot = (uint8_t)((g.pick_slot + 1) % 8);
+ }
+ }
+}
+
+static void party_band(void) {
+ pic_part(PIC_MENU, 0, 0, 0, 0, 320, 240);
+ gfx_blend(0, 0, 320, 240, BLACK, 10);
+ /* the faces */
+ for (int i = 0; i < 48; i++) {
+ int x = 4 + 29 * (i % 8), y = 4 + 29 * (i / 8);
+ if (y > gfx_y0 + BAND_H || y + 28 < gfx_y0) continue;
+ pic_part(PIC_FACE1 + i, x, y, 0, 0, 28, 28);
+ if (!g.f.have[i + 1]) gfx_blend(x, y, 28, 28, BLACK, 26);
+ for (int k = 0; k < 8; k++)
+ if (g.f.slot[k] == i + 1) {
+ gfx_fill(x + 18, y + 18, 10, 10, k < 4 ? RGB(0x2050E0) : RGB(0xC03030));
+ char s[2] = {(char)('1' + k), 0};
+ gfx_text(FONT_SMALL, x + 20, y + 16, s, WHITE);
+ }
+ if (g.pick_mode == 1 && g.pick == i) {
+ gfx_frame_rect(x - 1, y - 1, 30, 30, HILITE);
+ gfx_frame_rect(x - 2, y - 2, 32, 32, HILITE);
+ }
+ }
+ /* the party's two rows */
+ for (int k = 0; k < 8; k++) {
+ int x = 4 + 29 * (k & 3) + (k >= 4 ? 120 : 0), y = 182;
+ gfx_fill(x - 1, y - 1, 30, 30, k < 4 ? RGB(0x2050E0) : RGB(0xC03030));
+ if (g.f.slot[k]) pic_part(PIC_FACE1 + g.f.slot[k] - 1, x, y, 0, 0, 28, 28);
+ if (g.pick_slot == k) {
+ gfx_frame_rect(x - 2, y - 2, 32, 32, g.pick_mode == 0 ? HILITE : WHITE);
+ gfx_frame_rect(x - 3, y - 3, 34, 34, g.pick_mode == 0 ? HILITE : WHITE);
+ }
+ }
+ /* the one picked: its name, level, attacks */
+ int c = g.pick_mode == 1 ? g.pick + 1 : g.f.slot[g.pick_slot];
+ gfx_fill(240, 4, 76, 206, RGB(0x141A40));
+ gfx_frame_rect(240, 4, 76, 206, RGB(0x6070C0));
+ if (c && g.f.have[c]) {
+ int an = AN_IDLE1 + 2 * (c - 1);
+ int pic = ANIM_PICS[ANIMS[an].first + (g.t / 2) % ANIMS[an].n];
+ pic_draw(pic, 278, 110);
+ char s[32], t[12];
+ const char *name = CHAR_NAME[c];
+ int w = gfx_text_w(FONT_SMALL, name);
+ if (w > 72) gfx_text(FONT_SMALL, 242, 112, name, WHITE);
+ else gfx_text_c(FONT_SMALL, 278, 112, name, WHITE);
+ strcpy(s, "Level ");
+ num(t, g.f.lv[c] + 1);
+ strcat(s, t);
+ gfx_text(FONT_SMALL, 244, 126, s, WHITE);
+ strcpy(s, "Next ");
+ num(t, exp_needed(c, g.f.lv[c]) - (int32_t)g.f.next[c]);
+ strcat(s, t);
+ gfx_text(FONT_SMALL, 244, 139, s, WHITE);
+ for (int i = 0; i < 3; i++) {
+ int a = CHAR_ATTACKS[c][i];
+ gfx_fill(243, 155 + 17 * i, 70, 15, RGB(0x34488C));
+ gfx_text_c(FONT_SMALL, 278, 156 + 17 * i, ATTACK_NAME[a], WHITE);
+ }
+ } else if (c) {
+ gfx_text_c(FONT_TEXT, 278, 100, "???", WHITE);
+ }
+ gfx_blend(0, 226, 320, 14, BLACK, 18);
+ if (g.f.locked) gfx_text(FONT_SMALL, 4, 227, "Fixed party. 0 or Back done", KEYS);
+ else if (g.pick_mode == 0) gfx_text(FONT_SMALL, 4, 227, "Arrows slot OK change 0 done", KEYS);
+ else gfx_text(FONT_SMALL, 4, 227, "Arrows pick OK put in Back cancel", KEYS);
+}
+
+/* ------------------------------------------------------------------ the pause menu */
+enum { P_RESUME, P_PARTY, P_CHIPS, P_BYTES, P_JUMP, P_SAVE, P_HOWTO, P_QUIT, P_COUNT };
+static const char *const PAUSE_ITEM[P_COUNT] = {"Resume", "Party", "Chips", "Bytes", "Jump", "Save", "How to play",
+ "Quit"};
+static bool warp_open(int k) { /* 1798-1803 */
+ switch (k) {
+ case 0: return true;
+ case 1: return g.f.sw[1];
+ case 2: return g.f.w3;
+ case 3: return g.f.sw[2];
+ case 4: return g.f.sw[3];
+ default: return g.f.sw[4];
+ }
+}
+static const int16_t WARP[6][2] = {{1829, 1024}, {1673, 1628}, {918, 1726}, {2787, 833}, {3275, 1922}, {2544, 3685}};
+static const char *const WARP_NAME[6] = {"Fazbear Hills", "Choppy's Woods", "Dusting Fields", "Lilygear Lake",
+ "Blacktomb Yard", "Pinwheel Circus"};
+
+static void pause_step(void) {
+ if (g.confirm) {
+ if (pressed(OKS)) {
+ save_file();
+ g.running = false;
+ }
+ if (pressed(K_BACK)) g.confirm = 0;
+ return;
+ }
+ if (pressed(UPS)) g.menu = (uint8_t)((g.menu + P_COUNT - 1) % P_COUNT);
+ if (pressed(DOWNS)) g.menu = (uint8_t)((g.menu + 1) % P_COUNT);
+ if (pressed(K_BACK)) {
+ go(g.back);
+ return;
+ }
+ if (!pressed(OKS)) return;
+ bool battle = g.back == SC_BATTLE;
+ switch (g.menu) {
+ case P_RESUME: go(g.back); break;
+ case P_PARTY:
+ if (battle || g.f.mode == 2) break; /* 1194: not in Fixed Party */
+ g.pick_mode = 0, g.pick_slot = 0;
+ go(SC_PARTY);
+ g.back = SC_WORLD;
+ break;
+ case P_CHIPS: if (!battle) go(SC_CHIPS); break;
+ case P_BYTES: if (!battle) go(SC_BYTES); break;
+ case P_JUMP:
+ if (!battle && g.w.area != 23 && g.w.area != 50) go(SC_WARP);
+ break;
+ case P_SAVE:
+ if (!battle) {
+ world_save_pos();
+ save_file();
+ go(SC_WORLD);
+ }
+ break;
+ case P_HOWTO: go(SC_HOWTO); break;
+ case P_QUIT: g.confirm = 1; break;
+ }
+}
+
+static void menu_list(const char *const *items, int n, int sel, int x, int y, int w, const uint8_t *dim) {
+ for (int i = 0; i < n; i++) {
+ int yy = y + 22 * i;
+ gfx_fill(x, yy, w, 19, i == sel ? RGB(0x3A58B8) : RGB(0x1A2858));
+ if (i == sel) gfx_frame_rect(x - 1, yy - 1, w + 2, 21, HILITE);
+ gfx_text(FONT_TEXT, x + 8, yy + 2, items[i], dim && dim[i] ? RGB(0x707890) : WHITE);
+ }
+}
+
+static void pause_band(void) {
+ if (g.back == SC_BATTLE) battle_draw_band_dim();
+ else world_band_dim();
+ gfx_blend(0, 0, 320, 240, BLACK, 18);
+ gfx_text_c(FONT_BIG, 160, 8, "Paused", WHITE);
+ uint8_t dim[P_COUNT] = {0};
+ bool battle = g.back == SC_BATTLE;
+ dim[P_PARTY] = battle || g.f.mode == 2;
+ dim[P_CHIPS] = dim[P_BYTES] = dim[P_SAVE] = battle;
+ dim[P_JUMP] = battle || g.w.area == 23 || g.w.area == 50;
+ menu_list(PAUSE_ITEM, P_COUNT, g.menu, 90, 36, 140, dim);
+ if (g.confirm) {
+ gfx_fill(40, 90, 240, 56, RGB(0x0A1430));
+ gfx_frame_rect(40, 90, 240, 56, WHITE);
+ gfx_text_c(FONT_TEXT, 160, 98, "Save and quit?", WHITE);
+ gfx_text_c(FONT_SMALL, 160, 122, "OK yes Back no", KEYS);
+ }
+ gfx_blend(0, 226, 320, 14, BLACK, 18);
+ gfx_text(FONT_SMALL, 4, 227, "Arrows pick OK choose Back resume", KEYS);
+}
+
+/* ------------------------------------------------------------------ jumps */
+static void warp_step(void) {
+ if (pressed(UPS)) g.menu = (uint8_t)((g.menu + 5) % 6);
+ if (pressed(DOWNS)) g.menu = (uint8_t)((g.menu + 1) % 6);
+ if (pressed(K_BACK)) go(SC_PAUSE);
+ if (pressed(OKS) && warp_open(g.menu)) { /* 1804-1809 */
+ g.w.x = WARP[g.menu][0], g.w.y = WARP[g.menu][1];
+ world_save_pos();
+ go(SC_WORLD);
+ }
+}
+
+static void warp_band(void) {
+ world_band_dim();
+ gfx_blend(0, 0, 320, 240, BLACK, 18);
+ gfx_text_c(FONT_BIG, 160, 8, "Jump", WHITE);
+ uint8_t dim[6];
+ for (int k = 0; k < 6; k++) dim[k] = !warp_open(k);
+ menu_list(WARP_NAME, 6, g.menu, 70, 40, 180, dim);
+ gfx_blend(0, 226, 320, 14, BLACK, 18);
+ gfx_text(FONT_SMALL, 4, 227, "Arrows pick OK jump Back go back", KEYS);
+}
+
+/* ------------------------------------------------------------------ chips and bytes (4 worn each) */
+static void wear_step(bool bytes) {
+ uint8_t *worn = bytes ? g.f.bytes : g.f.chip;
+ int n = bytes ? NBYTE : NCHIP;
+ if (pressed(UPS)) g.menu = (uint8_t)((g.menu + n - 1) % n);
+ if (pressed(DOWNS)) g.menu = (uint8_t)((g.menu + 1) % n);
+ if (pressed(LEFTS)) g.menu = (uint8_t)((g.menu + n - 7) % n);
+ if (pressed(RIGHTS)) g.menu = (uint8_t)((g.menu + 7) % n);
+ if (pressed(K_BACK)) {
+ g.dirty = 1;
+ go(SC_PAUSE);
+ g.menu = bytes ? P_BYTES : P_CHIPS;
+ return;
+ }
+ if (!pressed(OKS)) return;
+ int id = g.menu + 1;
+ bool have = bytes ? g.f.byte_have[id] : g.f.chest[id];
+ if (!have) return;
+ for (int k = 0; k < 4; k++)
+ if (worn[k] == id) { /* off */
+ worn[k] = 0;
+ return;
+ }
+ for (int k = 0; k < 4; k++)
+ if (!worn[k]) {
+ worn[k] = (uint8_t)id;
+ return;
+ }
+}
+
+static void wear_band(bool bytes) {
+ pic_part(PIC_MENU, 0, 0, 0, 0, 320, 240);
+ gfx_blend(0, 0, 320, 240, BLACK, 16);
+ const uint8_t *worn = bytes ? g.f.bytes : g.f.chip;
+ int n = bytes ? NBYTE : NCHIP;
+ gfx_text_c(FONT_BIG, 160, 2, bytes ? "Bytes" : "Chips", WHITE);
+ for (int i = 0; i < n; i++) {
+ int col = i / 7, row = i % 7;
+ int x = 4 + 105 * col, y = 26 + 22 * row;
+ int id = i + 1;
+ bool have = bytes ? g.f.byte_have[id] : g.f.chest[id];
+ bool on = false;
+ for (int k = 0; k < 4; k++) on |= worn[k] == id;
+ gfx_fill(x, y, 102, 19, on ? RGB(0x2A7A3A) : RGB(0x1A2858));
+ if (g.menu == i) gfx_frame_rect(x - 1, y - 1, 104, 21, HILITE);
+ const char *name = have ? (bytes ? BYTE_NAME[id] : CHIP_NAME[id]) : "???";
+ gfx_text(FONT_SMALL, x + 3, y + 3, name, have ? WHITE : RGB(0x707890));
+ }
+ gfx_text(FONT_SMALL, 6, 184, "Worn:", WHITE);
+ for (int k = 0; k < 4; k++) {
+ const char *name = worn[k] ? (bytes ? BYTE_NAME[worn[k]] : CHIP_NAME[worn[k]]) : "-";
+ gfx_text(FONT_SMALL, 44 + 70 * k, 184, name, RGB(0xFFD040));
+ }
+ gfx_blend(0, 226, 320, 14, BLACK, 18);
+ gfx_text(FONT_SMALL, 4, 227, "Arrows pick OK wear or take off Back done", KEYS);
+}
+
+/* ------------------------------------------------------------------ the shops */
+static int shop_first(int kind) { /* the shop's events 56-62 */
+ switch (kind) {
+ case 1: return 1;
+ case 2: return 4;
+ case 5: return 7;
+ case 20: return 10;
+ case 11: return 13;
+ case 14: return 16;
+ case 17: return 19;
+ default: return 1;
+ }
+}
+
+static void shop_step(bool armor) {
+ if (pressed(UPS)) g.menu = (uint8_t)((g.menu + 2) % 3);
+ if (pressed(DOWNS)) g.menu = (uint8_t)((g.menu + 1) % 3);
+ if (pressed(K_BACK)) {
+ save_file();
+ go(SC_WORLD);
+ return;
+ }
+ if (!pressed(OKS)) return;
+ if (armor) { /* the armor shop: Reinforced, Steel, Titanium */
+ static const uint16_t PRICE[3] = {250, 1500, 9000};
+ static const uint8_t VALUE[3] = {1, 2, 10};
+ int i = g.menu;
+ if (!g.f.armor_have[i + 1] && g.f.tokens >= PRICE[i]) {
+ g.f.tokens -= PRICE[i];
+ g.f.armor = VALUE[i];
+ for (int k = 1; k <= i + 1; k++) g.f.armor_have[k] = 1;
+ g.dirty = 1;
+ }
+ } else {
+ int id = shop_first(g.shop_kind) + g.menu;
+ if (!g.f.byte_have[id] && g.f.tokens >= BYTE_PRICE[id]) {
+ g.f.tokens -= BYTE_PRICE[id];
+ g.f.byte_have[id] = 1;
+ g.dirty = 1;
+ }
+ }
+}
+
+static void shop_band(bool armor) {
+ pic_part(PIC_MENU, 0, 0, 0, 0, 320, 240);
+ gfx_blend(0, 0, 320, 240, BLACK, 14);
+ gfx_text_c(FONT_BIG, 160, 6, armor ? "Mendo's Armor" : "Lolbit's Byte Store", WHITE);
+ static const char *const DESC[8] = {"These Bytes shoot stingers at enemies for extra damage!",
+ "These Medpods will heal you during battles!",
+ "These Reapers have a chance to instantly kill enemies!",
+ "These UFO's shoot lasers for very high damage!",
+ "These Shields block base damage from all attacks!",
+ "These Bombs detonate once per battle for instant damage!",
+ "These Eyebots work on bosses and steadily drain their life!", ""};
+ int first = shop_first(g.shop_kind);
+ for (int i = 0; i < 3; i++) {
+ int y = 48 + 40 * i;
+ const char *name;
+ uint32_t price;
+ bool sold;
+ if (armor) {
+ static const char *const AN[3] = {"Reinforced", "Steel", "Titanium"};
+ static const uint16_t AP[3] = {250, 1500, 9000};
+ name = AN[i], price = AP[i], sold = g.f.armor_have[i + 1];
+ } else {
+ name = BYTE_NAME[first + i], price = BYTE_PRICE[first + i], sold = g.f.byte_have[first + i];
+ }
+ gfx_fill(50, y, 220, 34, g.menu == i ? RGB(0x3A58B8) : RGB(0x1A2858));
+ if (g.menu == i) gfx_frame_rect(49, y - 1, 222, 36, HILITE);
+ if (!armor) pic_draw(ANIM_PICS[ANIMS[AN_BYTE1 + first + i - 1].first], 72, y + 17);
+ gfx_text(FONT_TEXT, 96, y + 3, name, WHITE);
+ char s[24];
+ if (sold) strcpy(s, "Sold out");
+ else num(s, (int32_t)price), strcat(s, " tokens");
+ gfx_text(FONT_SMALL, 96, y + 19, s, sold ? RGB(0x90A0C0) : RGB(0xFFD040));
+ }
+ if (!armor) {
+ int d = first == 1 ? 0 : first == 4 ? 1 : first == 7 ? 2 : first == 10 ? 3 : first == 13 ? 4 : first == 16 ? 5 : 6;
+ gfx_text_c(FONT_SMALL, 160, 172, DESC[d], WHITE);
+ } else
+ gfx_text_c(FONT_SMALL, 160, 172, "Armor takes damage off every hit.", WHITE);
+ char s[32];
+ num(s, (int32_t)g.f.tokens);
+ strcat(s, " Faz Tokens");
+ gfx_text_c(FONT_TEXT, 160, 194, s, RGB(0xFFD040));
+ gfx_blend(0, 226, 320, 14, BLACK, 18);
+ gfx_text(FONT_SMALL, 4, 227, "Arrows pick OK buy Back leave", KEYS);
+}
+
+/* ------------------------------------------------------------------ how to play, game over */
+static void howto_band(void) {
+ pic_part(PIC_MENU, 0, 0, 0, 0, 320, 240);
+ gfx_blend(0, 0, 320, 240, BLACK, 20);
+ gfx_text_c(FONT_BIG, 160, 4, "How to play", WHITE);
+ static const char *const L[] = {
+ "Walk the map with the arrows. Enemies jump",
+ "you as you walk. Chests hold chips.",
+ "In battle each member charges up. When one",
+ "is ready, pick an attack with the arrows",
+ "and OK (or 1, 2, 3). The other row of four",
+ "comes in with the backspace key. Hold 0 to",
+ "run. Win for exp, levels and Faz Tokens.",
+ "Spend tokens at Lolbit's for bytes, at",
+ "Mendo's for armor. Wear chips and bytes",
+ "from the menu (Back). Beat challengers to",
+ "get new members.",
+ };
+ for (unsigned i = 0; i < sizeof L / sizeof L[0]; i++) gfx_text(FONT_SMALL, 10, 32 + 16 * (int)i, L[i], WHITE);
+ gfx_blend(0, 226, 320, 14, BLACK, 18);
+ gfx_text(FONT_SMALL, 4, 227, "Back go back", KEYS);
+}
+
+static void gameover_band(void) {
+ gfx_fill(0, gfx_y0, 320, BAND_H, BLACK);
+ gfx_text_c(FONT_HUGE, 160, 90, "GAME OVER", RGB(0xE03030));
+ if (g.t > 60) gfx_text_c(FONT_SMALL, 160, 140, "OK go on", KEYS);
+}
+
+/* ------------------------------------------------------------------ the steps */
+void game_step(uint32_t keys) {
+ g.pressed = keys & ~g.keys;
+ g.keys = keys;
+ g.t++;
+ g.now += 50;
+ if (pressed(K_HOME)) { /* Home: keep it all and quit */
+ if (g.scene != SC_TITLE && g.scene != SC_FILES && g.f.started) {
+ if (g.scene == SC_WORLD || g.scene == SC_SHOP || g.scene == SC_ARMOR) world_save_pos();
+ save_file();
+ }
+ g.running = false;
+ return;
+ }
+ switch (g.scene) {
+ case SC_TITLE:
+ if (pressed(OKS)) {
+ go(SC_FILES);
+ for (int i = 0; i < 3; i++) save_summary(i + 1, &summary[i].mode, &summary[i].diff, &summary[i].h, &summary[i].m, &summary[i].st);
+ }
+ if (pressed(K_BACK)) g.running = false;
+ break;
+ case SC_FILES: files_step(); break;
+ case SC_PARTY: party_step(); break;
+ case SC_WORLD:
+ if (pressed(K_BACK)) {
+ g.back = SC_WORLD;
+ go(SC_PAUSE);
+ break;
+ }
+ world_step();
+ if (g.t % 1800 == 0) world_save_pos(), save_file(); /* now and then */
+ break;
+ case SC_BATTLE:
+ if (pressed(K_BACK)) {
+ g.back = SC_BATTLE;
+ go(SC_PAUSE);
+ break;
+ }
+ battle_keys(g.pressed, g.keys);
+ battle_step();
+ if (!g.b.on && g.scene == SC_BATTLE) {
+ world_after_battle();
+ save_file();
+ go(SC_WORLD);
+ }
+ break;
+ case SC_PAUSE: pause_step(); break;
+ case SC_WARP: warp_step(); break;
+ case SC_CHIPS: wear_step(false); break;
+ case SC_BYTES: wear_step(true); break;
+ case SC_SHOP: shop_step(false); break;
+ case SC_ARMOR: shop_step(true); break;
+ case SC_HOWTO:
+ if (pressed(K_BACK) || pressed(OKS)) go(SC_PAUSE), g.menu = P_HOWTO;
+ break;
+ case SC_GAMEOVER: /* (the frame "game over", then the start again) */
+ if (g.t > 60 && pressed(OKS)) {
+ save_file();
+ world_enter();
+ go(SC_WORLD);
+ }
+ break;
+ }
+ if (g.dirty && g.t % 600 == 0 && g.f.started) save_file();
+}
+
+static void scene_band(void) {
+ switch (g.scene) {
+ case SC_TITLE: title_band(); break;
+ case SC_FILES: files_band(); break;
+ case SC_PARTY: party_band(); break;
+ case SC_PAUSE: pause_band(); break;
+ case SC_WARP: warp_band(); break;
+ case SC_CHIPS: wear_band(false); break;
+ case SC_BYTES: wear_band(true); break;
+ case SC_SHOP: shop_band(false); break;
+ case SC_ARMOR: shop_band(true); break;
+ case SC_HOWTO: howto_band(); break;
+ case SC_GAMEOVER: gameover_band(); break;
+ }
+}
+
+void game_draw(void) {
+ if (g.scene == SC_WORLD) world_draw();
+ else if (g.scene == SC_BATTLE) battle_draw();
+ else {
+ world_prepare_view();
+ battle_prepare_view();
+ gfx_frame(scene_band);
+ }
+}
diff --git a/games/fnafworld/src/game.h b/games/fnafworld/src/game.h
new file mode 100644
index 00000000..32402710
--- /dev/null
+++ b/games/fnafworld/src/game.h
@@ -0,0 +1,244 @@
+/* FNAF World: the game's state and its parts.
+ *
+ * game.c: the scenes around the map (the title, the files, the party, the pause menu, chips and bytes, the shops,
+ * game over) and the keys. world.c: the overworld (walking, the areas, encounters, chests, switches, bosses, jumps).
+ * battle.c: a battle as the game's events run it (rules.c: its numbers). save.c: the files. The game's names for its
+ * objects and counters are kept in the comments, with its event numbers (gamesrc spec/overworld_events.txt). */
+#ifndef FNAFW_GAME_H
+#define FNAFW_GAME_H
+#include <stdbool.h>
+#include <stdint.h>
+
+#define NCHAR 48 /* the characters, 1 to 48 */
+#define NCHIP 21
+#define NBYTE 21
+#define NSWITCH 9
+#define NCHEST 21
+
+/* a file (the game's Ini "fnafw1" to "fnafw3") */
+typedef struct {
+ uint8_t started, mode, diff; /* mode 1 Adventure, 2 Fixed Party; diff 1 Normal, 2 Hard */
+ uint8_t locked; /* the party is fixed ('locked') */
+ uint8_t have[NCHAR + 1]; /* 'Nhave' */
+ uint8_t lv[NCHAR + 1]; /* 'Nlv' (shown plus one) */
+ uint32_t next[NCHAR + 1]; /* 'Nnext': exp toward the next level */
+ uint8_t slot[8]; /* 's1' to 's8': the party, two rows of four */
+ uint32_t tokens;
+ uint8_t chest[NCHEST + 1]; /* 'cN': chest N opened, its chip found */
+ uint8_t chip[4]; /* 'active1' to 'active4': the chips worn */
+ uint8_t byte_have[NBYTE + 1]; /* 'pN' */
+ uint8_t bytes[4]; /* 'active1b' to 'active4b' */
+ uint8_t armor; /* 'armor': 0, 1, 2 or 10 */
+ uint8_t armor_have[4]; /* 'ar1' to 'ar3' */
+ uint8_t sw[NSWITCH + 1]; /* 'sw1' to 'sw9' */
+ uint8_t key, w3; /* the key; the third jump ('w3') */
+ uint8_t resetpos; /* lost: start again at the start */
+ int16_t x, y; /* 'x', 'y': where on the map (0: the start) */
+ uint8_t area;
+ uint8_t hours, minutes, seconds;
+ uint8_t beat[8]; /* 'beatgame1' to 'beatgame7' */
+} File;
+
+/* the overworld */
+typedef struct {
+ int16_t x, y; /* "8bit hitbox", the game's coordinates */
+ uint8_t dir; /* 0 right, 1 up, 2 left, 3 down */
+ uint8_t walking; /* "8bit hitbox" A */
+ uint16_t img; /* the walker's picture counter */
+ uint16_t grace; /* "8bit hitbox" B: frames without encounters */
+ uint8_t area; /* "area" */
+ uint8_t boss_won[24]; /* the bosses beaten since the map was loaded (their objects' A) */
+ uint8_t note; /* a message shown: N_* */
+ uint16_t note_t;
+ uint8_t note_n; /* (its chip, ...) */
+ uint32_t enc_t, sec_t; /* the encounter's every 2000 ms; the play clock */
+ uint8_t warp_menu, warp_sel;
+} World;
+
+/* an enemy ("target") */
+typedef struct {
+ uint8_t alive;
+ uint8_t an; /* its animation (AN_*) */
+ uint8_t img, cnt; /* the picture, the speed counter */
+ int16_t x, y; /* the game's 800 x 480 battle */
+ int16_t px, py; /* (its path: node, progress) */
+ uint8_t path, node;
+ int16_t node_t;
+ int32_t hurt; /* B... "target" L (s11): the damage taken, below 0 */
+ int32_t dmg; /* "target" A (s0): damage to take this frame */
+ int16_t speed; /* "target" C (s2) */
+ uint8_t s3; /* poisoned look */
+ int16_t s4; /* attacking: frames */
+ uint8_t s5; /* hit: blinks */
+ uint8_t s9; /* its hit is coming */
+ uint8_t s12; /* munchies to come */
+ int16_t s15; /* poison ticks */
+ int16_t s18; /* haunted: seconds */
+ uint8_t s19; /* bitten */
+ int16_t s20, s21; /* unscrew, unscrew 2 */
+ int16_t s25; /* the roll for an instant end */
+ uint8_t s7, s8, s17, s24;
+ uint8_t s23; /* status arrows to show */
+} Enemy;
+
+/* an effect on screen: the game's objects made by attacks (FX_*) */
+typedef struct {
+ uint8_t kind, an, img, cnt, plays, done;
+ int16_t x, y, vx, vy; /* (x, y in 1/16 pixels of the game's battle) */
+ int16_t t, a, b; /* its counters (the object's A, B...) */
+ int8_t target; /* an enemy, -1 none */
+} Fx;
+
+#define NFX 40
+
+typedef struct {
+ uint8_t on; /* "battle" */
+ uint8_t boss; /* "boss": 0 or the boss's number */
+ uint8_t chal; /* "Active 26" B: 2 in a challenger's battle; chal_c its character */
+ uint8_t chal_c, chal_roll, chal_banner, chal_won, chal_have;
+ uint8_t etype; /* "enemy type" */
+ uint8_t count; /* "make character" S: how many enemies came */
+ uint8_t row; /* "load row" 1 or 2 */
+ uint8_t stage; /* "victory stage" */
+ int32_t life[8], life_max[8]; /* "life p 1" to 8 */
+ uint8_t charge[8];
+ uint8_t ready; /* the slot (1 to 4) whose attacks show, 0 none */
+ uint8_t sel; /* the attack picked (0 to 2) */
+ uint8_t ready_turn; /* "ready for turn" */
+ uint8_t moving; /* "movement?" */
+ /* the party on the field */
+ struct { int16_t x, y; uint8_t an, img, cnt, state; int16_t t; uint8_t node; } pm[4];
+ uint8_t att_slot; /* "what character attacked" (its slot 1-4), 0 none */
+ uint8_t used; /* "used attack" */
+ uint8_t att_img, att_cnt, att_plays, att_an; /* the "attack" object */
+ uint8_t att_frame_done; /* (the picture whose effect was made) */
+ int16_t cur_level; /* "current level" */
+ int16_t multiplier;
+ int16_t atk_boost, def_boost, spd_boost; /* seconds */
+ int16_t shield, shield2, gift[4];
+ int16_t pwr_down, spd_down, spd_down2, pwr_cloud, pwr_cloud_t; /* "pwr down icon" A, "spd down icon" A... */
+ int16_t stunned;
+ int32_t heal[4], healed;
+ int16_t regen, regen_n; /* "value" R, S */
+ uint8_t party_flash;
+ int32_t enemy_max, boss_life, boss_speed, boss_strength, strength, special_strength;
+ uint8_t special, special_chance; /* "enemy attack" A (its kind) */
+ int16_t special_t; /* "enemy attack" B */
+ uint8_t special_go;
+ int16_t poison_all, confuse, hose, screw_t, screw_who, cheese, wall_t, special18;
+ uint8_t attacked_who;
+ uint8_t hit_slot; /* (the member the last hit landed on, for its effect) */
+ int32_t exp, tokens; /* "exp earned", "tokens" */
+ int16_t vt0, vt1, vt2; /* "victory" A, B, C */
+ uint8_t leveled[8];
+ uint8_t team_ok[2];
+ uint8_t running, run_luck;
+ uint8_t chip_flags; /* the chips' "chip settings" switches */
+ int16_t quick_t; /* Quickstart: frames the enemies wait */
+ uint8_t comet; /* Evercomet: chance in 10 */
+ uint8_t counter_bite, pizza_fury, freddle_fury, block_confuse, block_unscrew;
+ uint8_t bomb_used;
+ int16_t shake, flash; /* "follow 1" A, "flashhit" A */
+ uint8_t mimic, mimic_attack;
+ int16_t mimic_t;
+ int16_t endo_t;
+ int16_t hj_t, hj_kind, hj_level; /* a happy jam playing */
+ int16_t cup_t, cup_level; /* Cupcake's "value" A */
+ int16_t favors_t, favors_level;
+ int16_t cheese_t, cheese_pow; /* "value" D, E (hot cheese) */
+ int16_t popper_n, popper_pow, poppers_t, poppers_on, poppers_wait;
+ int16_t stars, stars2, star_pow; /* "switch parties" S, T, U */
+ int16_t pizzas, pizzas2, freddles, pizza_pow, pizza2_pow, freddle_pow;
+ int16_t newnums0, newnums1, newnums2;
+ uint8_t dark, dark_kind, mystery, mystery_kind, mystery_t;
+ uint8_t lost, won;
+ uint8_t slots[8]; /* the party as it was ("slot 1" to 8 come back from the file: 1167) */
+ uint32_t step; /* frames since it began */
+ uint32_t timers[40]; /* the "every" timers: when each fires next (1/3 ms) */
+ int16_t leave_t; /* the row leaving, then the other comes */
+ Enemy en[4];
+ Fx fx[NFX];
+} Battle;
+
+enum {
+ SC_TITLE, SC_FILES, SC_PARTY, SC_WORLD, SC_BATTLE, SC_PAUSE, SC_CHIPS, SC_BYTES, SC_SHOP, SC_ARMOR,
+ SC_GAMEOVER, SC_HOWTO, SC_WARP
+};
+
+typedef struct {
+ bool running;
+ uint8_t scene, back; /* back: the scene a menu returns to */
+ uint32_t t; /* frames in the scene */
+ uint32_t keys, pressed, held_t;
+ uint8_t menu, sub, menu2;
+ uint8_t slot; /* the file (1 to 3) */
+ uint8_t dirty;
+ File f;
+ World w;
+ Battle b;
+ uint8_t pick; /* the party select's cursor (0..47), the slot being set (0..7) */
+ uint8_t pick_slot, pick_mode;
+ uint8_t shop_kind; /* "what shop" */
+ uint8_t confirm;
+ uint32_t now; /* the game's clock: thirds of a millisecond, 50 a frame */
+} Game;
+
+extern Game g;
+
+uint32_t rnd(void);
+int rnd_n(int n); /* Clickteam's Random(n): 0 to n - 1 */
+
+void game_init(void);
+void game_step(uint32_t keys);
+void game_draw(void);
+
+/* saves (save.c) */
+void save_file(void);
+bool load_file(int slot, File *f);
+void save_new(int slot);
+void save_restore_copy(void);
+void save_summary(int slot, uint8_t *mode, uint8_t *diff, uint8_t *hours, uint8_t *minutes, bool *started);
+
+/* the overworld (world.c) */
+void world_enter(void);
+void world_step(void);
+void world_draw(void);
+void world_save_pos(void);
+void world_band_dim(void); /* (a band of the map, under menus) */
+void world_prepare_view(void);
+void world_after_battle(void);
+const char *area_name(int area);
+
+/* battles (battle.c) */
+void battle_start(int boss);
+void battle_challenger(int c); /* "A new challenger has appeared!" (1198-1202) */
+void battle_step(void);
+void battle_draw(void);
+void battle_keys(uint32_t pressed, uint32_t held);
+void battle_draw_band_dim(void);
+void battle_prepare_view(void);
+
+/* the numbers (rules.c) */
+extern const char *const CHAR_NAME[NCHAR + 1];
+extern const uint8_t CHAR_ATTACKS[NCHAR + 1][3];
+extern const char *const ATTACK_NAME[61];
+extern const uint8_t ATTACK_COLOUR[61];
+extern const char *const ENEMY_NAME[54];
+extern const char *const BOSS_NAME[20];
+extern const char *const CHIP_NAME[NCHIP + 1];
+extern const char *const BYTE_NAME[NBYTE + 1];
+extern const uint16_t BYTE_PRICE[NBYTE + 1];
+int32_t life_max(int c, int lv);
+int32_t exp_needed(int c, int lv);
+int32_t enemy_life(int type, int diff);
+int32_t challenger_life(int c, int diff);
+int challenger_pick(int area);
+int32_t victory_exp(int count, int type, int boss, int area, int diff);
+int32_t victory_tokens(int count, int type, int boss, int area, int diff);
+int exp_tick(int32_t exp);
+int divisor(bool def_boost, bool shield, bool pwr_down);
+int32_t enemy_strength(int type, int diff, int div, int block, int armor);
+int boss_info(int boss, int diff, int32_t *life, int32_t *speed, int32_t *strength, int *special, int *an);
+int enemy_special(int type);
+int enemy_hit_effect(int type);
+#endif
diff --git a/games/fnafworld/src/gfx.c b/games/fnafworld/src/gfx.c
new file mode 100644
index 00000000..fb987aff
--- /dev/null
+++ b/games/fnafworld/src/gfx.c
@@ -0,0 +1,227 @@
+/* Drawing (gfx.h): a band of 16 rows at a time, then pushed to the screen. */
+#include "gfx.h"
+#include "res.h"
+
+uint16_t *gfx_band;
+int gfx_y0;
+
+void gfx_set_band_memory(uint16_t *m) { gfx_band = m; }
+
+void gfx_frame(void (*draw)(void)) {
+ for (gfx_y0 = 0; gfx_y0 < SCREEN_H; gfx_y0 += BAND_H) {
+ draw();
+ plat_push(0, gfx_y0, SCREEN_W, BAND_H, gfx_band);
+ }
+ gfx_y0 = 0;
+}
+
+uint16_t gfx_mix(uint16_t f, uint16_t b, int a) {
+ uint32_t x = (f | (uint32_t)f << 16) & 0x07E0F81F, y = (b | (uint32_t)b << 16) & 0x07E0F81F;
+ y = (y + ((x - y) * (uint32_t)a >> 5)) & 0x07E0F81F;
+ return (uint16_t)(y | y >> 16);
+}
+
+/* the rectangle's part in this band: rows r0 to r1 of the band, columns x0 to x1 */
+static bool clip(int x, int y, int w, int h, int *x0, int *x1, int *r0, int *r1) {
+ *x0 = x > 0 ? x : 0, *x1 = x + w < SCREEN_W ? x + w : SCREEN_W;
+ int y0 = y > gfx_y0 ? y : gfx_y0, y1 = y + h < gfx_y0 + BAND_H ? y + h : gfx_y0 + BAND_H;
+ *r0 = y0 - gfx_y0, *r1 = y1 - gfx_y0;
+ return *x0 < *x1 && *r0 < *r1;
+}
+
+void gfx_fill(int x, int y, int w, int h, uint16_t c) {
+ int x0, x1, r0, r1;
+ if (!clip(x, y, w, h, &x0, &x1, &r0, &r1)) return;
+ for (int r = r0; r < r1; r++)
+ for (uint16_t *p = gfx_band + r * SCREEN_W + x0, *e = gfx_band + r * SCREEN_W + x1; p < e; p++) *p = c;
+}
+
+void gfx_blend(int x, int y, int w, int h, uint16_t c, int a) {
+ int x0, x1, r0, r1;
+ if (!clip(x, y, w, h, &x0, &x1, &r0, &r1)) return;
+ for (int r = r0; r < r1; r++)
+ for (uint16_t *p = gfx_band + r * SCREEN_W + x0, *e = gfx_band + r * SCREEN_W + x1; p < e; p++)
+ *p = gfx_mix(c, *p, a);
+}
+
+void gfx_frame_rect(int x, int y, int w, int h, uint16_t c) {
+ gfx_fill(x, y, w, 1, c);
+ gfx_fill(x, y + h - 1, w, 1, c);
+ gfx_fill(x, y, 1, h, c);
+ gfx_fill(x + w - 1, y, 1, h, c);
+}
+
+/* static: grey noise, spread out for gfx_mix (made once) */
+static uint32_t noise[2048];
+
+void gfx_static(int x, int y, int w, int h, int a, uint32_t seed) {
+ int x0, x1, r0, r1;
+ if (!clip(x, y, w, h, &x0, &x1, &r0, &r1) || a <= 0) return;
+ if (!noise[0]) {
+ uint32_t s = 0x2545F491u;
+ for (int i = 0; i < 2048; i++) {
+ s ^= s << 13, s ^= s >> 17, s ^= s << 5;
+ uint32_t g = (s >> 24) * 3 / 4;
+ uint32_t c = (g & 0xF8) << 8 | (g & 0xFC) << 3 | g >> 3;
+ noise[i] = ((c | c << 16) & 0x07E0F81F) | 1u << 31; /* (the top bit: made) */
+ }
+ }
+ for (int r = r0; r < r1; r++) {
+ uint32_t s = seed ^ (uint32_t)(gfx_y0 + r) * 0x9E3779B1u;
+ s ^= s >> 15, s *= 0x2C1B3C6Du, s ^= s >> 12;
+ /* a line now and then is brighter, as the game's static has */
+ uint32_t la = (s & 31) == 0 ? (uint32_t)a + 6 : (uint32_t)a;
+ if (la > 32) la = 32;
+ const uint32_t *nz = noise + (s >> 16 & 1023);
+ for (uint16_t *p = gfx_band + r * SCREEN_W + x0, *e = gfx_band + r * SCREEN_W + x1; p < e; p++) {
+ uint32_t n = *nz++ & 0x07E0F81F, b = (*p | (uint32_t)*p << 16) & 0x07E0F81F;
+ b = (b + ((n - b) * la >> 5)) & 0x07E0F81F;
+ *p = (uint16_t)(b | b >> 16);
+ }
+ }
+}
+
+void gfx_dim(int x, int y, int w, int h, int a) {
+ int x0, x1, r0, r1;
+ if (!clip(x, y, w, h, &x0, &x1, &r0, &r1)) return;
+ for (int r = r0; r < r1; r++)
+ for (uint16_t *p = gfx_band + r * SCREEN_W + x0, *e = gfx_band + r * SCREEN_W + x1; p < e; p++) {
+ if (a <= 32) {
+ *p = gfx_mix(*p, BLACK, a);
+ } else { /* brighter: each channel times a / 32, up to 2 */
+ uint32_t v = *p, R = (v >> 11) * (uint32_t)a >> 5, G = (v >> 5 & 63) * (uint32_t)a >> 5, B = (v & 31) * (uint32_t)a >> 5;
+ *p = (uint16_t)((R > 31 ? 31 : R) << 11 | (G > 63 ? 63 : G) << 5 | (B > 31 ? 31 : B));
+ }
+ }
+}
+
+/* ------------------------------------------------------------------ text */
+static const uint8_t *font_at(int font) {
+ const uint8_t *s = section(SEC_FONTS);
+ return s + rd32(s + 4 + 4 * font);
+}
+
+int gfx_line_h(int font) { return font_at(font)[0]; }
+
+/* 4-bit alpha rows (the first pixel in the low half of a byte) in colour c */
+static void alpha_rows(const uint8_t *rows, int w, int h, int x, int y, uint16_t c) {
+ int x0, x1, r0, r1;
+ if (!clip(x, y, w, h, &x0, &x1, &r0, &r1)) return;
+ int stride = (w + 1) >> 1;
+ for (int r = r0; r < r1; r++) {
+ const uint8_t *src = rows + (gfx_y0 + r - y) * stride;
+ uint16_t *d = gfx_band + r * SCREEN_W;
+ for (int px = x0; px < x1; px++) {
+ int i = px - x, a = src[i >> 1] >> ((i & 1) * 4) & 15;
+ if (a) d[px] = a == 15 ? c : gfx_mix(c, d[px], a * 2 + (a >> 3));
+ }
+ }
+}
+
+int gfx_text_n(int font, int x, int y, const char *s, int n, uint16_t c) {
+ const uint8_t *f = font_at(font);
+ int x0 = x;
+ bool here = y < gfx_y0 + BAND_H && y + f[0] > gfx_y0;
+ for (; *s && n-- > 0; s++) {
+ int ch = (uint8_t)*s;
+ if (ch < 32 || ch > 126) ch = '?';
+ const uint8_t *g = f + 4 + 12 * (ch - 32);
+ if (here && g[1]) alpha_rows(f + rd32(g + 8), g[1], g[2], x + (int8_t)g[3], y + (int8_t)g[4], c);
+ x += g[0];
+ }
+ return x - x0;
+}
+
+int gfx_text(int font, int x, int y, const char *s, uint16_t c) { return gfx_text_n(font, x, y, s, 1 << 30, c); }
+
+int gfx_text_wn(int font, const char *s, int n) {
+ const uint8_t *f = font_at(font);
+ int w = 0;
+ for (; *s && n-- > 0; s++) {
+ int ch = (uint8_t)*s;
+ if (ch < 32 || ch > 126) ch = '?';
+ w += f[4 + 12 * (ch - 32)];
+ }
+ return w;
+}
+int gfx_text_w(int font, const char *s) { return gfx_text_wn(font, s, 1 << 30); }
+
+void gfx_text_c(int font, int cx, int y, const char *s, uint16_t c) { gfx_text(font, cx - gfx_text_w(font, s) / 2, y, s, c); }
+void gfx_text_r(int font, int rx, int y, const char *s, uint16_t c) { gfx_text(font, rx - gfx_text_w(font, s), y, s, c); }
+void gfx_text_s(int font, int x, int y, const char *s, uint16_t c) {
+ gfx_text(font, x + 1, y + 1, s, BLACK);
+ gfx_text(font, x, y, s, c);
+}
+
+/* ------------------------------------------------------------------ small pictures */
+static const uint8_t *img_at(int id) {
+ const uint8_t *s = section(SEC_IMGS);
+ return s + rd32(s + 4 + 4 * id);
+}
+int gfx_img_w(int id) { return (int)rd16(img_at(id)); }
+int gfx_img_h(int id) { return (int)rd16(img_at(id) + 2); }
+
+void gfx_img(int id, int x, int y, uint16_t c) {
+ const uint8_t *p = img_at(id);
+ alpha_rows(p + 8, (int)rd16(p), (int)rd16(p + 2), x, y, c);
+}
+
+/* ------------------------------------------------------------------ the map's pictures (SPRS: tools/world.py) */
+static const uint8_t *spr_at(int id) {
+ const uint8_t *s = section(SEC_SPRS);
+ return s + rd32(s + 4 + 4 * id);
+}
+int gfx_spr_w(int id) { return (int)rd16(spr_at(id)); }
+int gfx_spr_h(int id) { return (int)rd16(spr_at(id) + 2); }
+int gfx_spr_hx(int id) { return (int)rds16(spr_at(id) + 4); }
+int gfx_spr_hy(int id) { return (int)rds16(spr_at(id) + 6); }
+
+/* sprite id with its top left corner at (x, y) */
+void gfx_spr(int id, int x, int y) {
+ const uint8_t *p = spr_at(id);
+ int w = (int)rd16(p), h = (int)rd16(p + 2), opaque = p[8] & 1;
+ int r0 = gfx_y0 - y, r1 = gfx_y0 + BAND_H - y;
+ if (r0 < 0) r0 = 0;
+ if (r1 > h) r1 = h;
+ int c0 = x < 0 ? -x : 0, c1 = x + w > SCREEN_W ? SCREEN_W - x : w;
+ if (r0 >= r1 || c0 >= c1) return;
+ const uint16_t *px = (const uint16_t *)(const void *)(p + 12);
+ const uint8_t *al = p + 12 + 2 * w * h;
+ int stride = (w + 1) >> 1;
+ for (int r = r0; r < r1; r++) {
+ const uint16_t *s = px + r * w;
+ uint16_t *d = gfx_band + (y + r - gfx_y0) * SCREEN_W + x;
+ if (opaque) {
+ for (int c = c0; c < c1; c++) d[c] = s[c];
+ continue;
+ }
+ const uint8_t *a = al + r * stride;
+ for (int c = c0; c < c1; c++) {
+ int v = a[c >> 1] >> ((c & 1) * 4) & 15;
+ if (v == 15) d[c] = s[c];
+ else if (v) d[c] = gfx_mix(s[c], d[c], v * 2 + (v >> 3));
+ }
+ }
+}
+
+/* an opaque sprite tiled over the rectangle (x, y, w, h), the tiles from (tx, ty) */
+void gfx_spr_tile(int id, int x, int y, int w, int h, int tx, int ty) {
+ const uint8_t *p = spr_at(id);
+ int sw = (int)rd16(p), sh = (int)rd16(p + 2);
+ int y0 = y > gfx_y0 ? y : gfx_y0, y1 = y + h < gfx_y0 + BAND_H ? y + h : gfx_y0 + BAND_H;
+ int x0 = x > 0 ? x : 0, x1 = x + w < SCREEN_W ? x + w : SCREEN_W;
+ if (y0 >= y1 || x0 >= x1) return;
+ const uint16_t *px = (const uint16_t *)(const void *)(p + 12);
+ for (int r = y0; r < y1; r++) {
+ int sr = (r - ty) % sh;
+ if (sr < 0) sr += sh;
+ const uint16_t *s = px + sr * sw;
+ uint16_t *d = gfx_band + (r - gfx_y0) * SCREEN_W;
+ int sc = (x0 - tx) % sw;
+ if (sc < 0) sc += sw;
+ for (int c = x0; c < x1; c++) {
+ d[c] = s[sc];
+ if (++sc == sw) sc = 0;
+ }
+ }
+}
diff --git a/games/fnafworld/src/gfx.h b/games/fnafworld/src/gfx.h
new file mode 100644
index 00000000..70241fd2
--- /dev/null
+++ b/games/fnafworld/src/gfx.h
@@ -0,0 +1,65 @@
+/* FNAF World: drawing, a band of 16 rows at a time.
+ *
+ * The screen is drawn in 15 bands of 320 x 16 pixels (one row of the pictures' 16 x 16 squares): for each
+ * band the scene's whole drawing function runs, everything clipped to the band, then the band is pushed.
+ * So the game needs no frame buffer (it would not fit in the RAM apps get), and a picture's squares are
+ * decoded once each, as the band they fall in is drawn. */
+#ifndef FNAFW_GFX_H
+#define FNAFW_GFX_H
+#include <stdbool.h>
+#include <stdint.h>
+#include "plat.h"
+
+#define BAND_H 16
+#define RGB(c) (uint16_t)((((c) >> 8) & 0xF800) | (((c) >> 5) & 0x07E0) | (((c) >> 3) & 0x1F))
+#define WHITE 0xFFFF
+#define BLACK 0x0000
+
+extern uint16_t *gfx_band; /* SCREEN_W x BAND_H */
+extern int gfx_y0; /* the band's top row */
+void gfx_set_band_memory(uint16_t *m);
+/* draws the frame: draw() once for each band */
+void gfx_frame(void (*draw)(void));
+
+uint16_t gfx_mix(uint16_t f, uint16_t b, int a); /* f over b, a from 0 (b) to 32 (f) */
+void gfx_fill(int x, int y, int w, int h, uint16_t c);
+void gfx_blend(int x, int y, int w, int h, uint16_t c, int a);
+void gfx_frame_rect(int x, int y, int w, int h, uint16_t c);
+/* video noise over a rectangle: a of 32 of the way to grey static; seed changes it each frame */
+void gfx_static(int x, int y, int w, int h, int a, uint32_t seed);
+/* the rectangle a of 32 of the way to black, or brighter (a > 32 up to 64) */
+void gfx_dim(int x, int y, int w, int h, int a);
+
+/* text in data.bin's fonts (FONT_*); returns the width */
+int gfx_text(int font, int x, int y, const char *s, uint16_t c);
+int gfx_text_w(int font, const char *s);
+int gfx_text_n(int font, int x, int y, const char *s, int n, uint16_t c); /* the first n letters */
+int gfx_text_wn(int font, const char *s, int n);
+int gfx_line_h(int font);
+void gfx_text_c(int font, int cx, int y, const char *s, uint16_t c); /* centred on cx */
+void gfx_text_r(int font, int rx, int y, const char *s, uint16_t c); /* ending at rx */
+/* with a 1-pixel dark shadow, for words over pictures */
+void gfx_text_s(int font, int x, int y, const char *s, uint16_t c);
+/* data.bin's small pictures (IMG_*): white (or grey) with alpha, in colour c */
+void gfx_img(int id, int x, int y, uint16_t c);
+int gfx_img_w(int id);
+int gfx_img_h(int id);
+
+/* pictures (pic.c): the whole of one with its hot spot at (x, y) (faded: a of 32), or the part (sx, sy, w, h)
+ * of it with its corner at (x, y) */
+void pic_draw(int id, int x, int y);
+void pic_fade(int id, int x, int y, int a);
+void pic_part(int id, int x, int y, int sx, int sy, int w, int h);
+int pic_w(int id); /* (in squares of 16 pixels, times 16) */
+int pic_h(int id);
+int pic_hx(int id);
+int pic_hy(int id);
+
+/* the map's pictures (SPRS): at their corner (x, y); an opaque one tiled over a rectangle */
+void gfx_spr(int id, int x, int y);
+void gfx_spr_tile(int id, int x, int y, int w, int h, int tx, int ty);
+int gfx_spr_w(int id);
+int gfx_spr_h(int id);
+int gfx_spr_hx(int id);
+int gfx_spr_hy(int id);
+#endif
diff --git a/games/fnafworld/src/icon.png b/games/fnafworld/src/icon.png
new file mode 100644
index 00000000..36de8991
Binary files /dev/null and b/games/fnafworld/src/icon.png differ
diff --git a/games/fnafworld/src/main.c b/games/fnafworld/src/main.c
new file mode 100644
index 00000000..067e90ef
--- /dev/null
+++ b/games/fnafworld/src/main.c
@@ -0,0 +1,46 @@
+/* FNAF World for the NumWorks calculator.
+ *
+ * Inspired by FNAF World by Scott Cawthon, not affiliated with him.
+ * Made by Mason Chen as part of NumPlay. */
+#include "game.h"
+#include "gfx.h"
+#include "plat.h"
+#include "res.h"
+
+#ifndef HOST
+const char eadk_app_name[] __attribute__((section(".rodata.eadk_app_name"))) = "FNAF World";
+const uint32_t eadk_api_level __attribute__((section(".rodata.eadk_api_level"))) = 0;
+extern const uint8_t fnafw_data[];
+const uint8_t *fnafw_bin;
+
+uint32_t perf_frames __attribute__((used)); /* read by tools/emu.py */
+uint32_t perf_updates __attribute__((used));
+
+int main(void) {
+ uint16_t band[SCREEN_W * BAND_H]; /* (here: on the stack, out of the RAM apps get) */
+ gfx_set_band_memory(band);
+ plat_begin();
+ fnafw_bin = fnafw_data;
+ game_init();
+ uint32_t next = plat_millis() * 3; /* in thirds of a millisecond: 50 a step, 60 steps a second */
+ while (g.running) {
+ /* the game's steps: drawn when caught up (at most 4 steps for a drawing) */
+ int n = 0;
+ uint32_t now = plat_millis() * 3;
+ while ((int32_t)(now - next) >= 0 && n < 4 && g.running) {
+ game_step(plat_keys());
+ perf_updates++;
+ next += 50;
+ n++;
+ }
+ if (!g.running) break;
+ if ((int32_t)(now - next) > 600) next = now; /* far behind: do not rush */
+ if (n) {
+ game_draw();
+ perf_frames++;
+ } else
+ plat_sleep(1);
+ }
+ return plat_end();
+}
+#endif
diff --git a/games/fnafworld/src/pic.c b/games/fnafworld/src/pic.c
new file mode 100644
index 00000000..876a4d68
--- /dev/null
+++ b/games/fnafworld/src/pic.c
@@ -0,0 +1,323 @@
+/* The pictures (tools/codec.py): 16 x 16 squares coded as JPEG codes them, decoded as the bands are drawn.
+ *
+ * A square: four 8 x 8 blocks of Y, one of Cb and one of Cr (at half resolution), each a Huffman-coded
+ * list of quantized cosine coefficients. The inverse transform is libjpeg's "ifast" one (the AAN algorithm,
+ * its scales folded into the quantization tables by tools/pack.py), with a shortcut for the many blocks
+ * that are one flat colour in these dark rooms. Colours are dithered on the way to 16 bits, or the dark
+ * gradients would band. */
+#include "gfx.h"
+#include "res.h"
+
+typedef struct {
+ const uint16_t *lut; /* 9 bits ahead: length << 8 | symbol, 0 when the code is longer */
+ const int32_t *maxcode; /* JPEG's, by length (1 to 17) */
+ const int32_t *valoff;
+ const uint8_t *vals;
+} Huff;
+
+static const uint8_t zigzag[64 + 16] = {
+ 0, 1, 8, 16, 9, 2, 3, 10, 17, 24, 32, 25, 18, 11, 4, 5, 12, 19, 26, 33, 40, 48, 41, 34, 27, 20, 13, 6, 7,
+ 14, 21, 28, 35, 42, 49, 56, 57, 50, 43, 36, 29, 22, 15, 23, 30, 37, 44, 51, 58, 59, 52, 45, 38, 31, 39, 46,
+ 53, 60, 61, 54, 47, 55, 62, 63,
+ 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63 /* (a corrupt run lands here) */
+};
+
+static Huff huff_tab(int k) {
+ const uint8_t *p = section(SEC_HUFF) + 1424 * k;
+ return (Huff){(const uint16_t *)(const void *)p, (const int32_t *)(const void *)(p + 1024),
+ (const int32_t *)(const void *)(p + 1096), p + 1168};
+}
+
+/* ------------------------------------------------------------------ bits */
+typedef struct {
+ const uint8_t *p;
+ uint32_t buf; /* the next bits, from the top */
+ int n;
+} Bits;
+
+static inline void fill(Bits *b) {
+ while (b->n <= 24) {
+ b->buf |= (uint32_t)*b->p++ << (24 - b->n);
+ b->n += 8;
+ }
+}
+static inline uint32_t take(Bits *b, int k) {
+ uint32_t v = b->buf >> (32 - k);
+ b->buf <<= k;
+ b->n -= k;
+ return v;
+}
+static inline int decode(Bits *b, const Huff *h) {
+ fill(b);
+ uint32_t e = h->lut[b->buf >> 23];
+ if (e) {
+ b->buf <<= e >> 8;
+ b->n -= (int)(e >> 8);
+ return (int)(e & 0xFF);
+ }
+ for (int l = 10; l <= 16; l++) {
+ int32_t code = (int32_t)(b->buf >> (32 - l));
+ if (code <= h->maxcode[l]) {
+ b->buf <<= l;
+ b->n -= l;
+ return h->vals[(code + h->valoff[l]) & 0xFF];
+ }
+ }
+ b->buf <<= 16; /* (corrupt: give up on this block) */
+ b->n -= 16;
+ return 0;
+}
+/* JPEG's extension of s bits to a signed value */
+static inline int value(Bits *b, int s) {
+ if (!s) return 0;
+ fill(b);
+ int v = (int)take(b, s);
+ return v < 1 << (s - 1) ? v - (1 << s) + 1 : v;
+}
+
+/* ------------------------------------------------------------------ one block */
+#define CONST_BITS 8
+#define MUL(v, c) (((v) * (c)) >> CONST_BITS)
+#define FIX_1_082392200 277
+#define FIX_1_414213562 362
+#define FIX_1_847759065 473
+#define FIX_2_613125930 669
+
+static inline uint8_t clamp8(int v) { return (uint8_t)(v < 0 ? 0 : v > 255 ? 255 : v); }
+
+/* decodes a block into out (8 x 8 bytes, stride 8); *pred: the DC before it */
+static void block(Bits *b, const Huff *dc, const Huff *ac, int *pred, const uint16_t *q, uint8_t *out) {
+ int32_t c[64];
+ uint64_t cols = 0; /* which coefficients are not 0, a bit each */
+ int s = decode(b, dc);
+ *pred += value(b, s);
+ int dcv = *pred * q[0];
+ for (int k = 1; k < 64;) {
+ int rs = decode(b, ac), r = rs >> 4;
+ s = rs & 15;
+ if (!s) {
+ if (r != 15) break;
+ k += 16;
+ continue;
+ }
+ k += r;
+ if (k > 63) break;
+ int z = zigzag[k++];
+ cols |= (uint64_t)1 << z;
+ c[z] = value(b, s) * q[z];
+ }
+ if (!cols) { /* one colour */
+ uint8_t v = clamp8(((dcv + 16) >> 5) + 128);
+ uint32_t w = v * 0x01010101u;
+ for (int i = 0; i < 16; i++) ((uint32_t *)(void *)out)[i] = w;
+ return;
+ }
+ c[0] = dcv;
+ int32_t ws[64];
+ for (int x = 0; x < 8; x++) { /* columns */
+ int32_t *in = c + x, *o = ws + x;
+#define IN(k) ((cols >> (x + 8 * (k)) & 1) ? in[8 * (k)] : 0)
+ if (!(cols >> 8 & (0x01010101010101ull << x))) {
+ int32_t d = x ? IN(0) : dcv;
+ for (int k = 0; k < 8; k++) o[8 * k] = d;
+ continue;
+ }
+ int32_t t0 = x ? IN(0) : dcv, t1 = IN(2), t2 = IN(4), t3 = IN(6);
+ int32_t t10 = t0 + t2, t11 = t0 - t2, t13 = t1 + t3, t12 = MUL(t1 - t3, FIX_1_414213562) - t13;
+ t0 = t10 + t13, t3 = t10 - t13, t1 = t11 + t12, t2 = t11 - t12;
+ int32_t t4 = IN(1), t5 = IN(3), t6 = IN(5), t7 = IN(7);
+#undef IN
+ int32_t z13 = t6 + t5, z10 = t6 - t5, z11 = t4 + t7, z12 = t4 - t7;
+ t7 = z11 + z13;
+ t11 = MUL(z11 - z13, FIX_1_414213562);
+ int32_t z5 = MUL(z10 + z12, FIX_1_847759065);
+ t10 = MUL(z12, FIX_1_082392200) - z5;
+ t12 = MUL(z10, -FIX_2_613125930) + z5;
+ t6 = t12 - t7, t5 = t11 - t6, t4 = t10 + t5;
+ o[0] = t0 + t7, o[56] = t0 - t7, o[8] = t1 + t6, o[48] = t1 - t6;
+ o[16] = t2 + t5, o[40] = t2 - t5, o[32] = t3 + t4, o[24] = t3 - t4;
+ }
+ for (int y = 0; y < 8; y++) { /* rows: +128 and rounding folded into the first */
+ int32_t *w = ws + 8 * y;
+ uint8_t *o = out + 8 * y;
+ int32_t w0 = w[0] + (128 << 5) + 16;
+ int32_t t10 = w0 + w[4], t11 = w0 - w[4], t13 = w[2] + w[6], t12 = MUL(w[2] - w[6], FIX_1_414213562) - t13;
+ int32_t t0 = t10 + t13, t3 = t10 - t13, t1 = t11 + t12, t2 = t11 - t12;
+ int32_t z13 = w[5] + w[3], z10 = w[5] - w[3], z11 = w[1] + w[7], z12 = w[1] - w[7];
+ int32_t t7 = z11 + z13, t11b = MUL(z11 - z13, FIX_1_414213562), z5 = MUL(z10 + z12, FIX_1_847759065);
+ int32_t t10b = MUL(z12, FIX_1_082392200) - z5, t12b = MUL(z10, -FIX_2_613125930) + z5;
+ int32_t t6 = t12b - t7, t5 = t11b - t6, t4 = t10b + t5;
+ o[0] = clamp8((t0 + t7) >> 5), o[7] = clamp8((t0 - t7) >> 5);
+ o[1] = clamp8((t1 + t6) >> 5), o[6] = clamp8((t1 - t6) >> 5);
+ o[2] = clamp8((t2 + t5) >> 5), o[5] = clamp8((t2 - t5) >> 5);
+ o[4] = clamp8((t3 + t4) >> 5), o[3] = clamp8((t3 - t4) >> 5);
+ }
+}
+
+/* ------------------------------------------------------------------ one square */
+#if defined(__ARM_FEATURE_SAT)
+#include <arm_acle.h>
+#define SAT8(v) __usat(v, 8)
+#else
+#define SAT8(v) ((v) < 0 ? 0 : (v) > 255 ? 255 : (v))
+#endif
+/* a 4 x 4 ordered dither: what is added to red and blue (0 to 7) and green (0 to 3) before they lose bits */
+static const uint8_t dither_rb[4][4] = {{0, 4, 1, 5}, {6, 2, 7, 3}, {1, 5, 0, 4}, {7, 3, 6, 2}};
+static const uint8_t dither_g[4][4] = {{0, 2, 0, 2}, {3, 1, 3, 1}, {0, 2, 0, 2}, {3, 1, 3, 1}};
+
+/* decodes the square at data into dst (16 x 16, rows stride apart) */
+static void square(const uint8_t *data, int qset, uint16_t *dst, int stride) {
+ static Huff h[4];
+ static const uint8_t *loaded;
+ if (loaded != fnafw_bin) {
+ for (int k = 0; k < 4; k++) h[k] = huff_tab(k);
+ loaded = fnafw_bin;
+ }
+ const uint16_t *qy = (const uint16_t *)(const void *)(section(SEC_QUANT) + 256 * qset), *qc = qy + 64;
+ uint8_t y[4][64] __attribute__((aligned(4))), cb[64] __attribute__((aligned(4))), cr[64] __attribute__((aligned(4)));
+ Bits b = {data, 0, 0};
+ int pred = 0;
+ for (int k = 0; k < 4; k++) block(&b, &h[0], &h[1], &pred, qy, y[k]);
+ pred = 0;
+ block(&b, &h[2], &h[3], &pred, qc, cb);
+ pred = 0;
+ block(&b, &h[2], &h[3], &pred, qc, cr);
+ for (int rp = 0; rp < 8; rp++) { /* two rows at a time, sharing their colours */
+ int dr[8], dg[8], db[8];
+ for (int c = 0; c < 8; c++) {
+ int u = cb[rp * 8 + c] - 128, v = cr[rp * 8 + c] - 128;
+ dr[c] = (91881 * v + 32768) >> 16;
+ dg[c] = (-22554 * u - 46802 * v + 32768) >> 16;
+ db[c] = (116130 * u + 32768) >> 16;
+ }
+ for (int r = 2 * rp; r < 2 * rp + 2; r++) {
+ const uint8_t *yl = y[(r >> 3) * 2] + (r & 7) * 8, *drb = dither_rb[r & 3], *dgg = dither_g[r & 3];
+ uint16_t *o = dst + r * stride;
+ for (int c = 0; c < 16; c++) {
+ if (c == 8) yl = y[(r >> 3) * 2 + 1] + (r & 7) * 8;
+ int l = yl[c & 7], k = c >> 1;
+ int R = SAT8(l + dr[k] + drb[c & 3]), G = SAT8(l + dg[k] + dgg[c & 3]), B = SAT8(l + db[k] + drb[(c + 2) & 3]);
+ o[c] = (uint16_t)((R & 0xF8) << 8 | (G & 0xFC) << 3 | B >> 3);
+ }
+ }
+ }
+}
+
+/* ------------------------------------------------------------------ pictures */
+typedef struct {
+ int mw, mh, q, hx, hy;
+ const uint8_t *table, *base_table; /* base_table: the picture whose squares it shares, or NULL */
+ const uint8_t *mask; /* its mask (tools/pics.py), or NULL */
+ int count; /* its own squares then */
+} Info;
+
+static Info info(int id) {
+ const uint8_t *p = section(SEC_PICS) + 16 * id, *t = section(SEC_TABLE);
+ Info i = {p[0], p[1], p[2], (int)rds16(p + 4), (int)rds16(p + 6), t + rd32(p + 12), NULL, NULL, (int)rd16(p + 10)};
+ if (p[3] & 1) {
+ i.mask = section(SEC_MASK) + rd32(i.table);
+ i.table += 4;
+ }
+ uint32_t base = rd16(p + 8);
+ if (base != 0xFFFF) {
+ const uint8_t *b = section(SEC_PICS) + 16 * base;
+ i.base_table = t + rd32(b + 12) + (b[3] & 1 ? 4 : 0);
+ }
+ return i;
+}
+
+static uint32_t square_at(const Info *i, int k) {
+ if (!i->base_table) return rd24(i->table + 3 * k);
+ int lo = 0, hi = i->count - 1;
+ while (lo <= hi) {
+ int mid = (lo + hi) >> 1, mk = (int)rd16(i->table + 5 * mid);
+ if (mk == k) return rd24(i->table + 5 * mid + 2);
+ if (mk < k) lo = mid + 1;
+ else hi = mid - 1;
+ }
+ return rd24(i->base_table + 3 * k);
+}
+
+int pic_w(int id) { return 16 * section(SEC_PICS)[16 * id]; }
+int pic_h(int id) { return 16 * section(SEC_PICS)[16 * id + 1]; }
+int pic_hx(int id) { return (int)rds16(section(SEC_PICS) + 16 * id + 4); }
+int pic_hy(int id) { return (int)rds16(section(SEC_PICS) + 16 * id + 6); }
+
+/* the mask's rows in this band, as levels 0 to 3, a byte a pixel */
+static uint8_t alpha[BAND_H][SCREEN_W];
+
+/* the part (sx, sy, w, h) of a picture with its top left corner at (x, y), fade of 32 */
+static void draw_part(const Info *in, int x, int y, int sx, int sy, int w, int h, int fade) {
+ /* clip to the screen, the band and the picture */
+ if (sx + w > in->mw * 16) w = in->mw * 16 - sx;
+ if (sy + h > in->mh * 16) h = in->mh * 16 - sy;
+ int x0 = x > 0 ? x : 0, x1 = x + w < SCREEN_W ? x + w : SCREEN_W;
+ int y0 = y > gfx_y0 ? y : gfx_y0, y1 = y + h < gfx_y0 + BAND_H ? y + h : gfx_y0 + BAND_H;
+ if (x0 >= x1 || y0 >= y1) return;
+ const uint8_t *bank = section(SEC_BANK);
+ uint16_t px[256];
+ /* in the picture: rows y0 - y + sy to y1 - y + sy, columns likewise */
+ int pr0 = y0 - y + sy, pr1 = y1 - y + sy, pc0 = x0 - x + sx, pc1 = x1 - x + sx;
+ if (in->mask) {
+ int W = in->mw * 16;
+ for (int r = pr0; r < pr1; r++) {
+ const uint8_t *m = in->mask + rd16(in->mask + 2 * (r >> 4));
+ for (int k = r & ~15; k < r; k++) /* (the rows before it in its row of squares) */
+ for (int c = 0; c < W; c += (*m++ & 63) + 1) {}
+ uint8_t *a = alpha[r - pr0];
+ for (int c = 0; c < pc1;) {
+ int v = *m >> 6, n = (*m++ & 63) + 1;
+ int s = c > pc0 ? c : pc0, e = c + n < pc1 ? c + n : pc1;
+ for (int k = s; k < e; k++) a[k - pc0] = (uint8_t)v;
+ c += n;
+ }
+ }
+ }
+ for (int my = pr0 >> 4; my <= (pr1 - 1) >> 4 && my < in->mh; my++)
+ for (int mx = pc0 >> 4; mx <= (pc1 - 1) >> 4 && mx < in->mw; mx++) {
+ uint32_t off = square_at(in, my * in->mw + mx);
+ if (off == 0xFFFFFF) continue;
+ const uint8_t *data = bank + off;
+ int r0 = my * 16 > pr0 ? my * 16 : pr0, r1 = my * 16 + 16 < pr1 ? my * 16 + 16 : pr1;
+ int c0 = mx * 16 > pc0 ? mx * 16 : pc0, c1 = mx * 16 + 16 < pc1 ? mx * 16 + 16 : pc1;
+ if (!in->mask && fade >= 32 && r1 - r0 == 16 && c1 - c0 == 16) { /* all of it shows: into the band */
+ square(data, in->q, gfx_band + (r0 - sy + y - gfx_y0) * SCREEN_W + (c0 - sx + x), SCREEN_W);
+ continue;
+ }
+ square(data, in->q, px, 16);
+ for (int r = r0; r < r1; r++) {
+ uint16_t *d = gfx_band + (r - sy + y - gfx_y0) * SCREEN_W + (c0 - sx + x);
+ const uint16_t *s = px + (r - my * 16) * 16 + (c0 - mx * 16);
+ if (!in->mask) {
+ if (fade >= 32)
+ for (int c = c0; c < c1; c++) *d++ = *s++;
+ else
+ for (int c = c0; c < c1; c++, d++) *d = gfx_mix(*s++, *d, fade);
+ continue;
+ }
+ const uint8_t *a = alpha[r - pr0] + (c0 - pc0);
+ for (int c = c0; c < c1; c++, d++, s++) {
+ int v = *a++;
+ if (!v) continue;
+ int f = v == 3 ? fade : v * 11 * fade >> 5;
+ *d = f >= 32 ? *s : gfx_mix(*s, *d, f);
+ }
+ }
+ }
+}
+
+void pic_part(int id, int x, int y, int sx, int sy, int w, int h) {
+ Info in = info(id);
+ draw_part(&in, x, y, sx, sy, w, h, 32);
+}
+
+void pic_draw(int id, int x, int y) {
+ Info in = info(id);
+ draw_part(&in, x - in.hx, y - in.hy, 0, 0, in.mw * 16, in.mh * 16, 32);
+}
+
+void pic_fade(int id, int x, int y, int a) {
+ if (a <= 0) return;
+ Info in = info(id);
+ draw_part(&in, x - in.hx, y - in.hy, 0, 0, in.mw * 16, in.mh * 16, a > 32 ? 32 : a);
+}
diff --git a/games/fnafworld/src/plat.h b/games/fnafworld/src/plat.h
new file mode 100644
index 00000000..7c1d5c15
--- /dev/null
+++ b/games/fnafworld/src/plat.h
@@ -0,0 +1,42 @@
+/* FNAF World: the platform (the calculator, or a computer for tests).
+ *
+ * plat_eadk.c: the calculator's EADK display, keyboard, time and files.
+ * plat_host.c: a frame buffer that tests save as images, scripted keys and
+ * simulated time (tests/play.c). */
+#ifndef FNAFW_PLAT_H
+#define FNAFW_PLAT_H
+#include <stdbool.h>
+#include <stddef.h>
+#include <stdint.h>
+
+#define SCREEN_W 320
+#define SCREEN_H 240
+
+/* keys held now, as bits */
+enum {
+ K_LEFT = 1 << 0, K_RIGHT = 1 << 1, K_UP = 1 << 2, K_DOWN = 1 << 3,
+ K_OK = 1 << 4, /* OK */
+ K_BACK = 1 << 5, /* Back: pause */
+ K_HOME = 1 << 6, /* Home, On/Off: keep the moment and quit */
+ K_DEL = 1 << 7, /* backspace: switch the party's rows */
+ K_0 = 1 << 8, /* the digits: K_0 << n */
+ K_EXE = 1 << 18, /* EXE: as OK */
+ K_ANY = 1 << 19
+};
+#define K_DIGIT(n) (K_0 << (n))
+uint32_t plat_keys(void);
+uint32_t plat_millis(void);
+void plat_sleep(uint32_t ms);
+void plat_push(int x, int y, int w, int h, const uint16_t *px);
+bool plat_save(const char *name, const void *data, uint32_t len);
+const uint8_t *plat_load(const char *name, uint32_t *len); /* NULL if absent */
+/* a file of len bytes to write in place (the calculator's storage is RAM): plat_reserve gives its
+ * bytes, plat_reserved says they are written; NULL if there is no room */
+uint8_t *plat_reserve(const char *name, uint32_t len);
+void plat_reserved(const char *name, uint32_t len);
+bool plat_remove(const char *name);
+void plat_begin(void);
+int plat_end(void);
+/* an N0110 or N0115 (216 MHz, the N0120 has 550) */
+bool plat_slow(void);
+#endif
diff --git a/games/fnafworld/src/plat_eadk.c b/games/fnafworld/src/plat_eadk.c
new file mode 100644
index 00000000..52991778
--- /dev/null
+++ b/games/fnafworld/src/plat_eadk.c
@@ -0,0 +1,44 @@
+/* The calculator: EADK display, keyboard, time and files. */
+#include <eadk.h>
+#include "../../common/epsilon_app.h"
+#include "../../common/epsilon_files.h"
+#include "plat.h"
+
+#define KEY(k) ((uint64_t)1 << (k))
+
+uint32_t plat_keys(void) {
+ static const uint8_t digits[10] = {eadk_key_zero, eadk_key_one, eadk_key_two, eadk_key_three, eadk_key_four,
+ eadk_key_five, eadk_key_six, eadk_key_seven, eadk_key_eight, eadk_key_nine};
+ uint64_t k = eadk_keyboard_scan();
+ uint32_t r = 0;
+ if (k & KEY(eadk_key_left)) r |= K_LEFT;
+ if (k & KEY(eadk_key_right)) r |= K_RIGHT;
+ if (k & KEY(eadk_key_up)) r |= K_UP;
+ if (k & KEY(eadk_key_down)) r |= K_DOWN;
+ if (k & KEY(eadk_key_ok)) r |= K_OK;
+ if (k & KEY(eadk_key_exe)) r |= K_EXE;
+ if (k & KEY(eadk_key_back)) r |= K_BACK;
+ if (k & (KEY(eadk_key_home) | KEY(eadk_key_on_off))) r |= K_HOME;
+ if (k & KEY(eadk_key_backspace)) r |= K_DEL;
+ for (int i = 0; i < 10; i++)
+ if (k & KEY(digits[i])) r |= K_DIGIT(i);
+ if (k) r |= K_ANY;
+ return r;
+}
+
+uint32_t plat_millis(void) { return (uint32_t)eadk_timing_millis(); }
+void plat_sleep(uint32_t ms) { eadk_timing_msleep(ms); }
+void plat_push(int x, int y, int w, int h, const uint16_t *px) {
+ eadk_display_push_rect((eadk_rect_t){(uint16_t)x, (uint16_t)y, (uint16_t)w, (uint16_t)h}, px);
+}
+bool plat_save(const char *name, const void *data, uint32_t len) { return ef_write(name, data, len); }
+const uint8_t *plat_load(const char *name, uint32_t *len) { return ef_read(name, len); }
+uint8_t *plat_reserve(const char *name, uint32_t len) {
+ uint32_t n;
+ return ef_write(name, NULL, len) ? (uint8_t *)(uintptr_t)ef_read(name, &n) : NULL; /* (the storage is RAM) */
+}
+void plat_reserved(const char *name, uint32_t len) { (void)name, (void)len; }
+bool plat_remove(const char *name) { return ef_remove(name); }
+void plat_begin(void) { np_app_begin(); }
+int plat_end(void) { return np_app_end(); }
+bool plat_slow(void) { return epsilon_slow_model(); }
diff --git a/games/fnafworld/src/plat_host.c b/games/fnafworld/src/plat_host.c
new file mode 100644
index 00000000..f3f5a8c5
--- /dev/null
+++ b/games/fnafworld/src/plat_host.c
@@ -0,0 +1,71 @@
+/* A computer: the screen goes to a frame buffer that tests save as images,
+ * keys come from a script, time is simulated. */
+#include <stdio.h>
+#include <stdlib.h>
+#include "plat.h"
+
+uint16_t host_fb[SCREEN_W * SCREEN_H];
+uint32_t host_time; /* ms */
+uint32_t host_keys;
+
+uint32_t plat_keys(void) { return host_keys; }
+uint32_t plat_millis(void) { return host_time; }
+void plat_sleep(uint32_t ms) { host_time += ms; }
+void plat_push(int x, int y, int w, int h, const uint16_t *px) {
+ for (int r = 0; r < h; r++)
+ for (int c = 0; c < w; c++)
+ if ((unsigned)(x + c) < SCREEN_W && (unsigned)(y + r) < SCREEN_H) host_fb[(y + r) * SCREEN_W + x + c] = px[r * w + c];
+}
+
+static char save_dir[256] = "build/host-saves";
+void host_save_dir(const char *d) { snprintf(save_dir, sizeof save_dir, "%s", d); }
+bool plat_save(const char *name, const void *data, uint32_t len) {
+ char p[512];
+ snprintf(p, sizeof p, "%s/%s", save_dir, name);
+ FILE *f = fopen(p, "wb");
+ if (!f) return false;
+ bool ok = fwrite(data, 1, len, f) == len;
+ fclose(f);
+ return ok;
+}
+/* (each file read gets its own buffer: callers may hold two at once) */
+static uint8_t loaded[4][1 << 16];
+static int next_load;
+const uint8_t *plat_load(const char *name, uint32_t *len) {
+ char p[512];
+ snprintf(p, sizeof p, "%s/%s", save_dir, name);
+ FILE *f = fopen(p, "rb");
+ if (!f) return NULL;
+ uint8_t *b = loaded[next_load++ & 3];
+ *len = (uint32_t)fread(b, 1, sizeof loaded[0], f);
+ fclose(f);
+ return b;
+}
+static uint8_t reserved[1 << 16];
+bool host_storage_full; /* tests: no room for any file */
+uint8_t *plat_reserve(const char *name, uint32_t len) {
+ (void)name;
+ return len <= sizeof reserved && !host_storage_full ? reserved : NULL;
+}
+void plat_reserved(const char *name, uint32_t len) { plat_save(name, reserved, len); }
+bool plat_remove(const char *name) {
+ char p[512];
+ snprintf(p, sizeof p, "%s/%s", save_dir, name);
+ return remove(p) == 0;
+}
+void plat_begin(void) {}
+int plat_end(void) { return 0; }
+bool plat_slow(void) { return false; }
+
+/* writes the screen as a PPM image */
+void host_shot(const char *path) {
+ FILE *f = fopen(path, "wb");
+ if (!f) return;
+ fprintf(f, "P6\n%d %d\n255\n", SCREEN_W, SCREEN_H);
+ for (int i = 0; i < SCREEN_W * SCREEN_H; i++) {
+ uint16_t c = host_fb[i];
+ uint8_t rgb[3] = {(uint8_t)((c >> 11) * 255 / 31), (uint8_t)(((c >> 5) & 63) * 255 / 63), (uint8_t)((c & 31) * 255 / 31)};
+ fwrite(rgb, 1, 3, f);
+ }
+ fclose(f);
+}
diff --git a/games/fnafworld/src/res.h b/games/fnafworld/src/res.h
new file mode 100644
index 00000000..f1227dde
--- /dev/null
+++ b/games/fnafworld/src/res.h
@@ -0,0 +1,15 @@
+/* FNAF World: data.bin (tools/pack.py), read where it lies in flash. */
+#ifndef FNAFW_RES_H
+#define FNAFW_RES_H
+#include <stdint.h>
+#include "data.h"
+
+extern const uint8_t *fnafw_bin;
+
+/* (byte by byte: the data is not always aligned) */
+static inline uint32_t rd16(const uint8_t *p) { return (uint32_t)(p[0] | p[1] << 8); }
+static inline int32_t rds16(const uint8_t *p) { return (int16_t)(p[0] | p[1] << 8); }
+static inline uint32_t rd24(const uint8_t *p) { return (uint32_t)(p[0] | p[1] << 8 | p[2] << 16); }
+static inline uint32_t rd32(const uint8_t *p) { return (uint32_t)(p[0] | p[1] << 8 | p[2] << 16 | (uint32_t)p[3] << 24); }
+static inline const uint8_t *section(int s) { return fnafw_bin + rd32(fnafw_bin + 8 + 4 * s); }
+#endif
diff --git a/games/fnafworld/src/rules.c b/games/fnafworld/src/rules.c
new file mode 100644
index 00000000..9758cf42
--- /dev/null
+++ b/games/fnafworld/src/rules.c
@@ -0,0 +1,177 @@
+/* FNAF World: its numbers, from its events (gamesrc spec/fnafworld_spec.md and fnafworld_spec2.md). */
+#include "game.h"
+
+const char *const CHAR_NAME[NCHAR + 1] = {
+ "", "Freddy", "Bonnie", "Chica", "Foxy", "Toy Bonnie", "Toy Chica", "Toy Freddy", "Mangle", "Balloon Boy", "JJ",
+ "Phantom Freddy", "Phantom Chica", "Phantom BB", "Phantom Foxy", "Phantom Mangle", "Withered Bonnie",
+ "Withered Chica", "Withered Freddy", "Withered Foxy", "Shadow Freddy", "Marionette", "Phantom Marionette",
+ "Golden Freddy", "Paperpals", "Nightmare Freddy", "Nightmare Bonnie", "Nightmare Chica", "Nightmare Foxy",
+ "Endo 01", "Endo 02", "Plushtrap", "Endoplush", "Springtrap", "RXQ", "Crying Child", "Funtime Foxy",
+ "Nightmare Fredbear", "Nightmare", "Fredbear", "Spring Bonnie", "Jack-O-Bonnie", "Jack-O-Chica", "Animdude",
+ "Mr. Chipper", "Nightmare BB", "Nightmarionne", "Coffee", "Purpleguy"};
+
+/* the events 156-249 (and the character select's 153-200) */
+const uint8_t CHAR_ATTACKS[NCHAR + 1][3] = {
+ {0, 0, 0}, {1, 6, 26}, {2, 7, 12}, {11, 13, 15}, {3, 8, 31}, {7, 32, 36}, {11, 26, 44}, {1, 13, 29}, {3, 34, 36},
+ {9, 31, 32}, {9, 34, 41}, {22, 23, 24}, {16, 23, 41}, {17, 21, 24}, {8, 16, 41}, {16, 38, 43}, {4, 6, 42},
+ {2, 11, 37}, {1, 22, 40}, {3, 24, 35}, {41, 40, 44}, {37, 38, 40}, {8, 35, 39}, {8, 25, 46}, {37, 39, 49},
+ {5, 23, 33}, {5, 25, 43}, {5, 20, 44}, {5, 42, 35}, {27, 28, 47}, {29, 47, 48}, {16, 20, 23}, {48, 4, 45},
+ {5, 10, 24}, {46, 49, 50}, {27, 28, 50}, {14, 30, 50}, {19, 33, 51}, {19, 25, 51}, {51, 15, 49}, {10, 14, 30},
+ {46, 54, 52}, {46, 54, 57}, {48, 58, 53}, {49, 57, 59}, {51, 55, 56}, {37, 55, 53}, {50, 58, 60}, {29, 52, 59}};
+
+const char *const ATTACK_NAME[61] = {
+ "", "Mic Toss", "Bite", "Hook", "Eye Beam", "Bite 2", "Pizza Wheel", "Bash Jam", "Jumpscare", "Balloons",
+ "Springlocks", "Cupcake", "Happy Jam", "Party Favors", "Happy Jam 2", "Regen Song", "Toxic Bite",
+ "Toxic Balloon", "Toxic Song", "Toxic Bite 2", "Bad Pizza", "Gloom Balloon", "Gloom Song", "Sludge", "Rainy Day",
+ "Rainy Day 2", "Birthday", "Power Song", "Armor Song", "Speed Song", "Cosmic Song", "Hot Cheese", "Munchies",
+ "Freddles", "Poppers", "Hot Cheese 2", "Prize Ball", "Prize Ball 2", "Mystery Box", "Mystery Box 2", "Esc Key",
+ "Unscrew", "Unscrew 2", "Pizza Wheel 2", "Waterhose", "Waterhose 2", "Haunting", "Endo Army", "Neon Wall",
+ "Mimic Ball", "Gift Boxes", "Mega Bite", "Slasher", "4th Wall", "Jack-O-Bomb", "Bubble Breath", "Balloons 2",
+ "Buzzsaw", "Mega Virus", "Hocus Pocus", "Neon Wall 2"};
+
+/* the colour of each button's end (the game's button pictures): 0 orange, 1 red, 2 pink, 3 green, 4 purple, 5 white,
+ * 6 yellow, 7 black */
+const uint8_t ATTACK_COLOUR[61] = {
+ 0, 0, 0, 0, 1, 0, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 1, 1, 1, 1, 1, 6, 6,
+ 6, 6, 6, 7, 7, 1, 7, 7, 6, 6, 6, 6, 6, 1, 4, 4, 0, 2, 0, 0, 1, 6, 1};
+
+const char *const ENEMY_NAME[54] = {
+ "", "Bouncepot", "Mechrab", "Gearrat", "Totemole", "Chop 'N Roll", "Boxbyte", "Chillax", "Flan", "Seaweed",
+ "Crabapple", "Colossal", "Quarry", "Metalman", "Goldmine", "Graveweed", "Beartrap", "Prototype", "Tombstack", "Rot",
+ "Blacktrap", "Meringue", "Dogfight", "Ballboy", ">>>>>>", "%__^^&(", "_!2222", "Tangle", "Redbear", "White Rabbit",
+ "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "Neon", "Jangle", "P. Goon"};
+
+const char *const BOSS_NAME[20] = {
+ "", "Auto Chipper", "Seagoon", "Eyesore", "Mad Endo", "Browboy", "Gold Endo", "Bubba", "Porkpatch", "Bouncer", "",
+ "Snowcone", "Supergoon", "Overclock", "Security", "Chipper's Revenge", "", "", "", "PurpleGeist"};
+
+const char *const CHIP_NAME[NCHIP + 1] = {
+ "", "Headstart: Defense", "Headstart: Strength", "Headstart: Speed", "Evercomet: Weak", "Quickstart: Party",
+ "Block: Jumpscare", "Run: Luck", "Endless: Defense", "Endless: Strength", "Endless: Speed", "Evercomet: Strong",
+ "Auto: Giftboxes", "Auto: Regen", "Find: Characters", "Curse: Status", "Freddle: Fury", "Auto: Shield",
+ "Auto: Mimic", "Counter: Bite", "Pizza: Fury", "Block: Unscrew"};
+
+const char *const BYTE_NAME[NBYTE + 1] = {
+ "", "Gnat", "Neon Bee", "Neon Wasp", "Medpod 1", "Medpod 2", "Mega-Med", "Mini-Reaper", "Reaper", "X-Reaper",
+ "Mini-FO", "UFO", "X-FO", "Block5", "Block20", "Block50", "Pop-Pop", "BOOM", "KABOOM", "BossDrain01",
+ "BossDrain02", "BossDrain-X"};
+
+/* the shop's events 69-110 */
+const uint16_t BYTE_PRICE[NBYTE + 1] = {0, 25, 75, 150, 25, 100, 500, 100, 500, 2000, 200, 500, 1500, 50, 500, 2000,
+ 99, 999, 4999, 200, 1500, 5000};
+
+/* 1017: "life p N" = level * 5 + 100 + character * 5 */
+int32_t life_max(int c, int lv) { return lv * 5 + 100 + c * 5; }
+
+/* 1100: a level up when "next" > (level^2 + 1) * 10 + character * 5 */
+int32_t exp_needed(int c, int lv) { return (lv * lv + 1) * 10 + c * 5; }
+
+/* 1003 */
+int32_t enemy_life(int type, int diff) { return (10 + type * type * 5) * diff; }
+
+/* 1004: ((c * 50) + 100) + ((c / 20) * 2000) * diff */
+int32_t challenger_life(int c, int diff) { return c * 50 + 100 + c / 20 * 2000 * diff; }
+
+/* 1619: the challenger: 9 + Random(area + 3) + (Random(3) / 2) * (Random(3) + 1) */
+int challenger_pick(int area) {
+ int a = rnd_n(area + 3);
+ int b = rnd_n(3) / 2;
+ int c = rnd_n(3) + 1;
+ return 9 + a + b * c;
+}
+
+/* 1077-1084 */
+int32_t victory_exp(int count, int type, int boss, int area, int diff) {
+ if (boss) {
+ if (boss == 6) return 0;
+ if (boss == 14) return 5000 * diff;
+ if (boss == 10 || boss == 15 || boss == 19) return 1;
+ return (area * 50 + 200) * diff;
+ }
+ return type == 14 ? 0 : count * type * 5 * diff;
+}
+
+int32_t victory_tokens(int count, int type, int boss, int area, int diff) {
+ if (boss) {
+ if (boss == 6) return 500 * diff;
+ if (boss == 14) return 250 * diff;
+ if (boss == 10 || boss == 15 || boss == 19) return 1;
+ return 0;
+ }
+ if (type == 14) return count * 25;
+ int a = rnd_n(11) / 10 * 10;
+ return count * area + a + rnd_n(6);
+}
+
+/* 1086-1093: how much exp one tick (50 ms) counts; the checks follow each other */
+int exp_tick(int32_t exp) {
+ int k = 0;
+ static const int32_t over[8] = {0, 10, 25, 50, 100, 200, 300, 500};
+ static const int take[8] = {1, 2, 2, 2, 2, 2, 10, 20};
+ for (int i = 0; i < 8; i++)
+ if (exp > over[i]) exp -= take[i], k += take[i];
+ return k;
+}
+
+/* the hits' divisor: "attack arrow 2" D (2 with a defense boost, else 1) + "shield" B (2) + "pwr down icon" D (2) */
+int divisor(bool def_boost, bool shield, bool pwr_down) { return (def_boost ? 2 : 1) + (shield ? 2 : 0) + (pwr_down ? 2 : 0); }
+
+/* 1061 */
+int32_t enemy_strength(int type, int diff, int div, int block, int armor) {
+ return (type * 4 + rnd_n(5)) * diff / div - block - armor * 10;
+}
+
+/* 1577-1597: a boss's life, speed, strength (rolled), its special and its animation (in "character 2") */
+int boss_info(int boss, int diff, int32_t *life, int32_t *speed, int32_t *strength, int *special, int *an) {
+ static const struct { int32_t life; uint8_t times_diff; int16_t speed, str, str_r; uint8_t special, an, effect; } B[20] = {
+ {0, 0, 100, 0, 1, 0, 0, 0},
+ {300, 1, 100, 40, 20, 7, 52, 4}, /* Auto Chipper */
+ {2000, 1, 100, 90, 20, 8, 53, 6}, /* Seagoon */
+ {1000, 1, 100, 40, 20, 3, 54, 7}, /* Eyesore */
+ {4000, 1, 100, 200, 10, 2, 55, 8}, /* Mad Endo */
+ {5000, 1, 100, 250, 100, 1, 51, 9}, /* Browboy */
+ {20000, 1, 100, 250, 100, 4, 56, 10}, /* Gold Endo */
+ {15000, 1, 100, 250, 100, 7, 57, 11}, /* Bubba */
+ {10000, 1, 100, 450, 100, 6, 58, 2}, /* Porkpatch */
+ {1000, 1, 100, 60, 20, 9, 59, 5}, /* Bouncer */
+ {100000, 0, 100, 1000, 500, 10, 60, 6}, /* the last */
+ {15000, 1, 100, 200, 300, 0, 59, 7}, /* Snowcone (specials 5 to 9) */
+ {10000, 1, 25, 400, 300, 0, 53, 8}, /* Supergoon (3 to 5) */
+ {15000, 1, 10, 200, 100, 3, 55, 9}, /* Overclock */
+ {50000, 1, 200, 999, 999, 11, 61, 10}, /* Security */
+ {200000, 0, 75, 3000, 100, 0, 62, 11}, /* Chipper's Revenge (5 to 10) */
+ {0, 0, 100, 0, 1, 0, 0, 0}, {0, 0, 100, 0, 1, 0, 0, 0}, {0, 0, 100, 0, 1, 0, 0, 0},
+ {500000, 0, 1000, 999, 999, 0, 63, 2}, /* PurpleGeist */
+ };
+ if (boss < 1 || boss > 19 || !B[boss].an) boss = 1;
+ if (life) *life = B[boss].life * (B[boss].times_diff ? diff : 1);
+ if (speed) *speed = B[boss].speed;
+ if (strength) *strength = B[boss].str + rnd_n(B[boss].str_r);
+ if (special) *special = B[boss].special;
+ if (an) *an = B[boss].an;
+ return B[boss].effect;
+}
+
+/* 966-1000: each enemy's special ("enemy attack" A) and the picture its hits make ("what attack effect") */
+int enemy_special(int type) {
+ switch (type) {
+ case 3: return 6;
+ case 6: case 9: case 15: case 19: return 2;
+ case 8: case 23: return 1;
+ case 10: case 17: return 4;
+ case 11: case 22: return 8;
+ case 18: return 3;
+ case 20: case 27: return 5;
+ case 21: case 24: return 9;
+ case 25: return 10;
+ case 26: return 11;
+ case 28: case 29: return 7;
+ default: return 0;
+ }
+}
+
+int enemy_hit_effect(int type) {
+ static const uint8_t E[30] = {0, 9, 1, 2, 5, 8, 3, 10, 10, 5, 8, 10, 6, 4, 5, 7, 3, 4, 2, 11, 3, 5, 6, 2, 3, 4, 5, 6, 7, 8};
+ if (type >= 51) return type == 51 ? 8 : type == 52 ? 9 : 10;
+ return type >= 1 && type <= 29 ? E[type] : 1;
+}
diff --git a/games/fnafworld/src/save.c b/games/fnafworld/src/save.c
new file mode 100644
index 00000000..0d6d9f68
--- /dev/null
+++ b/games/fnafworld/src/save.c
@@ -0,0 +1,158 @@
+/* FNAF World: the files (the game's Ini "fnafw1" to "fnafw3"), each fnafw1.sav to fnafw3.sav, and a copy of them in
+ * a Python script: installing apps from the NumWorks website keeps only Python scripts, so the saves come back from
+ * it when the files themselves are gone. Each is a comment line "#>name:base64" (the way NumPlay and its big games
+ * keep theirs). */
+#include <string.h>
+#include "game.h"
+#include "plat.h"
+
+#define COPY_NAME "fnafw_saves.py"
+#define MAGIC 0x57464E46u /* "FNFW" */
+#define VERSION 1
+
+typedef struct {
+ uint32_t magic;
+ uint16_t version, size;
+ File f;
+ uint32_t check;
+} Saved;
+
+static const char *const kept[3] = {"fnafw1.sav", "fnafw2.sav", "fnafw3.sav"};
+#define NKEPT 3
+static const char copy_head[] = "# FNAF World's saves: keep this file\n";
+static const char b64[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
+
+static uint32_t checksum(const File *f) {
+ const uint8_t *p = (const uint8_t *)f;
+ uint32_t h = 2166136261u;
+ for (unsigned i = 0; i < sizeof *f; i++) h = (h ^ p[i]) * 16777619u;
+ return h;
+}
+
+static void copy_write(void) {
+ uint32_t total = 1 + (sizeof copy_head - 1) + 1, len;
+ int n = 0;
+ for (int k = 0; k < NKEPT; k++)
+ if (plat_load(kept[k], &len) && len) total += 2 + (uint32_t)strlen(kept[k]) + 1 + (len + 2) / 3 * 4 + 1, n++;
+ plat_remove(COPY_NAME);
+ if (!n) return;
+ uint8_t *o = plat_reserve(COPY_NAME, total), *p = o;
+ if (!o) return;
+ *p++ = 0; /* (the script's status byte: not imported) */
+ memcpy(p, copy_head, sizeof copy_head - 1), p += sizeof copy_head - 1;
+ for (int k = 0; k < NKEPT; k++) {
+ const uint8_t *d = plat_load(kept[k], &len);
+ if (!d || !len) continue;
+ uint32_t nl = (uint32_t)strlen(kept[k]);
+ *p++ = '#', *p++ = '>';
+ memcpy(p, kept[k], nl), p += nl;
+ *p++ = ':';
+ for (uint32_t i = 0; i < len; i += 3, p += 4) {
+ /* (written out: GCC 15.2 for the calculator got a loop over the four wrong, see NumPlay's
+ * launcher/src/storage.c) */
+ uint32_t left = len - i, v = (uint32_t)d[i] << 16 | (left > 1 ? d[i + 1] << 8 : 0) | (left > 2 ? d[i + 2] : 0);
+ p[0] = (uint8_t)b64[v >> 18 & 63];
+ p[1] = (uint8_t)b64[v >> 12 & 63];
+ p[2] = left > 1 ? (uint8_t)b64[v >> 6 & 63] : '=';
+ p[3] = left > 2 ? (uint8_t)b64[v & 63] : '=';
+ }
+ *p++ = '\n';
+ }
+ *p++ = 0;
+ plat_reserved(COPY_NAME, (uint32_t)(p - o));
+}
+
+static int b64_value(uint8_t c) {
+ for (int i = 0; i < 64; i++)
+ if ((uint8_t)b64[i] == c) return i;
+ return -1;
+}
+
+static const uint8_t *copy_line(int k, uint32_t *len) {
+ uint32_t n, nl = (uint32_t)strlen(kept[k]);
+ const uint8_t *c = plat_load(COPY_NAME, &n);
+ if (!c) return NULL;
+ for (uint32_t i = 0; i + nl + 3 <= n; i++)
+ if (c[i] == '#' && c[i + 1] == '>' && !memcmp(c + i + 2, kept[k], nl) && c[i + 2 + nl] == ':') {
+ const uint8_t *l = c + i + 3 + nl;
+ uint32_t m = 0;
+ while (l + m < c + n && l[m] != '\n' && l[m]) m++;
+ *len = m;
+ return l;
+ }
+ return NULL;
+}
+
+void save_restore_copy(void) {
+ for (int k = 0; k < NKEPT; k++) {
+ uint32_t have, len;
+ if (plat_load(kept[k], &have)) continue;
+ const uint8_t *l = copy_line(k, &len);
+ if (!l || len < 4 || len % 4) continue;
+ uint32_t size = len / 4 * 3 - (l[len - 1] == '=') - (l[len - 2] == '=');
+ uint8_t *out = plat_reserve(kept[k], size);
+ if (!out) continue;
+ l = copy_line(k, &len);
+ bool ok = l != NULL && len / 4 * 3 - (l[len - 1] == '=') - (l[len - 2] == '=') == size;
+ uint32_t o = 0;
+ for (uint32_t i = 0; ok && i < len; i += 4) {
+ int v0 = l[i] == '=' ? 0 : b64_value(l[i]), v1 = l[i + 1] == '=' ? 0 : b64_value(l[i + 1]);
+ int v2 = l[i + 2] == '=' ? 0 : b64_value(l[i + 2]), v3 = l[i + 3] == '=' ? 0 : b64_value(l[i + 3]);
+ if (v0 < 0 || v1 < 0 || v2 < 0 || v3 < 0) ok = false;
+ uint32_t wd = (uint32_t)(v0 << 18 | v1 << 12 | v2 << 6 | v3);
+ if (o < size) out[o++] = (uint8_t)(wd >> 16);
+ if (o < size) out[o++] = (uint8_t)(wd >> 8);
+ if (o < size) out[o++] = (uint8_t)wd;
+ }
+ if (ok && o == size) plat_reserved(kept[k], size);
+ else plat_remove(kept[k]);
+ }
+}
+
+/* a file that holds together: every number in its range (a bad one is not loaded) */
+static bool valid(File *f) {
+ if (f->mode > 2 || f->diff > 2 || (f->started && (!f->mode || !f->diff))) return false;
+ for (int k = 0; k < 8; k++)
+ if (f->slot[k] > NCHAR) return false;
+ for (int k = 0; k < 4; k++)
+ if (f->chip[k] > NCHIP || f->bytes[k] > NBYTE) return false;
+ if (f->x < 0 || f->x > 6000 || f->y < 0 || f->y > 4000) f->x = f->y = 0;
+ if (f->armor != 0 && f->armor != 1 && f->armor != 2 && f->armor != 10) f->armor = 0;
+ for (int c = 1; c <= NCHAR; c++) f->have[c] &= 1;
+ return true;
+}
+
+bool load_file(int slot, File *f) {
+ if (slot < 1 || slot > 3) return false;
+ uint32_t len;
+ const uint8_t *d = plat_load(kept[slot - 1], &len);
+ if (!d || len != sizeof(Saved)) return false;
+ Saved s;
+ memcpy(&s, d, sizeof s);
+ if (s.magic != MAGIC || s.version != VERSION || s.size != sizeof(File) || s.check != checksum(&s.f)) return false;
+ if (!valid(&s.f)) return false;
+ *f = s.f;
+ return true;
+}
+
+void save_file(void) {
+ if (g.slot < 1 || g.slot > 3 || !g.f.started) return;
+ Saved s;
+ memset(&s, 0, sizeof s);
+ s.magic = MAGIC, s.version = VERSION, s.size = sizeof(File), s.f = g.f;
+ s.check = checksum(&s.f);
+ plat_save(kept[g.slot - 1], &s, sizeof s);
+ copy_write();
+ g.dirty = 0;
+}
+
+void save_new(int slot) {
+ g.slot = (uint8_t)slot;
+ save_file();
+}
+
+void save_summary(int slot, uint8_t *mode, uint8_t *diff, uint8_t *hours, uint8_t *minutes, bool *started) {
+ File f;
+ if (!load_file(slot, &f)) memset(&f, 0, sizeof f);
+ *mode = f.mode, *diff = f.diff, *hours = f.hours, *minutes = f.minutes, *started = f.started;
+}
diff --git a/games/fnafworld/src/world.c b/games/fnafworld/src/world.c
new file mode 100644
index 00000000..ff9dbd83
--- /dev/null
+++ b/games/fnafworld/src/world.c
@@ -0,0 +1,351 @@
+/* FNAF World: the overworld, as the overworld frame's events run it (events 1123-1153, 1394-1440, 1543-1559,
+ * 1632-1699, 1786-1845): walking with the four feelers, the areas, encounters, chests and their chips, switches
+ * and the barriers they open, the key and its doors, the bosses, the shops, the jumps.
+ *
+ * The map is tools/world.py's: drawn at 0.4 around the walker ("8bit hitbox", the game's coordinates). */
+#include <string.h>
+#include "anims.h"
+#include "data.h"
+#include "game.h"
+#include "gfx.h"
+#include "res.h"
+
+#define W g.w
+#define VW 800 /* the view, the game's pixels (320 x 240 at 0.4) */
+#define VH 600
+
+enum { O_ZONE, O_CHEST, O_COINS, O_BOSS, O_SWITCH, O_BARRIER, O_SHOP, O_KEY, O_PORT };
+
+typedef struct { int16_t x, y; uint16_t w, h, spr; } Ground;
+static const uint8_t *wsec;
+static int ng, ni, no, wrows, wstride;
+static const uint8_t *groundp, *instp, *objp, *wallp;
+
+static void world_load(void) {
+ if (wsec) return;
+ wsec = section(SEC_WORLD);
+ ng = (int)rd16(wsec), ni = (int)rd16(wsec + 2), no = (int)rd16(wsec + 4);
+ wrows = (int)rd16(wsec + 6), wstride = (int)rd16(wsec + 8);
+ groundp = wsec + 12;
+ instp = groundp + 12 * ng;
+ objp = instp + 6 * ni;
+ wallp = objp + 14 * no;
+}
+
+typedef struct { uint8_t kind, n; int16_t x0, y0, x1, y1; uint16_t s0, s1; } Obj;
+static Obj obj(int i) {
+ const uint8_t *p = objp + 14 * i;
+ Obj o = {p[0], p[1], (int16_t)rds16(p + 2), (int16_t)rds16(p + 4), (int16_t)rds16(p + 6), (int16_t)rds16(p + 8),
+ (uint16_t)rd16(p + 10), (uint16_t)rd16(p + 12)};
+ return o;
+}
+
+const char *area_name(int area) {
+ switch (area) {
+ case 2: return "Choppy's Woods";
+ case 5: return "Dusting Fields";
+ case 8: return "Lilygear Lake";
+ case 11: return "Mysterious Mine";
+ case 14: return "Blacktomb Yard";
+ case 17: return "Deep-Metal Mine";
+ case 20: return "Pinwheel Circus";
+ case 23: return "&*___TWRE";
+ case 26: return "Pinwheel Funhouse";
+ case 50: return "Geist Lair";
+ default: return "Fazbear Hills";
+ }
+}
+
+/* is a barrier there (not opened yet)? 1670-1797 */
+static bool barrier_on(int n) {
+ if (n >= 1 && n <= 3) return !g.f.sw[n];
+ if (n == 4) return !g.f.sw[4];
+ if (n == 5) return !g.f.sw[5];
+ if (n >= 6 && n <= 9) return !g.f.sw[n];
+ if (n == 10) return !g.f.key;
+ return false;
+}
+
+static bool wall_at(int x, int y) {
+ if (x < 0 || y < 0 || x >= MAP_W || y >= MAP_H) return true;
+ int cx = x / CELL, cy = y / CELL;
+ if (cy >= wrows) return true;
+ return wallp[cy * wstride + (cx >> 3)] >> (cx & 7) & 1;
+}
+/* a feeler (its box) on an obstacle backdrop ("feel top":C-23) */
+static bool feel_wall(int x0, int y0, int w, int h) {
+ for (int y = y0 - y0 % CELL; y < y0 + h; y += CELL)
+ for (int x = x0 - x0 % CELL; x < x0 + w; x += CELL)
+ if (wall_at(x < x0 ? x0 : x, y < y0 ? y0 : y)) return true;
+ return false;
+}
+static bool overlap(int x0, int y0, int w, int h, const Obj *o) {
+ return x0 < o->x1 && x0 + w > o->x0 && y0 < o->y1 && y0 + h > o->y0;
+}
+static bool feel_barrier(int x0, int y0, int w, int h) {
+ for (int i = 0; i < no; i++) {
+ Obj o = obj(i);
+ if (o.kind == O_BARRIER && barrier_on(o.n) && overlap(x0, y0, w, h, &o)) return true;
+ }
+ return false;
+}
+
+void world_save_pos(void) { /* 'x', 'y', 'area' and the time */
+ g.f.x = W.x, g.f.y = W.y, g.f.area = W.area;
+ g.dirty = 1;
+}
+
+void world_enter(void) {
+ world_load();
+ memset(&W, 0, sizeof W);
+ W.x = START_X, W.y = START_Y, W.dir = 3;
+ if (g.f.x > 0 && !g.f.resetpos) W.x = g.f.x, W.y = g.f.y, W.area = g.f.area; /* 9 */
+ if (g.f.resetpos) { /* 1285: back at the start, the bosses back */
+ g.f.resetpos = 0;
+ world_save_pos();
+ }
+}
+
+static void note(int n, int k) { W.note = (uint8_t)n, W.note_t = 150, W.note_n = (uint8_t)k; }
+enum { N_NONE, N_CHIP, N_KEY, N_SWITCH, N_MEMBER, N_CHALLENGER, N_SAVED, N_COINS };
+
+void world_step(void) {
+ uint32_t k = g.keys;
+ /* the clock ('hours', 'min', 'seconds') */
+ if (++W.sec_t >= 60) {
+ W.sec_t = 0;
+ if (++g.f.seconds >= 60) {
+ g.f.seconds = 0;
+ if (++g.f.minutes >= 60) g.f.minutes = 0, g.f.hours = (uint8_t)(g.f.hours < 255 ? g.f.hours + 1 : 255);
+ }
+ }
+ if (W.note_t > 0) W.note_t--;
+ if (W.note == N_CHALLENGER) { /* 1199-1202: the banner, then its battle */
+ if (W.note_t == 0) {
+ W.note = 0;
+ battle_challenger(W.note_n);
+ g.scene = SC_BATTLE;
+ }
+ return;
+ }
+ if (W.grace > 0) W.grace--; /* 1136 */
+ /* walking (1125-1128): 2 pixels a frame, if the feeler that way is free */
+ W.walking = 0;
+ int x = W.x, y = W.y;
+ if ((k & K_UP) && !(k & K_DOWN) &&
+ !feel_wall(x - FEEL_TOP_HX, y - 16 - FEEL_TOP_HY, FEEL_TOP_W, FEEL_TOP_H)) W.y -= 2, W.walking = 1, W.dir = 1;
+ if ((k & K_DOWN) && !(k & K_UP) &&
+ !feel_wall(x - FEEL_BOTTOM_HX, y + 14 - FEEL_BOTTOM_HY, FEEL_BOTTOM_W, FEEL_BOTTOM_H)) W.y += 2, W.walking = 1, W.dir = 3;
+ if ((k & K_RIGHT) && !(k & K_LEFT) &&
+ !feel_wall(x + 16 - FEEL_RIGHT_HX, y - FEEL_RIGHT_HY, FEEL_RIGHT_W, FEEL_RIGHT_H)) W.x += 2, W.walking = 1, W.dir = 0;
+ if ((k & K_LEFT) && !(k & K_RIGHT) &&
+ !feel_wall(x - 15 - FEEL_LEFT_HX, y - FEEL_LEFT_HY, FEEL_LEFT_W, FEEL_LEFT_H)) W.x -= 2, W.walking = 1, W.dir = 2;
+ /* the barriers push back (1635-1664) */
+ if (feel_barrier(W.x - FEEL_TOP_HX, W.y - 16 - FEEL_TOP_HY, FEEL_TOP_W, FEEL_TOP_H)) W.y += 20;
+ if (feel_barrier(W.x - FEEL_BOTTOM_HX, W.y + 14 - FEEL_BOTTOM_HY, FEEL_BOTTOM_W, FEEL_BOTTOM_H)) W.y -= 20;
+ if (feel_barrier(W.x + 16 - FEEL_RIGHT_HX, W.y - FEEL_RIGHT_HY, FEEL_RIGHT_W, FEEL_RIGHT_H)) W.x -= 20;
+ if (feel_barrier(W.x - 15 - FEEL_LEFT_HX, W.y - FEEL_LEFT_HY, FEEL_LEFT_W, FEEL_LEFT_H)) W.x += 20;
+ if (W.walking) W.img++;
+ else W.img = 0;
+ /* what the hitbox touches */
+ int hx = W.x - HIT_HX, hy = W.y - HIT_HY;
+ static uint8_t on_port, hold;
+ bool any_port = false;
+ for (int i = 0; i < no; i++) {
+ Obj o = obj(i);
+ if (!overlap(hx, hy, HIT_W, HIT_H, &o)) continue;
+ switch (o.kind) {
+ case O_ZONE: /* 1142-1152 */
+ if (W.area != o.n) {
+ W.area = o.n;
+ if (o.n == 5 && !g.f.w3) g.f.w3 = 1; /* 1803 */
+ }
+ break;
+ case O_CHEST: /* 1419-1440 */
+ if (!g.f.chest[o.n]) {
+ g.f.chest[o.n] = 1;
+ note(N_CHIP, o.n);
+ world_save_pos();
+ }
+ break;
+ case O_SWITCH: /* 1665-1669, 1790-1793 */
+ if (!g.f.sw[o.n]) {
+ g.f.sw[o.n] = 1;
+ note(N_SWITCH, o.n);
+ world_save_pos();
+ }
+ break;
+ case O_KEY: /* 1788: the key, guarded by Bouncer */
+ if (!g.f.key) {
+ g.f.key = 1;
+ note(N_KEY, 0);
+ battle_start(9);
+ g.scene = SC_BATTLE;
+ return;
+ }
+ break;
+ case O_BOSS: /* 1543-1558 */
+ if (!(W.boss_won[i >> 3] >> (i & 7) & 1) && o.n != 10 && o.n != 6) {
+ W.boss_won[i >> 3] |= (uint8_t)(1 << (i & 7));
+ battle_start(o.n);
+ g.scene = SC_BATTLE;
+ return;
+ }
+ break;
+ case O_PORT: { /* 1168-1185, 1393-1396, 1465-1504: to another place */
+ any_port = true;
+ bool go = false;
+ if (o.n == 0) go = !on_port;
+ else if (o.n == 3) go = (g.pressed & K_DOWN) != 0;
+ else if (k & K_UP) go = ++hold > (o.n == 1 ? 75 : 25);
+ else hold = 0;
+ on_port = 1;
+ if (go) {
+ W.x = (int16_t)o.s0, W.y = (int16_t)o.s1;
+ hold = 0;
+ return;
+ }
+ break;
+ }
+ case O_SHOP: /* 1696-1698, 1835-1838: after standing on it a moment */
+ if (!W.walking && ++W.enc_t > 50) {
+ W.enc_t = 0;
+ world_save_pos();
+ if (o.n == 1) g.shop_kind = (uint8_t)(W.area == 0 ? 1 : W.area), g.scene = SC_SHOP, g.t = 0, g.menu = 0;
+ else if (o.n == 2) g.scene = SC_ARMOR, g.t = 0, g.menu = 0;
+ return;
+ }
+ break;
+ }
+ }
+ if (!any_port) on_port = 0, hold = 0;
+ /* encounters (1133): every 2000 ms walking, one in four */
+ W.sec_t += 0;
+ static uint32_t enc_ms;
+ if (W.walking) {
+ enc_ms += 50;
+ if (enc_ms >= 2000 * 3) {
+ enc_ms -= 2000 * 3;
+ if (!W.grace && rnd_n(4) == 1) {
+ battle_start(0);
+ g.scene = SC_BATTLE;
+ }
+ }
+ }
+}
+
+/* after a battle (1198, 1240): a challenger, or a new member */
+void world_after_battle(void) {
+ Battle *b = &g.b;
+ memcpy(g.f.slot, b->slots, 8);
+ if (b->chal == 2 && b->chal_won) {
+ if (!g.f.have[b->chal_c]) g.f.have[b->chal_c] = 1, note(N_MEMBER, b->chal_c);
+ b->chal = 0;
+ } else if (b->won && !b->boss && !b->chal && b->chal_roll == 1 && g.f.mode != 2 && g.f.lv[g.f.slot[0]] >= 3 &&
+ W.area != 50) {
+ int c = challenger_pick(W.area);
+ if (c <= 40 && !g.f.have[c]) {
+ note(N_CHALLENGER, c);
+ W.note_t = 100;
+ }
+ }
+ world_save_pos();
+}
+
+/* ------------------------------------------------------------------ drawing */
+static int view_x, view_y; /* the view's corner, at 0.4 */
+
+void world_band_dim(void) {
+ int vx = view_x, vy = view_y;
+ gfx_fill(0, gfx_y0, SCREEN_W, BAND_H, RGB(0x203018));
+ /* the ground */
+ for (int i = 0; i < ng; i++) {
+ const uint8_t *p = groundp + 12 * i;
+ int x = (int)rds16(p) - vx, y = (int)rds16(p + 2) - vy, w = (int)rd16(p + 4), h = (int)rd16(p + 6);
+ if (y >= gfx_y0 + BAND_H || y + h <= gfx_y0 || x >= SCREEN_W || x + w <= 0) continue;
+ gfx_spr_tile((int)rd16(p + 8), x, y, w, h, x, y);
+ }
+ /* the pictures (in the game's order) */
+ for (int i = 0; i < ni; i++) {
+ const uint8_t *p = instp + 6 * i;
+ int y = (int)rds16(p + 2) - vy;
+ if (y >= gfx_y0 + BAND_H || y + 160 <= gfx_y0) continue;
+ int x = (int)rds16(p) - vx, s = (int)rd16(p + 4);
+ if (x >= SCREEN_W || x + 200 <= 0) continue;
+ if (y + gfx_spr_h(s) <= gfx_y0 || x + gfx_spr_w(s) <= 0) continue;
+ gfx_spr(s, x, y);
+ }
+ /* what the events act on */
+ for (int i = 0; i < no; i++) {
+ Obj o = obj(i);
+ if (o.s0 == 0xFFFF || o.kind == O_ZONE || o.kind == O_PORT) continue;
+ int s = o.s0;
+ if (o.kind == O_CHEST && g.f.chest[o.n]) continue;
+ if (o.kind == O_BARRIER && !barrier_on(o.n)) continue;
+ if (o.kind == O_KEY && g.f.key) continue;
+ if (o.kind == O_BOSS && (W.boss_won[i >> 3] >> (i & 7) & 1)) continue;
+ if (o.kind == O_SWITCH && g.f.sw[o.n]) s = o.s1;
+ int x = o.x0 * 2 / 5 - vx, y = o.y0 * 2 / 5 - vy;
+ if (y >= gfx_y0 + BAND_H || y + gfx_spr_h(s) <= gfx_y0 || x >= SCREEN_W || x + gfx_spr_w(s) <= 0) continue;
+ gfx_spr(s, x, y);
+ }
+ /* the walker ("Active 16" on the hitbox: anim 1 in its direction, anim 0 standing) */
+ if (W.area == 8) { /* 1161: on the lake, the raft ("lilly", at the walker -2, +9) */
+ int s = SPR_LILLY + W.dir * LILLY_N + (W.img / 4) % LILLY_N;
+ gfx_spr(s, (W.x - 2) * 2 / 5 - vx - gfx_spr_hx(s), (W.y + 9) * 2 / 5 - vy - gfx_spr_hy(s));
+ } else {
+ int s = W.walking ? SPR_WALK + W.dir * WALK_N + (W.img / 2) % WALK_N : SPR_STAND;
+ if (!W.walking && W.dir != 3) s = SPR_WALK + W.dir * WALK_N;
+ gfx_spr(s, W.x * 2 / 5 - vx - gfx_spr_hx(s), W.y * 2 / 5 - vy - gfx_spr_hy(s));
+ }
+ /* the corner: the area, the tokens */
+ if (gfx_y0 < 16) {
+ gfx_blend(0, 0, 320, 15, BLACK, 16);
+ gfx_text_s(FONT_SMALL, 4, 1, area_name(W.area), WHITE);
+ char t[24];
+ uint32_t v = g.f.tokens;
+ int p = 23;
+ t[p] = 0;
+ do t[--p] = (char)('0' + v % 10), v /= 10; while (v && p > 0);
+ const char *lbl = " Faz Tokens";
+ for (int i = 0; lbl[i] && p + i < 23; i++) {}
+ gfx_text_r(FONT_SMALL, 316 - gfx_text_w(FONT_SMALL, " tokens"), 1, t + p, RGB(0xFFD040));
+ gfx_text_r(FONT_SMALL, 316, 1, " tokens", WHITE);
+ }
+ if (gfx_y0 + BAND_H > 226) {
+ gfx_blend(0, 226, 320, 14, BLACK, 16);
+ gfx_text_s(FONT_SMALL, 4, 227, "Arrows walk Back menu Home save and quit", RGB(0xD0D8F0));
+ }
+ if (W.note_t > 0 && W.note) {
+ char s2[48];
+ const char *a = "", *b = "";
+ switch (W.note) {
+ case N_CHIP: a = "Found new chip!", b = CHIP_NAME[W.note_n]; break;
+ case N_SWITCH: a = "A switch!", b = "Something opened."; break;
+ case N_KEY: a = "Found a key!", b = "Locked doors open now."; break;
+ case N_MEMBER: a = "You have a new party member!", b = CHAR_NAME[W.note_n]; break;
+ case N_CHALLENGER: a = "A new challenger has appeared!", b = ""; break;
+ case N_SAVED: a = "Saved.", b = ""; break;
+ }
+ (void)s2;
+ int y = 92;
+ gfx_fill(30, y, 260, b[0] ? 40 : 24, RGB(0x0A1430));
+ gfx_frame_rect(30, y, 260, b[0] ? 40 : 24, WHITE);
+ gfx_text_c(FONT_TEXT, 160, y + 4, a, WHITE);
+ if (b[0]) gfx_text_c(FONT_TEXT, 160, y + 21, b, RGB(0xFFD040));
+ }
+}
+
+void world_prepare_view(void) {
+ int cx = W.x - VW / 2, cy = W.y - VH / 2; /* 1123: the view on the hitbox */
+ if (cx < 0) cx = 0;
+ if (cy < 0) cy = 0;
+ if (cx > MAP_W - VW) cx = MAP_W - VW;
+ if (cy > MAP_H - VH) cy = MAP_H - VH;
+ view_x = cx * 2 / 5, view_y = cy * 2 / 5;
+}
+
+void world_draw(void) {
+ world_prepare_view();
+ gfx_frame(world_band_dim);
+}
diff --git a/games/fnafworld/tests/rules.c b/games/fnafworld/tests/rules.c
new file mode 100644
index 00000000..74485746
--- /dev/null
+++ b/games/fnafworld/tests/rules.c
@@ -0,0 +1,231 @@
+/* FNAF World on a computer (make test, with the sanitizers): the numbers against the game's events (gamesrc spec
+ * fnafworld_spec.md, fnafworld_spec2.md), battles played to a win by pressing OK, walking the map, random keys
+ * everywhere, and the saves. Prints what failed; exits 1 if anything did. Screenshots: build/rules shots DIR. */
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include "../src/game.h"
+#include "../src/gfx.h"
+#include "../src/plat.h"
+
+extern const uint8_t fnafw_data[];
+const uint8_t *fnafw_bin;
+extern uint32_t host_keys, host_time;
+void host_shot(const char *path);
+void host_save_dir(const char *d);
+static int fails, checks;
+#define CHECK(c, ...) (checks++, (c) ? 0 : (fails++, printf("FAIL %d: ", __LINE__), printf(__VA_ARGS__), printf("\n")))
+#define B g.b
+
+static void step(uint32_t keys) { game_step(keys); }
+static void steps(int n, uint32_t keys) {
+ for (int i = 0; i < n; i++) step(keys);
+}
+static void tap(uint32_t k) { step(k), step(0); }
+
+static void new_game(int mode, int diff) {
+ game_init();
+ tap(K_OK); /* the title */
+ tap(K_OK); /* file 1 */
+ tap(K_OK); /* new game */
+ tap(K_UP), tap(K_OK); /* erase: yes */
+ for (int i = 1; i < mode; i++) tap(K_DOWN);
+ tap(K_OK);
+ for (int i = 1; i < diff; i++) tap(K_DOWN);
+ tap(K_OK);
+}
+
+static void rules(void) {
+ CHECK(life_max(1, 0) == 105 && life_max(48, 10) == 390, "life: level * 5 + 100 + character * 5");
+ CHECK(exp_needed(1, 0) == 15 && exp_needed(8, 3) == 140, "next: (level^2 + 1) * 10 + character * 5");
+ CHECK(enemy_life(1, 1) == 15 && enemy_life(3, 2) == 110 && enemy_life(53, 1) == 14055, "enemy life (10 + t^2 * 5) * diff");
+ CHECK(challenger_life(9, 1) == 550 && challenger_life(20, 2) == 5100 && challenger_life(40, 1) == 6100,
+ "challenger life (c * 50 + 100) + (c / 20) * 2000 * diff");
+ CHECK(victory_exp(3, 2, 0, 0, 1) == 30 && victory_exp(4, 14, 0, 11, 1) == 0, "exp: count * type * 5 * diff");
+ CHECK(victory_exp(1, 0, 1, 2, 2) == 600 && victory_exp(1, 0, 14, 0, 1) == 5000 && victory_exp(1, 0, 6, 0, 1) == 0,
+ "boss exp (area * 50 + 200) * diff; Security 5000; Gold Endo 0");
+ CHECK(victory_tokens(4, 14, 0, 11, 1) == 100 && victory_tokens(1, 0, 6, 0, 2) == 1000, "Goldmine: count * 25; Gold Endo 500 * diff");
+ for (int i = 0; i < 200; i++) {
+ int32_t t = victory_tokens(3, 4, 0, 5, 1);
+ if (t < 15 || t > 30 || (t > 20 && t < 25)) {
+ CHECK(0, "tokens count * area + (Random(11)/10)*10 + Random(6): %d", (int)t);
+ break;
+ }
+ }
+ CHECK(exp_tick(1) == 1 && exp_tick(12) == 3 && exp_tick(600) == 41 && exp_tick(301) == 11, "exp ticks (1086-1093)");
+ CHECK(divisor(false, false, false) == 1 && divisor(true, true, true) == 6, "the hits' divisor");
+ int lo = 1000, hi = -1000;
+ for (int i = 0; i < 500; i++) {
+ int32_t s = enemy_strength(3, 1, 1, 0, 0);
+ if (s < lo) lo = s;
+ if (s > hi) hi = s;
+ }
+ CHECK(lo == 12 && hi == 16, "strength type 3: 12 to 16 (%d to %d)", lo, hi);
+ CHECK(enemy_strength(3, 2, 2, 5, 1) <= (12 + 4) * 2 / 2 - 5 - 10, "strength: / divisor - block - armor * 10");
+ for (int i = 0; i < 300; i++) {
+ int c = challenger_pick(0);
+ if (c < 9 || c > 14) {
+ CHECK(0, "challenger in Fazbear Hills: 9 to 14 (%d)", c);
+ break;
+ }
+ }
+ int32_t life, speed, str;
+ int sp, an;
+ boss_info(1, 1, &life, &speed, &str, &sp, &an);
+ CHECK(life == 300 && speed == 100 && str >= 40 && str < 60 && sp == 7 && an == 52, "Auto Chipper (1577)");
+ boss_info(15, 2, &life, &speed, &str, &sp, &an);
+ CHECK(life == 200000 && speed == 75 && an == 62, "Chipper's Revenge (1596)");
+ CHECK(enemy_special(3) == 6 && enemy_special(1) == 0 && enemy_special(25) == 10 && enemy_hit_effect(19) == 11, "specials");
+ CHECK(CHAR_ATTACKS[1][0] == 1 && CHAR_ATTACKS[48][2] == 59 && CHAR_ATTACKS[25][1] == 23, "attacks (156-249)");
+}
+
+static bool play_battle(int boss, int max_frames) {
+ battle_start(boss);
+ g.scene = SC_BATTLE;
+ for (int i = 0; i < max_frames && g.scene == SC_BATTLE; i++) {
+ uint32_t k = B.ready && (i & 1) ? K_OK : 0;
+ step(k);
+ }
+ return g.scene != SC_BATTLE;
+}
+
+static void battles(void) {
+ new_game(1, 1);
+ CHECK(g.scene == SC_PARTY && g.f.mode == 1 && g.f.diff == 1, "a new game: Adventure, Normal, the party next");
+ CHECK(g.f.have[1] && g.f.have[8] && !g.f.have[9] && g.f.slot[0] == 1 && g.f.slot[7] == 8, "the first eight");
+ tap(K_DIGIT(0));
+ CHECK(g.scene == SC_WORLD && g.w.x == 1827 && g.w.y == 1023, "on the map at the start (%d %d)", g.w.x, g.w.y);
+ /* walking (1125-1128): 2 pixels a frame */
+ int x = g.w.x;
+ steps(10, K_LEFT);
+ CHECK(g.w.x == x - 20 || g.scene == SC_BATTLE, "walked 20 left (%d)", g.w.x - x);
+ /* battles to a win */
+ int won = 0, ran = 0;
+ uint32_t t0 = g.f.tokens;
+ for (int n = 0; n < 12; n++) {
+ g.w.area = 0;
+ g.w.grace = 0;
+ if (play_battle(0, 60 * 120)) won += g.b.won;
+ else ran++;
+ (void)ran;
+ if (g.scene == SC_GAMEOVER) break;
+ }
+ CHECK(won >= 10, "won %d of 12 battles in Fazbear Hills", won);
+ CHECK(g.f.tokens > t0, "tokens won (%u)", (unsigned)g.f.tokens);
+ CHECK(g.f.lv[1] > 0, "Freddy levelled up (%d)", g.f.lv[1]);
+ /* charges (91-106): never two full in a row */
+ battle_start(0);
+ g.scene = SC_BATTLE;
+ int bad = 0;
+ for (int i = 0; i < 60 * 20; i++) {
+ step(0);
+ int full = 0;
+ for (int k = 0; k < 4; k++) full += B.charge[(B.row - 1) * 4 + k] == 10;
+ bad += full > 1;
+ }
+ CHECK(!bad, "one full charge at a time (%d)", bad);
+ /* a boss */
+ g.scene = SC_WORLD;
+ for (int c = 1; c <= 8; c++) g.f.lv[c] = 20;
+ CHECK(play_battle(1, 60 * 300) && g.b.won, "Auto Chipper beaten at level 21");
+ /* every attack, at least once */
+ for (int a = 1; a <= 60; a++) {
+ battle_start(0);
+ g.scene = SC_BATTLE;
+ steps(60, 0);
+ B.att_slot = 1, B.used = (uint8_t)a, B.att_an = 0, B.att_img = 0, B.cur_level = 5;
+ steps(400, 0);
+ }
+ CHECK(1, "every attack played");
+}
+
+static void fuzz(void) {
+ srand(7);
+ static const uint32_t keys[] = {0, K_LEFT, K_RIGHT, K_UP, K_DOWN, K_OK, K_EXE, K_BACK, K_DEL, K_DIGIT(0), K_DIGIT(1),
+ K_DIGIT(2), K_DIGIT(3), K_LEFT | K_UP, K_RIGHT | K_DOWN};
+ for (int run = 0; run < 40; run++) {
+ new_game(1 + run % 2, 1 + (run / 2) % 2);
+ tap(K_DIGIT(0));
+ for (int i = 0; i < 60 * 60 && g.running; i++) {
+ uint32_t k = keys[rand() % (int)(sizeof keys / sizeof keys[0])];
+ if (g.scene == SC_PAUSE && (k & (K_OK | K_EXE)) && g.menu == 7) k = 0; /* (not quitting) */
+ int hold = 1 + rand() % 20;
+ for (int h = 0; h < hold; h++) step(k);
+ if (i % 300 == 0) game_draw();
+ }
+ }
+ CHECK(1, "random keys");
+}
+
+static void saves(void) {
+ new_game(1, 2);
+ tap(K_DIGIT(0));
+ g.f.tokens = 1234, g.f.lv[3] = 7, g.f.chest[5] = 1, g.f.chip[0] = 5;
+ g.w.x = 2000, g.w.y = 1500;
+ world_save_pos();
+ save_file();
+ File f;
+ CHECK(load_file(1, &f) && f.tokens == 1234 && f.lv[3] == 7 && f.chest[5] && f.chip[0] == 5 && f.x == 2000 && f.diff == 2,
+ "a file comes back");
+ plat_save("fnafw2.sav", "garbage", 7);
+ CHECK(!load_file(2, &f), "a bad file is not loaded");
+ plat_remove("fnafw1.sav");
+ save_restore_copy();
+ CHECK(load_file(1, &f) && f.tokens == 1234, "the file back from the script's copy");
+}
+
+static void shots(const char *dir) {
+ char p[512];
+ new_game(1, 1);
+ game_init();
+ game_draw();
+ snprintf(p, sizeof p, "%s/title.ppm", dir), host_shot(p);
+ new_game(1, 1);
+ game_draw();
+ snprintf(p, sizeof p, "%s/party.ppm", dir), host_shot(p);
+ tap(K_DIGIT(0));
+ steps(30, K_RIGHT);
+ game_draw();
+ snprintf(p, sizeof p, "%s/map.ppm", dir), host_shot(p);
+ battle_start(0);
+ g.scene = SC_BATTLE;
+ for (int i = 0; i < 400 && !B.ready; i++) step(0);
+ game_draw();
+ snprintf(p, sizeof p, "%s/battle.ppm", dir), host_shot(p);
+ tap(K_OK);
+ steps(16, 0);
+ game_draw();
+ snprintf(p, sizeof p, "%s/attack.ppm", dir), host_shot(p);
+ static const int16_t spots[][2] = {{2274, 700}, {1924, 560}, {1774, 950}, {1574, 1700}, {3000, 1000}, {1000, 3000},
+ {2500, 3500}, {3400, 2300}, {5300, 3000}};
+ for (unsigned i = 0; i < sizeof spots / sizeof spots[0]; i++) {
+ g.scene = SC_WORLD;
+ g.w.x = spots[i][0], g.w.y = spots[i][1];
+ game_draw();
+ snprintf(p, sizeof p, "%s/map%u.ppm", dir, i), host_shot(p);
+ }
+ g.w.area = 8;
+ battle_start(2);
+ g.scene = SC_BATTLE;
+ steps(90, 0);
+ game_draw();
+ snprintf(p, sizeof p, "%s/boss.ppm", dir), host_shot(p);
+}
+
+int main(int argc, char **argv) {
+ static uint16_t band[SCREEN_W * BAND_H];
+ gfx_set_band_memory(band);
+ fnafw_bin = fnafw_data;
+ host_save_dir("build/host-saves");
+ system("mkdir -p build/host-saves");
+ if (argc > 2 && !strcmp(argv[1], "shots")) {
+ shots(argv[2]);
+ return 0;
+ }
+ rules();
+ battles();
+ saves();
+ fuzz();
+ printf("%d checks, %d failed\n", checks, fails);
+ return fails ? 1 : 0;
+}
diff --git a/games/fnafworld/tools/ccn.py b/games/fnafworld/tools/ccn.py
new file mode 100644
index 00000000..86b6d6f5
--- /dev/null
+++ b/games/fnafworld/tools/ccn.py
@@ -0,0 +1,209 @@
+"""FNAF World's application data (Clickteam Fusion 2.5, build 284), read only; tools/pack.py uses it.
+
+The game's fnaf-world.exe holds its data encrypted; ~/Documents/Assets/gamesrc/fnafworld/tools/unpack.py writes it out
+plain as app.ccn: chunks (u16 id, u16 flags 0, u32 size, the data). The ones read here:
+- 0x6666, the pictures: u32 count, then each: i32 its number + 1, u32 size, u32 packed size, zlib data: i32, i32,
+ u32 size, i16 width, i16 height, u8 mode (4: BGR), u8 flags (16: an alpha plane follows), u16, 4 x i16 hot spot and
+ action point, 4 bytes the clear colour, then the rows (BGR, padded to an even number of bytes; the alpha rows to 4).
+- 0x2229, the objects: u32 count, then each a run of chunks: 0x4444 (u16 its number, i16 kind: 0 quick backdrop,
+ 1 backdrop, 2 active, 3 string, 7 counter), 0x4445 (its name, UTF-16), 0x4446 (its properties: a backdrop's
+ picture at byte 16; a quick backdrop's size at 8, its fill at 24 (1 a colour, 3 a picture) and the colour or picture at 26; an active's animations from the
+ offset at byte 4: u16 size, u16 count, u16 offsets, each animation 32 directions; a direction: u8 its slowest and
+ fastest speed, u16 how many times it plays (0 for ever), u16 the picture it loops back to, u16 the picture count,
+ the pictures).
+- 0x3333, the frames: chunks of their own, 0x3334 the size, 0x3335 the name, 0x3341 the layers (u32 count, each:
+ u32 flags, f32 x and y scroll, u32, u32, the name), 0x3338 the objects placed (u32 count, then 20 bytes each:
+ u16, u16 the object, i32 x, i32 y, i16, i16, i16 the layer, i16)."""
+import os
+import struct
+import zlib
+
+from PIL import Image
+
+CCN = os.path.expanduser("~/Documents/Assets/gamesrc/fnafworld/dl/app.ccn")
+
+
+def chunks(b, p=0):
+ out = []
+ while p + 8 <= len(b):
+ cid, _, size = struct.unpack_from("<HHI", b, p)
+ out.append((cid, b[p + 8:p + 8 + size]))
+ p += 8 + size
+ if cid == 0x7F7F:
+ break
+ return out
+
+
+def wstr(b):
+ return b.decode("utf-16-le", "replace").split("\0")[0]
+
+
+class Frame:
+ def __init__(self, sub):
+ self.name = wstr(sub[0x3335])
+ self.w, self.h = struct.unpack_from("<ii", sub[0x3334], 0)
+ self.layers = []
+ if 0x3341 in sub:
+ b = sub[0x3341]
+ q = 4
+ for _ in range(struct.unpack_from("<I", b, 0)[0]):
+ fl, xc, yc, _, _ = struct.unpack_from("<IffII", b, q)
+ q += 20
+ e = q
+ while b[e:e + 2] != b"\0\0":
+ e += 2
+ self.layers.append((wstr(b[q:e + 2]), fl, xc, yc))
+ q = e + 2
+ self.placed = [] # (object, x, y, layer)
+ x = sub.get(0x3338, b"\0\0\0\0")
+ for k in range(struct.unpack_from("<I", x, 0)[0]):
+ _, obj, px, py, _, _, layer, _ = struct.unpack_from("<HHiihhhh", x, 4 + 20 * k)
+ self.placed.append((obj, px, py, layer))
+ self.events = sub.get(0x333D, b"")
+
+
+class App:
+ def __init__(self, path=CCN):
+ d = open(path, "rb").read()
+ assert d[:4] == b"PAMU", "not a Clickteam application"
+ top = chunks(d, 16)
+ self.pics = {}
+ bank = next(c for i, c in top if i == 0x6666)
+ q = 4
+ for _ in range(struct.unpack_from("<I", bank, 0)[0]):
+ h, _, csize = struct.unpack_from("<iII", bank, q)
+ self.pics[h - 1] = (q + 12, csize)
+ q += 12 + csize
+ self.bank = bank
+ self._cache = {}
+ self.objects, self.meta = {}, {}
+ self.ink, self.visible, self.obstacle, self.fine, self.values = {}, {}, {}, {}, {}
+ b = next(c for i, c in top if i == 0x2229)
+ q = 4
+ for _ in range(struct.unpack_from("<I", b, 0)[0]):
+ head = name = props = None
+ while True:
+ sid, _, size = struct.unpack_from("<HHI", b, q)
+ body = b[q + 8:q + 8 + size]
+ q += 8 + size
+ if sid == 0x4444:
+ head = struct.unpack_from("<Hh", body, 0)
+ ink = struct.unpack_from("<II", body, 8) if len(body) >= 16 else (0, 0xFFFFFFFF)
+ elif sid == 0x4445:
+ name = wstr(body)
+ elif sid == 0x4446:
+ props = body
+ elif sid == 0x7F7F:
+ break
+ kind = head[1]
+ anims, meta, image = {}, {}, None
+ if kind == 2 and props:
+ anims, meta = self._anims(props)
+ elif kind == 1 and props and len(props) >= 18:
+ image = struct.unpack_from("<H", props, 16)[0]
+ elif kind == 0 and props and len(props) >= 34:
+ w, hh = struct.unpack_from("<ii", props, 8)
+ shape, fill = struct.unpack_from("<HH", props, 22)
+ image = (w, hh, struct.unpack_from("<H", props, 26)[0] if fill == 3 else None,
+ struct.unpack_from("<I", props, 26)[0] if fill == 1 else None)
+ self.objects[head[0]] = (kind, name, anims, image)
+ self.ink[head[0]] = ink
+ vis, obst, fine = True, False, False
+ if kind == 2 and props and len(props) > 44:
+ nf = struct.unpack_from("<H", props, 42)[0]
+ vis, obst = bool(nf & 8), (nf & 0x30) == 0x10
+ elif kind in (0, 1) and props and len(props) >= 8:
+ ob, col = struct.unpack_from("<HH", props, 4)
+ obst, fine = ob == 1, col == 1
+ self.visible[head[0]], self.obstacle[head[0]], self.fine[head[0]] = vis, obst, fine
+ self.meta[head[0]] = meta
+ self.frames = {}
+ for i, c in top:
+ if i == 0x3333:
+ f = Frame(dict(chunks(c)))
+ self.frames[f.name] = f
+
+ @staticmethod
+ def _anims(p):
+ at = struct.unpack_from("<H", p, 4)[0]
+ if not at:
+ return {}, {}
+ out, meta = {}, {}
+ count = struct.unpack_from("<H", p, at + 2)[0]
+ for a, off in enumerate(struct.unpack_from(f"<{count}H", p, at + 4)):
+ if not off:
+ continue
+ dirs = struct.unpack_from("<32H", p, at + off)
+ for di, doff in enumerate(dirs):
+ if not doff:
+ continue
+ q = at + off + doff
+ lo, hi, rep, back, n = struct.unpack_from("<BBHHH", p, q)
+ out[(a, di)] = list(struct.unpack_from(f"<{n}H", p, q + 8))
+ meta[(a, di)] = (hi, rep, back)
+ return out, meta
+
+ def _raw(self, h):
+ if h not in self._cache:
+ at, csize = self.pics[h]
+ raw = zlib.decompress(self.bank[at:at + csize])
+ _, _, _, w, hh, mode, flags, _, hx, hy, ax, ay = struct.unpack_from("<iiIhhBBHhhhh", raw, 0)
+ self._cache[h] = (raw, w, hh, mode, flags, hx, hy, ax, ay)
+ return self._cache[h]
+
+ def picture(self, h):
+ """a picture by its number, RGBA"""
+ raw, w, hh, mode, flags, *_ = self._raw(h)
+ tr = raw[28:32]
+ px = raw[32:]
+ if flags & 8:
+ px = zlib.decompress(px[4:])
+ assert mode == 4 and not flags & 7, (h, mode, flags)
+ pitch = w * 3 + (w * 3) % 2 * 3 if False else w * 3
+ pad = (2 - (w * 3) % 2) % 2
+ padp = -(-pad // 3) if pad else 0
+ pitch = (w + padp) * 3
+ import numpy as np
+ rows = np.frombuffer(px[:pitch * hh], dtype=np.uint8).reshape(hh, pitch)[:, :w * 3].reshape(hh, w, 3)
+ rgb = rows[..., ::-1]
+ if flags & 16:
+ ap = w + (4 - w % 4) % 4
+ a = np.frombuffer(px[pitch * hh:pitch * hh + ap * hh], dtype=np.uint8).reshape(hh, ap)[:, :w]
+ else:
+ a = np.where((rows == np.frombuffer(tr[:3], dtype=np.uint8)).all(axis=2), 0, 255).astype(np.uint8)
+ return Image.fromarray(np.dstack([rgb, a]).astype(np.uint8), "RGBA")
+
+ def size(self, h):
+ return self._raw(h)[1:3]
+
+ def hotspot(self, h):
+ """a picture's hot spot: where an object placed at (x, y) has it"""
+ return self._raw(h)[5:7]
+
+ def action(self, h):
+ return self._raw(h)[7:9]
+
+ def find(self, name, frame=None):
+ """objects by name (those placed in that frame, when given)"""
+ hits = [h for h, o in self.objects.items() if o[1] == name]
+ if frame is not None:
+ placed = {o for o, *_ in self.frames[frame].placed}
+ hits = [h for h in hits if h in placed]
+ return hits
+
+ def obj(self, name, frame=None):
+ hits = self.find(name, frame)
+ assert len(hits) == 1, (name, frame, hits)
+ return hits[0]
+
+ def anim(self, name, a=0, d=0, frame=None):
+ o = name if isinstance(name, int) else self.obj(name, frame)
+ return self.objects[o][2][(a, d)]
+
+ def anims(self, name, frame=None):
+ o = name if isinstance(name, int) else self.obj(name, frame)
+ return self.objects[o][2]
+
+ def speed(self, name, a=0, d=0, frame=None):
+ o = name if isinstance(name, int) else self.obj(name, frame)
+ return self.meta[o][(a, d)]
diff --git a/games/fnafworld/tools/codec.py b/games/fnafworld/tools/codec.py
new file mode 100644
index 00000000..cd60b260
--- /dev/null
+++ b/games/fnafworld/tools/codec.py
@@ -0,0 +1,249 @@
+"""Five Nights at Freddy's: the pictures' codec (src/pic.c decodes it).
+
+The game's pictures are dark, grainy renders: what keeps them small is what JPEG does, so this is JPEG's
+baseline coding without its file format. A picture is a grid of 16 x 16 squares (MCUs): YCbCr, the colours at
+half resolution (4:2:0), each 8 x 8 block cosine-transformed, quantized and Huffman-coded (JPEG's run/size
+symbols and tables, one set for the whole game). Every square stands alone, starting on a byte, with no DC
+prediction from the one before it (only between the four Y blocks of a square), so the game decodes only the
+squares on screen, and pictures share squares: a camera with Bonnie in it is the empty camera's squares but
+where he stands, the frames of a jumpscare share what doesn't move, and squares that come out the same anywhere
+are stored once."""
+import heapq
+
+import numpy as np
+
+ZIGZAG = [0, 1, 8, 16, 9, 2, 3, 10, 17, 24, 32, 25, 18, 11, 4, 5, 12, 19, 26, 33, 40, 48, 41, 34, 27, 20, 13, 6, 7,
+ 14, 21, 28, 35, 42, 49, 56, 57, 50, 43, 36, 29, 22, 15, 23, 30, 37, 44, 51, 58, 59, 52, 45, 38, 31, 39, 46,
+ 53, 60, 61, 54, 47, 55, 62, 63]
+STD_LUMA = [16, 11, 10, 16, 24, 40, 51, 61, 12, 12, 14, 19, 26, 58, 60, 55, 14, 13, 16, 24, 40, 57, 69, 56,
+ 14, 17, 22, 29, 51, 87, 80, 62, 18, 22, 37, 56, 68, 109, 103, 77, 24, 35, 55, 64, 81, 104, 113, 92,
+ 49, 64, 78, 87, 103, 121, 120, 101, 72, 92, 95, 98, 112, 100, 103, 99]
+STD_CHROMA = [17, 18, 24, 47, 99, 99, 99, 99, 18, 21, 26, 66, 99, 99, 99, 99, 24, 26, 56, 99, 99, 99, 99, 99,
+ 47, 66, 99, 99, 99, 99, 99, 99] + [99] * 32
+# libjpeg's "ifast" IDCT folds these scales into the quantization table (src/pic.c)
+AANSCALES = [16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520, 22725, 31521, 29692, 26722, 22725, 17855, 12299,
+ 6270, 21407, 29692, 27969, 25172, 21407, 16819, 11585, 5906, 19266, 26722, 25172, 22654, 19266, 15137,
+ 10426, 5315, 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520, 12873, 17855, 16819, 15137, 12873,
+ 10114, 6967, 3552, 8867, 12299, 11585, 10426, 8867, 6967, 4799, 2446, 4520, 6270, 5906, 5315, 4520,
+ 3552, 2446, 1247]
+LUT_BITS = 9
+
+
+def qtable(base, quality):
+ s = 5000 / quality if quality < 50 else 200 - 2 * quality
+ return np.array([min(255, max(1, int((b * s + 50) // 100))) for b in base], dtype=np.float64)
+
+
+def dct_matrix():
+ c = np.zeros((8, 8))
+ for k in range(8):
+ for n in range(8):
+ c[k, n] = (np.sqrt(1 / 8) if k == 0 else np.sqrt(2 / 8)) * np.cos((2 * n + 1) * k * np.pi / 16)
+ return c
+
+
+DCT = dct_matrix()
+
+
+def ycbcr(rgb):
+ """an H x W x 3 picture (0-255) -> Y (H x W), Cb and Cr (H/2 x W/2), all level-shifted (-128)"""
+ r, g, b = rgb[..., 0], rgb[..., 1], rgb[..., 2]
+ y = 0.299 * r + 0.587 * g + 0.114 * b - 128
+ cb = -0.168736 * r - 0.331264 * g + 0.5 * b
+ cr = 0.5 * r - 0.418688 * g - 0.081312 * b
+ h, w = y.shape
+ cb = cb.reshape(h // 2, 2, w // 2, 2).mean(axis=(1, 3))
+ cr = cr.reshape(h // 2, 2, w // 2, 2).mean(axis=(1, 3))
+ return y, cb, cr
+
+
+def blocks_of(plane):
+ """an H x W plane -> (H/8, W/8, 8, 8) of its DCT coefficients"""
+ h, w = plane.shape
+ b = plane.reshape(h // 8, 8, w // 8, 8).transpose(0, 2, 1, 3)
+ return np.einsum("ij,abjk,lk->abil", DCT, b, DCT)
+
+
+def quantize(coef, q, deadzone):
+ """coefficients (..., 8, 8) / a natural-order table, rounded toward 0 a little (deadzone) on the AC ones"""
+ x = coef / q.reshape(8, 8)
+ r = np.sign(x) * np.floor(np.abs(x) + 0.5 - deadzone)
+ r[..., 0, 0] = np.round(x[..., 0, 0])
+ return np.maximum(r, 0 * r - 2047).clip(-2047, 2047).astype(np.int32)
+
+
+def size_of(v):
+ v = abs(int(v))
+ n = 0
+ while v:
+ n += 1
+ v >>= 1
+ return n
+
+
+def bits_of(v, n):
+ return v if v >= 0 else v + (1 << n) - 1
+
+
+def block_symbols(zz, pred):
+ """one block's coefficients in zigzag order -> [(table: 0 DC 1 AC, symbol, extra bits value, extra bits count)]"""
+ out = []
+ d = int(zz[0]) - pred
+ s = size_of(d)
+ out.append((0, s, bits_of(d, s), s))
+ run = 0
+ last = 63
+ while last > 0 and zz[last] == 0:
+ last -= 1
+ for k in range(1, last + 1):
+ v = int(zz[k])
+ if v == 0:
+ run += 1
+ continue
+ while run > 15:
+ out.append((1, 0xF0, 0, 0))
+ run -= 16
+ s = size_of(v)
+ out.append((1, run << 4 | s, bits_of(v, s), s))
+ run = 0
+ if last < 63:
+ out.append((1, 0x00, 0, 0))
+ return out
+
+
+def mcu_symbols(yq, cbq, crq):
+ """the quantized blocks of one square: 4 Y (8 x 8 each, natural order), Cb, Cr -> [(component class, ...)]"""
+ syms = []
+ pred = 0
+ for b in yq:
+ zz = b.reshape(64)[ZIGZAG]
+ syms += [(0,) + s for s in block_symbols(zz, pred)]
+ pred = int(zz[0])
+ for b in (cbq, crq):
+ zz = b.reshape(64)[ZIGZAG]
+ syms += [(1,) + s for s in block_symbols(zz, 0)]
+ return syms
+
+
+def huffman_lengths(freq):
+ """symbol -> frequency, to code lengths of at most 16 bits (JPEG's Annex K.2 and K.3)"""
+ # a symbol of its own takes the all-ones code, which JPEG never uses (the padding is ones)
+ f = {s: float(c) for s, c in freq.items() if c > 0}
+ f[256] = 0.5
+ syms = list(f)
+ heap = [(f[s], i, [s]) for i, s in enumerate(syms)]
+ heapq.heapify(heap)
+ length = {s: 0 for s in syms}
+ n = len(syms)
+ while len(heap) > 1:
+ f1, _, a = heapq.heappop(heap)
+ f2, _, b = heapq.heappop(heap)
+ for s in a + b:
+ length[s] += 1
+ n += 1
+ heapq.heappush(heap, (f1 + f2, n, a + b))
+ bits = [0] * 64
+ for s in syms:
+ bits[length[s]] += 1
+ i = 63
+ while i > 16:
+ while bits[i] > 0:
+ j = i - 2
+ while bits[j] == 0:
+ j -= 1
+ bits[i] -= 2
+ bits[i - 1] += 1
+ bits[j + 1] += 2
+ bits[j] -= 1
+ i -= 1
+ while bits[i] == 0:
+ i -= 1
+ bits[i] -= 1 # (the reserved code goes)
+ order = sorted(syms, key=lambda s: (length[s], s == 256, s))[:-1]
+ out = {}
+ k = 0
+ for ln in range(1, 17):
+ for _ in range(bits[ln]):
+ out[order[k]] = ln
+ k += 1
+ return out
+
+
+def canonical(lengths):
+ """symbol -> length to (symbol -> (code, length), BITS[1..16], HUFFVAL)"""
+ order = sorted(lengths, key=lambda s: (lengths[s], s))
+ bits = [0] * 17
+ for s in order:
+ bits[lengths[s]] += 1
+ codes = {}
+ code = 0
+ k = 0
+ for ln in range(1, 17):
+ for _ in range(bits[ln]):
+ codes[order[k]] = (code, ln)
+ code += 1
+ k += 1
+ code <<= 1
+ return codes, bits[1:], order
+
+
+def decode_tables(bits, vals):
+ """BITS and HUFFVAL -> the decoder's tables: a LUT_BITS lookup (length << 8 | symbol, 0 when longer), then
+ for the slow way JPEG's maxcode (17 int32, -1 when none) and valoffset (17 int32), then HUFFVAL (256 bytes)"""
+ lut = [0] * (1 << LUT_BITS)
+ maxcode = [-1] * 18
+ valoff = [0] * 18
+ code = 0
+ k = 0
+ for ln in range(1, 17):
+ n = bits[ln - 1]
+ if n:
+ valoff[ln] = k - code
+ for _ in range(n):
+ if ln <= LUT_BITS:
+ base = code << (LUT_BITS - ln)
+ for j in range(1 << (LUT_BITS - ln)):
+ lut[base + j] = ln << 8 | vals[k]
+ code += 1
+ k += 1
+ maxcode[ln] = code - 1
+ code <<= 1
+ maxcode[17] = 0x7FFFFFFF
+ out = b"".join(v.to_bytes(2, "little") for v in lut)
+ out += b"".join(v.to_bytes(4, "little", signed=True) for v in maxcode)
+ out += b"".join(v.to_bytes(4, "little", signed=True) for v in valoff)
+ out += bytes(vals) + bytes(256 - len(vals))
+ return out
+
+
+class BitWriter:
+ def __init__(self):
+ self.out = bytearray()
+ self.acc = 0
+ self.n = 0
+
+ def put(self, v, n):
+ if n == 0:
+ return
+ self.acc = self.acc << n | (v & ((1 << n) - 1))
+ self.n += n
+ while self.n >= 8:
+ self.n -= 8
+ self.out.append(self.acc >> self.n & 0xFF)
+ self.acc &= (1 << self.n) - 1
+
+ def flush(self):
+ """pads with ones (like JPEG) to a byte"""
+ if self.n:
+ self.put((1 << (8 - self.n)) - 1, 8 - self.n)
+ return bytes(self.out)
+
+
+def encode_mcu(syms, tables):
+ """a square's symbols -> its bytes; tables[component class][0 DC, 1 AC][symbol] = (code, length)"""
+ w = BitWriter()
+ for comp, tab, sym, val, n in syms:
+ code, ln = tables[comp][tab][sym]
+ w.put(code, ln)
+ w.put(val, n)
+ return w.flush()
diff --git a/games/fnafworld/tools/pack.py b/games/fnafworld/tools/pack.py
new file mode 100644
index 00000000..c41f467b
--- /dev/null
+++ b/games/fnafworld/tools/pack.py
@@ -0,0 +1,386 @@
+#!/usr/bin/env python3
+"""FNAF World: its pictures, its map and fonts -> src/data.bin, src/data.h and src/anims.h.
+
+ python3 -I tools/pack.py [CCN] CCN: the game's data, written plain by ~/Documents/Assets/gamesrc/fnafworld/
+ tools/unpack.py from its fnaf-world.exe (Update 2); by default
+ ~/Documents/Assets/gamesrc/fnafworld/dl/app.ccn
+
+Every picture is the game's own, read by tools/ccn.py. The battle is the game's 800 x 480 screen at 0.4 (320 x 192),
+its characters, enemies and effects pictures with masks (tools/pics.py); the map is at 0.4 too (tools/world.py);
+title and menus at 0.5 (their middle 640 x 480).
+
+data.bin: "FNFW", the number of sections, their offsets, then the sections (SEC_* in data.h): HUFF, QUANT, PICS,
+TABLE, BANK, MASK (tools/pics.py), FONTS (as Five Nights at Freddy's 4's), IMGS (small 4-bit alpha pictures:
+u16 width, height, 4 bytes, the rows), SPRS and WORLD (tools/world.py).
+
+anims.h: the game's animations (AN_*): their pictures, speed (a picture each 100 / speed frames), how many times
+they play (0: for ever) and the picture they go back to."""
+import os
+import struct
+import sys
+
+import numpy as np
+from PIL import Image, ImageDraw, ImageFont
+
+HERE = os.path.dirname(os.path.abspath(__file__))
+sys.path.insert(0, HERE)
+import ccn # noqa: E402
+import pics # noqa: E402
+import world # noqa: E402
+
+OUT_BIN = os.path.join(HERE, "..", "src", "data.bin")
+OUT_H = os.path.join(HERE, "..", "src", "data.h")
+OUT_ANIMS = os.path.join(HERE, "..", "src", "anims.h")
+ROOT = os.path.join(HERE, "..", "..", "..")
+SECTIONS = ["HUFF", "QUANT", "PICS", "TABLE", "BANK", "MASK", "FONTS", "IMGS", "SPRS", "WORLD"]
+FONT_DIRS = [os.environ.get("FONTS", ""), "/usr/share/fonts/truetype/dejavu", "/usr/share/fonts/TTF",
+ "/usr/local/share/fonts", "/Library/Fonts", os.path.expanduser("~/Library/Fonts"),
+ os.path.expanduser("~/Documents/Assets/gamesrc/fonts/dejavu")]
+S = 0.4
+OW = "overworld"
+APP = None
+BANK = pics.Bank()
+ANIMS = [] # (key, [picture indexes], speed, plays, back)
+DEFINES = []
+
+
+def define(name, value):
+ DEFINES.append((name, value))
+
+
+def find_font(name):
+ for d in FONT_DIRS:
+ p = os.path.join(d, name) if d else ""
+ if p and os.path.exists(p):
+ return p
+ raise SystemExit(f"pack: {name} not found (the DejaVu fonts; FONTS=<their folder>)")
+
+
+def font(size, bold=False, mono=False):
+ name = "DejaVu" + ("SansMono" if mono else "Sans") + ("-Bold" if bold else "") + ".ttf"
+ return ImageFont.truetype(find_font(name), size)
+
+
+def arr(im):
+ return np.asarray(im.convert("RGB")).astype(np.float64)
+
+
+# ------------------------------------------------------------------ the game's pictures
+_BY_H = {}
+
+
+def spic(h, scale=S, quality="sprite", prev=None):
+ """the game's picture h as a picture with a mask (each once)"""
+ key = (h, scale)
+ if key not in _BY_H:
+ _BY_H[key] = BANK.sprite(f"H{h}_{int(scale * 100)}", APP.picture(h), scale, quality,
+ refs=[prev] if prev else [], hot=APP.hotspot(h)).index
+ return _BY_H[key]
+
+
+def anim(key, obj, a=0, d=0, scale=S, frame=OW, quality="sprite", keep=None):
+ """one of the game's animations: its pictures (each once) and its timing; keep: which pictures"""
+ o = obj if isinstance(obj, int) else APP.obj(obj, frame)
+ hs = APP.anim(o, a, d)
+ speed, plays, back = APP.speed(o, a, d)
+ idx, prev = [], None
+ for i, h in enumerate(hs):
+ if keep is not None and i not in keep:
+ continue
+ p = spic(h, scale, quality, BANK.pics[prev] if prev is not None else None)
+ idx.append(p)
+ prev = p
+ ANIMS.append((key, idx, speed, plays, min(back, len(idx) - 1)))
+ return key
+
+
+def screen_pic(name, im, x0=80, scale=0.5, quality="face", base=None):
+ """an 800 x 480 picture at scale, its 320 x 240 from x0 (in the scaled picture)"""
+ a = arr(im.convert("RGB").resize((round(im.width * scale), round(im.height * scale)), Image.LANCZOS))
+ return BANK.add(name, a[:240, x0:x0 + 320], None, quality, base=base).index
+
+
+def composite(frame, moves=None, skip=()):
+ """a frame of the game as it shows (its visible objects at their places), with some moved"""
+ f = APP.frames[frame]
+ c = Image.new("RGBA", (f.w, f.h), (0, 0, 0, 255))
+ for o, x, y, layer in sorted(f.placed, key=lambda t: t[3]):
+ kind, name, an, image = APP.objects[o]
+ if kind == 1 and image is not None:
+ h = image
+ elif kind == 2 and an and APP.visible[o]:
+ h = an[min(an)][0]
+ else:
+ continue
+ if o in skip or name in skip:
+ continue
+ if moves and o in moves:
+ x, y = moves[o](x, y)
+ hx, hy = APP.hotspot(h)
+ layer_im = Image.new("RGBA", (f.w, f.h))
+ layer_im.paste(APP.picture(h), (x - hx, y - hy))
+ c.alpha_composite(layer_im)
+ return c
+
+
+def char_anim(c):
+ """character c (1 to 48)'s animation number in "character" and "attack" (the events 30-77, 419-466)"""
+ return 0 if c == 1 else c + 10 if c <= 40 else c + 11
+
+
+def battle():
+ for c in range(1, 49):
+ anim(f"IDLE{c}", "character", char_anim(c))
+ anim(f"ATTACK{c}", "attack", char_anim(c))
+ anim("KO", "character", 51)
+ tg = APP.obj("target", OW)
+ for a in [0] + list(range(12, 41)):
+ anim(f"ENEMY{a}", tg, a)
+ c2 = APP.obj("character 2", OW)
+ for c in range(9, 41):
+ anim(f"CHAL{c}", c2, c + 10)
+ for a in range(51, 64):
+ anim(f"BOSS{a}", c2, a)
+ # the scenes: each "background" as the battle's camera shows it (the view from 23, 14)
+ for n, nm in ((0, "background"), (2, "background 2"), (3, "background 3"), (4, "background 4"),
+ (5, "background 5"), (6, "background 6"), (7, "background 7"), (8, "background 8"),
+ (9, "background 9"), (11, "background 11")):
+ h = APP.anim(nm, 0, 0, OW)[0]
+ im = APP.picture(h).convert("RGB").crop((23, 14, 823, 494)).resize((320, 192), Image.LANCZOS)
+ p = BANK.add(f"BG{n}", arr(im), None, "scene")
+ define(f"PIC_BG{n}", p.index)
+ # the effects
+ ae = APP.obj("attack effect", OW)
+ for a in [0] + list(range(12, 22)):
+ anim(f"HIT{a}", ae, a)
+ anim("SPARK", "Active 5", 0)
+ for key, obj, a in (("MICSPIN", "micspin", 0), ("PIZZA", "pizza", 0), ("PIZZA2", "pizza", 12),
+ ("BITE", "bite", 0), ("BITE2", "bite 2", 0), ("BITE3", "bite 3", 0), ("MEGABITE", "megabite", 0),
+ ("BITE4", "bite 4", 0), ("TOXICBITE", "toxic bite", 0), ("HOOK", "Hook", 0),
+ ("SCARE", "Active 8", 0), ("NOTE", "happy note", 0), ("NOTE2", "happy note", 12),
+ ("TORNADO", "Active 7", 0), ("CLAW", "claw", 0), ("CLAW2", "claw", 12), ("DIZZY", "confused 2", 0),
+ ("BROKEN", "broken", 0), ("POW", "pow", 0), ("STAR", "star", 0), ("CLOUD", "cloud", 0),
+ ("PRIZE", "prize ball", 12), ("PRIZE2", "prize ball", 15), ("POPPER", "popper", 12),
+ ("MUNCHIE", "munchie", 0), ("MUNCHIE2", "munchie", 12), ("HEAD", "head", 0),
+ ("FREDDLE", "Freddle", 0), ("BADPIZZA", "bad pizza", 0), ("ENDO", "endo army", 12),
+ ("ENDO2", "endo army", 13), ("DAGGER", "dagger", 0), ("SAW", "saw", 0),
+ ("JACKO", "Active 35", 0), ("ANTI", "anti", 0), ("GIFT", "gift p 1", 0),
+ ("MIMIC", "mimic", 0), ("MIMIC2", "mimic", 12), ("SCREW", "screw", 0),
+ ("DRIP", "cheese drip", 0), ("BADNOTE", "bad note", 0), ("SYTH", "syth", 0),
+ ("STINGER", "stinger", 0), ("PBUBBLE", "P bubble", 0), ("SPARKLE", "sparkle1", 0),
+ ("VICTORY", "victory", 0), ("LEVELUP", "level up", 0), ("RUN", "run", 0),
+ ("CHALLENGER", "Active 26", 0), ("NEWMEMBER", "new member", 0), ("WALL", "wall", 0),
+ ("BUBBLE", "bubble", 0), ("DOWN", "down", 0), ("DOWN2", "down", 12), ("DOWN3", "down", 13)):
+ anim(key, obj, a)
+ for k, a in enumerate((0, 12, 13, 14)):
+ anim(f"BALLOON{k}", "balloon", a)
+ anim("WATER", "water", 0, keep=range(0, 6, 2))
+ anim("WATER2", "water", 13, keep=range(0, 6, 2))
+ anim("PUDDLE", "cheese puddle", 4)
+ anim("SHIELD", "shield", 0, scale=0.4)
+ eat = APP.obj("enemy attack", OW)
+ for a in [0] + list(range(12, 22)):
+ anim(f"SPECIAL{a}", eat, a)
+ bi = APP.obj("Byte Icon", OW)
+ for b in range(1, 22):
+ anim(f"BYTE{b}", bi, 0 if b == 1 else b + 10)
+
+
+def menus():
+ # the title as it ends up (the logo slid in, the characters up, the button in)
+ f = APP.frames["title screen"]
+ moves = {}
+ for o, x, y, layer in f.placed:
+ n = APP.objects[o][1]
+ if n == "Active 2" and x < 0:
+ moves[o] = lambda x, y: (x + 800, y)
+ elif n == "Active" and x > 900:
+ moves[o] = lambda x, y: (x - 550, y)
+ elif n == "Active 3":
+ moves[o] = lambda x, y: (x, y - 416)
+ define("PIC_TITLE", screen_pic("TITLE", composite("title screen", moves, skip=("Active 32",))))
+ bg = APP.anim(APP.find("Active", "file setup")[0], 0, 0)[0]
+ define("PIC_MENU", screen_pic("MENU", APP.picture(bg).convert("RGB")))
+ # the buttons (the game's own, their words in them)
+ for key, name in (("NEWGAME", "new game"), ("CONTINUE", "continue"), ("YES", "YES"), ("NO", "NO"),
+ ("ADVENTURE", "adventure button"), ("FIXED", "fixed party text"), ("NORMAL", "normal"),
+ ("HARD", "hard"), ("SLOT", "file slot 1")):
+ o = APP.find(name, "file setup")[0]
+ define(f"PIC_B_{key}", spic(APP.anim(o, 0, 0)[0], 0.5, "face"))
+ # the character select's faces (each "char" animation's picture)
+ o = APP.find("char", "character select")[0]
+ for c in range(1, 49):
+ h = APP.anim(o, 0 if c == 1 else c + 10, 0)[0] # (no gap at 51 here: the events 52-72)
+ im = APP.picture(h).convert("RGBA")
+ bgc = Image.new("RGBA", im.size, (24, 24, 48, 255))
+ bgc.alpha_composite(im)
+ a = arr(bgc.resize((28, 28), Image.LANCZOS))
+ p = BANK.add(f"FACE{c}", np.pad(a, ((0, 4), (0, 4), (0, 0)), mode="edge"), None, "face")
+ if c == 1:
+ define("PIC_FACE1", p.index)
+ for k, n in enumerate(("trophy1", "trophy 2", "trophy 3", "pixel trophy", "spirit trophy", "end trophy", "trophy 4")):
+ o = APP.find(n, "file setup")[0]
+ define(f"PIC_TROPHY{k + 1}", spic(APP.anim(o, 0, 0)[0], 0.4, "face"))
+
+
+# ------------------------------------------------------------------ fonts and small pictures
+def nibbles(alpha):
+ h, w = alpha.shape
+ out = bytearray()
+ for r in range(h):
+ row = list(alpha[r]) + [0]
+ for c in range(0, w, 2):
+ out.append(int(row[c]) | int(row[c + 1]) << 4)
+ return bytes(out)
+
+
+def to4(a):
+ return np.clip(np.round(np.asarray(a, dtype=np.float64) / 255 * 15), 0, 15).astype(np.uint8)
+
+
+def ttf_font(f, line=None):
+ asc, desc = f.getmetrics()
+ line = line or asc + desc
+ glyphs = []
+ for c in range(32, 127):
+ ch = chr(c)
+ adv = int(round(f.getlength(ch)))
+ box = f.getbbox(ch)
+ if box[2] <= box[0] or ch == " ":
+ glyphs.append((adv, 0, 0, 0, 0, b""))
+ continue
+ im = Image.new("L", (box[2] - box[0], box[3] - box[1]))
+ ImageDraw.Draw(im).text((-box[0], -box[1]), ch, font=f, fill=255)
+ glyphs.append((adv, im.width, im.height, box[0], box[1], nibbles(to4(np.asarray(im)))))
+ return line, asc, glyphs
+
+
+def pack_fonts(fonts):
+ blobs = []
+ for line, asc, glyphs in fonts:
+ b = struct.pack("<BBBB", line, asc, 32, 95)
+ rows, offs = b"", []
+ for adv, w, h, x, y, r in glyphs:
+ offs.append(len(rows))
+ rows += r
+ g0 = len(b) + 12 * 95
+ for (adv, w, h, x, y, r), o in zip(glyphs, offs):
+ b += struct.pack("<BBBbbBHI", adv, w, h, x, y, 0, 0, g0 + o)
+ blobs.append(b + rows)
+ out = struct.pack("<I", len(fonts))
+ p = 4 + 4 * len(fonts)
+ for b in blobs:
+ out += struct.pack("<I", p)
+ p += len(b)
+ return out + b"".join(blobs)
+
+
+IMGS = []
+
+
+def img(name, alpha):
+ a = to4(alpha)
+ h, w = a.shape
+ define(f"IMG_{name}", len(IMGS))
+ IMGS.append(struct.pack("<HHBBH", w, h, 0, 0, 0) + nibbles(a))
+
+
+def pack_imgs():
+ out = struct.pack("<I", len(IMGS))
+ p = 4 + 4 * len(IMGS)
+ for d in IMGS:
+ out += struct.pack("<I", p)
+ p += len(d) + (-len(d) % 4)
+ return out + b"".join(d + bytes(-len(d) % 4) for d in IMGS)
+
+
+def icons():
+ """the arrow, the chip pictures"""
+ up = Image.new("L", (9, 6))
+ ImageDraw.Draw(up).polygon([(0, 5), (4, 0), (8, 5)], fill=255)
+ img("UP", np.asarray(up))
+ img("DOWN", np.asarray(up)[::-1])
+ k = Image.new("L", (13, 9)) # the backspace key
+ d = ImageDraw.Draw(k)
+ d.polygon([(0, 4), (4, 0), (12, 0), (12, 8), (4, 8)], outline=255)
+ d.line([(6, 2), (10, 6)], fill=255)
+ d.line([(6, 6), (10, 2)], fill=255)
+ img("DEL", np.asarray(k))
+
+
+def make_icon():
+ sys.path.insert(0, os.path.join(ROOT, "tools"))
+ from make_icon import corner_mask
+ o = APP.find("char", "character select")[0]
+ im = APP.picture(APP.anim(o, 0, 0)[0]).convert("RGBA")
+ c = Image.new("RGBA", im.size, (40, 90, 200, 255))
+ c.alpha_composite(im)
+ c = c.convert("RGB").resize((55, 56), Image.LANCZOS)
+ c.putalpha(corner_mask(55, 56))
+ c.save(os.path.join(HERE, "..", "src", "icon.png"), optimize=True)
+
+
+def write_anims():
+ flat, lines = [], []
+ for key, idx, speed, plays, back in ANIMS:
+ lines.append((key, len(flat), len(idx), speed, plays, back))
+ flat += idx
+ h = ["/* Made by tools/pack.py: the game's animations (AN_*), its own speeds and plays. Included once (anim.c). */",
+ "#ifndef FNAFW_ANIMS_H", "#define FNAFW_ANIMS_H", "#include <stdint.h>", "",
+ "typedef struct {", " uint16_t first; /* in ANIM_PICS */",
+ " uint8_t n, speed, plays, back; /* a picture lasts 100 / speed frames; plays 0: for ever */",
+ "} AnimDef;", ""]
+ h.append("enum {")
+ h += [f" AN_{k}," for k, *_ in lines]
+ h += [" AN_COUNT", "};", ""]
+ h.append("static const uint16_t ANIM_PICS[] = {")
+ for i in range(0, len(flat), 16):
+ h.append(" " + ", ".join(str(v) for v in flat[i:i + 16]) + ",")
+ h += ["};", "", "static const AnimDef ANIMS[AN_COUNT] = {"]
+ h += [f" {{{f}, {n}, {s}, {min(p, 255)}, {b}}}, /* {k} */" for k, f, n, s, p, b in lines]
+ h += ["};", "", "#endif", ""]
+ open(OUT_ANIMS, "w").write("\n".join(h))
+
+
+def main():
+ global APP
+ APP = ccn.App(sys.argv[1] if len(sys.argv) > 1 else ccn.CCN)
+ menus()
+ battle()
+ icons()
+ make_icon()
+ wdata, wdefs = world.build(APP)
+ DEFINES.extend(wdefs)
+ huff, quant, pics_, table, bank, masks = BANK.encode()
+ fonts = [
+ ttf_font(font(11, bold=True)), # FONT_SMALL
+ ttf_font(font(13, bold=True)), # FONT_TEXT
+ ttf_font(font(18, bold=True)), # FONT_BIG
+ ttf_font(font(10, bold=True, mono=True)), # FONT_NUM
+ ttf_font(font(26, bold=True)), # FONT_HUGE
+ ]
+ sections = [huff, quant, pics_, table, bank, masks, pack_fonts(fonts), pack_imgs(), world.pack_sprites(), wdata]
+ head = b"FNFW" + struct.pack("<I", len(sections))
+ offs, p = [], len(head) + 4 * len(sections)
+ for s in sections:
+ offs.append(p)
+ p += len(s) + (-len(s) % 4)
+ out = head + b"".join(struct.pack("<I", o) for o in offs)
+ for s in sections:
+ out += s + bytes(-len(s) % 4)
+ open(OUT_BIN, "wb").write(out)
+ h = ["/* Made by tools/pack.py: what is in data.bin. */", "#ifndef FNAFW_DATA_H", "#define FNAFW_DATA_H", ""]
+ h += [f"#define SEC_{n} {i}" for i, n in enumerate(SECTIONS)]
+ h += [f"#define PIC_COUNT {len(BANK.pics)}"]
+ h += [f"#define FONT_{n} {i}" for i, n in enumerate(["SMALL", "TEXT", "BIG", "NUM", "HUGE"])]
+ h += [f"#define {n} {v}" for n, v in DEFINES]
+ h += ["", "#endif", ""]
+ open(OUT_H, "w").write("\n".join(h))
+ write_anims()
+ for name, s in zip(SECTIONS, sections):
+ print(f" {name}: {len(s)} bytes")
+ print(f"data.bin: {len(out)} bytes")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/games/fnafworld/tools/pics.py b/games/fnafworld/tools/pics.py
new file mode 100644
index 00000000..2ba0e867
--- /dev/null
+++ b/games/fnafworld/tools/pics.py
@@ -0,0 +1,209 @@
+"""FNAF World's pictures for src/pic.c: JPEG-coded 16 x 16 squares (tools/codec.py), with or without a mask.
+
+A picture is a grid of squares (each coded alone, as in Five Nights at Freddy's 4). The battle's characters, enemies
+and effects stand over the scene, so they also have a mask: their alpha in 4 levels (0 clear, 3 solid), row by row,
+each row runs of one level (a byte: level << 6 | length - 1). Squares that are clear all through are not coded, and
+under the clear pixels the colours are spread from the solid ones, which keeps the coded squares small.
+
+PICS: 16 bytes a picture: width and height in squares, its quality, flags (1: a mask), its hot spot (i16 x, y: where
+it is drawn from, in pixels from its top left corner), the picture it shares squares with (u16, 0xFFFF none), how many
+squares it has of its own then (u16), where its table starts (u32). TABLE: with a mask first where it starts in MASK
+(u32), then each square's place in BANK (u24, 0xFFFFFF clear) or, sharing, the squares that differ (u16 the square,
+u24 its place). MASK: for each row of squares where its rows start (u16, from the mask's start), then the rows."""
+import struct
+
+import numpy as np
+from PIL import Image
+
+import codec as C
+
+QUALITY = {"scene": 78, "sprite": 70, "face": 80}
+QNAMES = list(QUALITY)
+
+
+def pad16(a):
+ h, w = a.shape[:2]
+ H, W = -(-h // 16) * 16, -(-w // 16) * 16
+ return np.pad(a, ((0, H - h), (0, W - w)) + ((0, 0),) * (a.ndim - 2), mode="edge" if a.ndim == 3 else "constant")
+
+
+def spread(rgb, solid):
+ """the colours of the solid pixels spread over the clear ones (so the squares code small)"""
+ out = rgb * solid[..., None]
+ w = solid.astype(np.float64)
+ for _ in range(10):
+ k = lambda x: x + np.roll(x, 1, 0) + np.roll(x, -1, 0) + np.roll(x, 1, 1) + np.roll(x, -1, 1)
+ s = np.stack([k(out[..., i]) for i in range(3)], -1)
+ ww = k(w)
+ fill = (w == 0) & (ww > 0)
+ if not fill.any():
+ break
+ out[fill] = s[fill] / ww[fill][:, None]
+ w = np.where(fill, 1.0, w)
+ if (w == 0).any():
+ out[w == 0] = rgb[solid > 0].mean(axis=0) if solid.any() else 0
+ return out
+
+
+def mask_rows(a2):
+ """a mask (rows of levels 0 to 3) -> its bytes: the start of each row of squares, then the rows' runs"""
+ H, W = a2.shape
+ rows = []
+ for r in range(H):
+ row = a2[r]
+ b = bytearray()
+ i = 0
+ while i < W:
+ j = i
+ while j < W and row[j] == row[i] and j - i < 64:
+ j += 1
+ b.append(int(row[i]) << 6 | (j - i - 1))
+ i = j
+ rows.append(bytes(b))
+ head, body = [], bytearray()
+ for r in range(H):
+ if r % 16 == 0:
+ head.append(len(body))
+ body += rows[r]
+ n = len(head)
+ out = b"".join(struct.pack("<H", 2 * n + h) for h in head) + bytes(body)
+ assert len(out) < 65536
+ return out
+
+
+class Pic:
+ def __init__(self, name, rgb, alpha, quality, hot, base=None, refs=()):
+ self.name, self.q, self.base = name, quality, base
+ self.hot = hot
+ self.a = pad16(np.clip(rgb, 0, 255).astype(np.float64))
+ self.mask = None
+ if alpha is not None:
+ al = pad16(alpha.astype(np.float64))
+ # three levels: clear, half (the edges, the shadows) and solid; fewer runs than four
+ a2 = np.where(al < 72, 0, np.where(al < 200, 2, 3)).astype(np.uint8)
+ self.mask = a2
+ self.a = spread(self.a, (a2 >= 2).astype(np.float64) if (a2 >= 2).any() else (a2 > 0).astype(np.float64))
+ self.refs = [r for r in ([base] if base else []) + list(refs) if r]
+ self.mh, self.mw = self.a.shape[0] // 16, self.a.shape[1] // 16
+
+
+class Bank:
+ def __init__(self):
+ self.pics = []
+ self.by_name = {}
+
+ def add(self, name, rgb, alpha=None, quality="scene", hot=(0, 0), base=None, refs=()):
+ assert name not in self.by_name, name
+ p = Pic(name, rgb, alpha, quality, hot, base, refs)
+ p.index = len(self.pics)
+ self.pics.append(p)
+ self.by_name[name] = p
+ return p
+
+ def sprite(self, name, im, scale, quality="sprite", refs=(), hot=(0, 0), trim=True):
+ """an RGBA picture at scale with its hot spot (in the source picture), trimmed to what shows"""
+ w, h = max(1, round(im.width * scale)), max(1, round(im.height * scale))
+ a = np.asarray(im.convert("RGBA").resize((w, h), Image.LANCZOS)).astype(np.float64)
+ al = a[..., 3]
+ ys, xs = np.nonzero(al > 40)
+ if trim and len(ys):
+ y0, y1, x0, x1 = ys.min(), ys.max() + 1, xs.min(), xs.max() + 1
+ else:
+ y0, y1, x0, x1 = 0, h, 0, w
+ hx, hy = round(hot[0] * scale) - x0, round(hot[1] * scale) - y0
+ return self.add(name, a[y0:y1, x0:x1, :3], al[y0:y1, x0:x1], quality, (hx, hy), refs=refs)
+
+ def encode(self):
+ qt = {k: (C.qtable(C.STD_LUMA, v), C.qtable(C.STD_CHROMA, v)) for k, v in QUALITY.items()}
+ for p in self.pics:
+ y, cb, cr = C.ycbcr(p.a)
+ ql, qc = qt[p.q]
+ yq = C.quantize(C.blocks_of(y), ql, 0.18)
+ cbq = C.quantize(C.blocks_of(cb), qc, 0.22)
+ crq = C.quantize(C.blocks_of(cr), qc, 0.22)
+ p.sq = []
+ for my in range(p.mh):
+ for mx in range(p.mw):
+ if p.mask is not None and not p.mask[my * 16:my * 16 + 16, mx * 16:mx * 16 + 16].any():
+ p.sq.append(None)
+ continue
+ src = None
+ tile = p.a[my * 16:my * 16 + 16, mx * 16:mx * 16 + 16]
+ for r in p.refs:
+ if mx < r.mw and my < r.mh and r.q == p.q and r.sq[my * r.mw + mx] is not None:
+ d = np.abs(tile - r.a[my * 16:my * 16 + 16, mx * 16:mx * 16 + 16])
+ strict = r is not p.base
+ if d.max() <= (6 if strict else 14) and d.mean() <= (1.2 if strict else 3.0):
+ src = r.sq[my * r.mw + mx]
+ break
+ if src is None:
+ blocks = [yq[2 * my + i, 2 * mx + j] for i in (0, 1) for j in (0, 1)]
+ src = ("own", tuple(C.mcu_symbols(blocks, cbq[my, mx], crq[my, mx])))
+ p.sq.append(src)
+ freq = [[{}, {}], [{}, {}]]
+ seen = set()
+ for p in self.pics:
+ for s in p.sq:
+ if s is None or id(s) in seen:
+ continue
+ seen.add(id(s))
+ for comp, tab, sym, _, _ in s[1]:
+ f = freq[comp][tab]
+ f[sym] = f.get(sym, 0) + 1
+ tables, huff = [[None, None], [None, None]], b""
+ for comp in (0, 1):
+ for tab in (0, 1):
+ codes, bits, vals = C.canonical(C.huffman_lengths(freq[comp][tab]))
+ tables[comp][tab] = codes
+ huff += C.decode_tables(bits, vals)
+ bank, where, by_id = bytearray(), {}, {}
+ for p in self.pics:
+ p.off = []
+ for s in p.sq:
+ if s is None:
+ p.off.append(0xFFFFFF)
+ continue
+ if id(s) not in by_id:
+ data = C.encode_mcu(s[1], tables)
+ if data not in where:
+ where[data] = len(bank)
+ bank += data
+ by_id[id(s)] = where[data]
+ p.off.append(by_id[id(s)])
+ bank += bytes(8)
+ assert len(bank) < 0xFFFFFF
+ quant = b""
+ for k in QNAMES:
+ for t in qt[k]:
+ quant += b"".join(struct.pack("<H", (int(t[i]) * C.AANSCALES[i] + 2048) >> 12) for i in range(64))
+ masks, mask_at = bytearray(b"\0\0\0\0"), {}
+ pics, table = b"", bytearray()
+ for p in self.pics:
+ flags = 0
+ head = b""
+ if p.mask is not None:
+ m = mask_rows(p.mask)
+ if m not in mask_at:
+ mask_at[m] = len(masks)
+ masks += m
+ flags |= 1
+ head = struct.pack("<I", mask_at[m])
+ diff = []
+ if p.base:
+ b = p.base
+ assert (b.mw, b.mh) == (p.mw, p.mh) and not b.base
+ diff = [k for k in range(len(p.off)) if p.off[k] != b.off[k]]
+ if p.base and 5 * len(diff) < 3 * len(p.off):
+ pics += struct.pack("<BBBBhhHHI", p.mw, p.mh, QNAMES.index(p.q), flags, p.hot[0], p.hot[1],
+ p.base.index, len(diff), len(table))
+ table += head
+ for k in diff:
+ table += struct.pack("<H", k) + p.off[k].to_bytes(3, "little")
+ else:
+ pics += struct.pack("<BBBBhhHHI", p.mw, p.mh, QNAMES.index(p.q), flags, p.hot[0], p.hot[1],
+ 0xFFFF, 0, len(table))
+ table += head
+ for o in p.off:
+ table += o.to_bytes(3, "little")
+ print(f"pictures: {len(self.pics)}, squares {len(bank)} bytes, masks {len(masks)}, tables {len(table)}")
+ return huff, quant, pics, bytes(table), bytes(bank), bytes(masks)
diff --git a/games/fnafworld/tools/world.py b/games/fnafworld/tools/world.py
new file mode 100644
index 00000000..af54e3fb
--- /dev/null
+++ b/games/fnafworld/tools/world.py
@@ -0,0 +1,239 @@
+"""FNAF World's overworld for tools/pack.py: the 6000 x 4000 map as the game lays it out (its frame "overworld").
+
+Drawn at 0.4 (the game's 50-pixel grid is 20 pixels here). What never changes is a list of pictures placed in the
+game's own order (its layers, the backdrops of a layer under its actives); the ground is the big tiled backdrops of
+the bottom layer, kept as rectangles and their tile. Pictures are raw 16-bit colour with 4-bit alpha (SPRS: u16 width,
+height, i16 hot spot x, y, u16 flags: 1 no alpha, u16 0, the pixels, then the alpha rows), fast to draw many of.
+
+What the game's events act on (chests, bosses, switches, barriers, shops, the area zones...) is listed apart with
+its box in the game's coordinates, and drawn by src/world.c as their state says. Walls: the obstacle backdrops,
+a bit for each 10 x 10 pixels of the map (the game's feelers test them)."""
+import struct
+
+import numpy as np
+from PIL import Image
+
+S = 0.4
+CELL = 10
+SPR = [] # blobs
+_SPR = {}
+
+
+def ink_hidden(app, o):
+ ink, param = app.ink[o]
+ return bool(ink & 0x1000) and (param >> 24) == 0
+
+
+def sprite(app, h, scale=S, opaque=False, size=None):
+ """a picture as a raw sprite (shared when used again)"""
+ key = (h, scale, opaque, size)
+ if key in _SPR:
+ return _SPR[key]
+ im = app.picture(h)
+ hx, hy = app.hotspot(h)
+ w, hh = size or (max(1, round(im.width * scale)), max(1, round(im.height * scale)))
+ a = np.asarray(im.resize((w, hh), Image.LANCZOS)).astype(np.int32)
+ rgb = ((a[..., 0] >> 3) << 11) | ((a[..., 1] >> 2) << 5) | (a[..., 2] >> 3)
+ blob = struct.pack("<HHhhHH", w, hh, round(hx * scale), round(hy * scale), 1 if opaque else 0, 0)
+ blob += rgb.astype("<u2").tobytes()
+ if not opaque:
+ al = np.clip(np.round(a[..., 3] / 255 * 15), 0, 15).astype(np.uint8)
+ for r in range(hh):
+ row = list(al[r]) + [0]
+ blob += bytes(int(row[c]) | int(row[c + 1]) << 4 for c in range(0, w, 2))
+ _SPR[key] = len(SPR)
+ SPR.append(blob)
+ return _SPR[key]
+
+
+def pack_sprites():
+ out = struct.pack("<I", len(SPR))
+ p = 4 + 4 * len(SPR)
+ for b in SPR:
+ out += struct.pack("<I", p)
+ p += len(b) + (-len(b) % 4)
+ return out + b"".join(b + bytes(-len(b) % 4) for b in SPR)
+
+
+# what the events act on: name -> (kind, number); the kinds are src/world.h's O_*
+CHESTS = [f"minor chest {k}" for k in range(1, 8)] + [f"Chest {k}" for k in range(1, 8)] + \
+ [f"red chest {k}" for k in range(1, 8)]
+BOSSES = {"boss 1": 1, "seagoon boss": 2, "guard chest": 3, "guard chest 2": 4, "brow boy": 5, "guard chest 3": 6,
+ "showstopper": 7, "showstopper 2": 8, "snowman": 9, "snowman 2": 11, "showstopper 3": 12,
+ "guard chest 4": 13, "owl": 14, "ch": 15, "Active 30": 19, "4": 10}
+BARRIERS = {"barrier 1": 1, "barrier 2": 2, "barrier 3": 3, "fence block": 4, "Active 29": 5, "final barrier": 6,
+ "final barrier 2": 7, "final barrier 3": 8, "final barrier 4": 9, "locked": 10}
+ZONES = {"+ 0": 0, "+2": 2, "+ 5": 5, "+ 8": 8, "+ 11": 11, "+ 14": 14, "+ 17": 17, "+ 20": 20, "+ 23": 23,
+ "+ 26": 26, "+ 40": 50}
+KINDS = ["ZONE", "CHEST", "COINS", "BOSS", "SWITCH", "BARRIER", "SHOP", "KEY", "PORT"]
+# the ways from place to place (events 1168-1185, 1395-1396, 1465-1504): touching (0), holding up a while (75 or
+# 25 frames: 1, 2) or pressing down (3) on the first sends the walker to the second's place plus (dx, dy)
+PORTS = [("enter mine", "mine entrance", 1, -43, 0), ("mine entrance", "enter mine", 28, 60, 0),
+ ("grave entrance", "grave entrance 2", 3, 61, 0), ("grave entrance 2", "grave entrance", -8, -49, 0),
+ ("mine entrance 2", "mine entrance 4", 1, -47, 0), ("mine entrance 3", "mine entrance 5", 3, -49, 0),
+ ("mine entrance 4", "mine entrance 2", 0, 52, 0), ("mine entrance 5", "mine entrance 3", 29, 58, 0),
+ ("whirlpool", "whirlpool 2", -1, -43, 0), ("whirlpool 2", "whirlpool", 0, 55, 0),
+ ("Active 22", "circus entrance", 2, -46, 0), ("circus entrance", "Active 22", -1, 63, 0),
+ ("secret", "secret 2", 77, 25, 0), ("secret 2", "secret", -25, 28, 0),
+ ("enter tent", "circus dungeon entr", -1, -42, 1), ("circus dungeon entr", "enter tent", 0, 44, 0),
+ ("layer 1", "layer 2", 0, -78, 1), ("layer 2", "layer 1", 1, 44, 3),
+ ("layer 3", "layer 4", 1, -86, 1), ("layer 4", "layer 3", -1, 28, 3),
+ ("layer 5", "layer 6", 1, -61, 1), ("layer 6", "layer 5", 0, 25, 3),
+ ("enter mine 2", "enter tent 2", 1, 47, 0), ("enter tent 2", "enter mine 2", 6, -62, 2),
+ ("Active 27", "Active 28", 24, 75, 0), ("Active 28", "Active 27", 25, -28, 0)]
+for a, b, x, y in ((1, 9, 26, -28), (2, 7, 87, 29), (3, 8, 25, -30), (4, 10, -29, 26), (5, 11, 79, 27), (7, 2, -31, 29),
+ (8, 3, 25, 76), (9, 1, 25, 75), (10, 4, 80, 29), (11, 5, -27, 30), (6, 4, 78, 29), (12, 20, -25, 27),
+ (13, 16, 74, 31), (14, 6, -25, 27), (15, 3, 24, 77), (20, 12, 77, 29), (16, 13, -25, 28),
+ (17, 1, 24, 75), (18, 3, 25, 77), (19, 23, 25, 79), (23, 19, 24, -23), (21, 1, 23, 77),
+ (22, 24, -27, 31), (24, 22, 75, 27)):
+ PORTS.append((f"treetentportal {a}", f"treetentportal {b}", x, y, 0))
+
+
+def build(app):
+ """-> (WORLD section bytes, defines)"""
+ f = app.frames["overworld"]
+ defines = []
+ inst = [] # (layer, order, x, y, sprite)
+ ground = [] # (x, y, w, h, sprite) scaled
+ objs = [] # (kind, n, x0, y0, x1, y1, sprite0, sprite1) game coords
+ walls = np.zeros((f.h // CELL, f.w // CELL), dtype=bool)
+
+ def box(h, x, y):
+ hx, hy = app.hotspot(h)
+ w, hh = app.size(h)
+ return x - hx, y - hy, x - hx + w, y - hy + hh
+
+ def wall_pic(h, x0, y0, fine):
+ im = app.picture(h)
+ if fine:
+ a = np.asarray(im)[..., 3] > 0
+ else:
+ a = np.ones((im.height, im.width), dtype=bool)
+ H, W = a.shape
+ for cy in range(max(0, y0 // CELL), min(walls.shape[0], (y0 + H + CELL - 1) // CELL)):
+ for cx in range(max(0, x0 // CELL), min(walls.shape[1], (x0 + W + CELL - 1) // CELL)):
+ ys, xs = cy * CELL - y0, cx * CELL - x0
+ part = a[max(0, ys):max(0, ys + CELL), max(0, xs):max(0, xs + CELL)]
+ if part.size and part.mean() >= 0.5:
+ walls[cy, cx] = True
+
+ def battle_spot(x, y):
+ return x < 880 and y < 560
+
+ chest_n = {n: k + 1 for k, n in enumerate(CHESTS)}
+ where = {}
+ for o, x, y, layer in f.placed:
+ if layer <= 2:
+ where.setdefault(app.objects[o][1], (x, y))
+ port_of = {}
+ for a, b, dx, dy, mode in PORTS:
+ bx, by = where[b]
+ port_of[a] = (bx + dx, by + dy, mode)
+ for order, (o, x, y, layer) in enumerate(f.placed):
+ if layer > 2:
+ continue
+ kind, name, anims, image = app.objects[o]
+ if kind == 1 and image is not None:
+ if ink_hidden(app, o) and not app.obstacle[o]:
+ continue
+ x0, y0, x1, y1 = box(image, x, y)
+ if battle_spot(x, y):
+ continue
+ if app.obstacle[o]:
+ wall_pic(image, x0, y0, app.fine[o])
+ if not ink_hidden(app, o):
+ inst.append((layer, 0, order, round(x0 * S), round(y0 * S), sprite(app, image)))
+ elif kind == 0 and image and image[2] is not None:
+ w, hh, pat, _ = image
+ if battle_spot(x, y):
+ continue
+ tw, th = app.size(pat)
+ if app.obstacle[o]:
+ for ty in range(0, hh, th):
+ for tx in range(0, w, tw):
+ wall_pic(pat, x + tx, y + ty, app.fine[o])
+ if layer == 0 and (np.asarray(app.picture(pat))[..., 3] == 255).all():
+ sw, sh = max(1, round(tw * S)), max(1, round(th * S))
+ ground.append((round(x * S), round(y * S), round(w * S), round(hh * S),
+ sprite(app, pat, opaque=True, size=(sw, sh))))
+ else:
+ for ty in range(0, hh, th):
+ for tx in range(0, w, tw):
+ hx, hy = app.hotspot(pat)
+ inst.append((layer, 0, order, round((x + tx) * S), round((y + ty) * S),
+ sprite(app, pat)))
+ elif kind == 2 and anims:
+ if battle_spot(x, y) or (x, y) == (0, 0):
+ continue
+ h = anims[min(anims)][0]
+ x0, y0, x1, y1 = box(h, x, y)
+ if name in chest_n:
+ objs.append((1, chest_n[name], x0, y0, x1, y1, sprite(app, h), 0))
+ elif name in ("small coin chest", "big coin chest"):
+ continue # (made by events)
+ elif name in BOSSES:
+ vis = app.visible[o]
+ objs.append((3, BOSSES[name], x0, y0, x1, y1, sprite(app, h) if vis else 0xFFFF, 0))
+ elif name.startswith("switch "):
+ a12 = anims.get((12, 0), anims[min(anims)])
+ objs.append((4, int(name.split()[1]), x0, y0, x1, y1, sprite(app, h), sprite(app, a12[0])))
+ elif name in BARRIERS:
+ objs.append((5, BARRIERS[name], x0, y0, x1, y1, sprite(app, h), 0))
+ elif name in ZONES:
+ objs.append((0, ZONES[name], x0, y0, x1, y1, 0xFFFF, 0))
+ elif name in ("shop", "shop 2", "shop 3"):
+ objs.append((6, {"shop": 1, "shop 2": 2, "shop 3": 3}[name], x0, y0, x1, y1, sprite(app, h), 0))
+ elif name == "key":
+ objs.append((7, 1, x0, y0, x1, y1, sprite(app, h), 0))
+ elif name in port_of:
+ tx, ty, mode = port_of[name]
+ objs.append((8, mode, x0, y0, x1, y1, tx, ty))
+ if app.visible[o] and not ink_hidden(app, o):
+ inst.append((layer, 1, order, round(x0 * S), round(y0 * S), sprite(app, h)))
+ elif app.visible[o] and not ink_hidden(app, o):
+ inst.append((layer, 1, order, round(x0 * S), round(y0 * S), sprite(app, h)))
+ inst.sort(key=lambda t: (t[0], t[1], t[2]))
+ # the walker: "Active 16", anim 1 in 4 directions (0 right, 8 up, 16 left, 24 down), anim 0 standing
+ walker = app.obj("Active 16", "overworld")
+ wa = app.anims(walker)
+ first = len(SPR)
+ for d in (0, 8, 16, 24):
+ for h in wa[(1, d)]:
+ sprite(app, h)
+ stand = sprite(app, wa[(0, 24)][0])
+ defines += [("SPR_WALK", first), ("WALK_N", len(wa[(1, 0)])), ("SPR_STAND", stand)]
+ # on Lilygear Lake ("area" 8) the walker rides "lilly" (1161-1162): 4 directions
+ la = app.anims(app.obj("lilly", "overworld"))
+ first = len(SPR)
+ for d in (0, 8, 16, 24):
+ for h in la[(0, d)]:
+ sprite(app, h)
+ defines += [("SPR_LILLY", first), ("LILLY_N", len(la[(0, 0)]))]
+ hit = app.anims(app.obj("8bit hitbox", "overworld"))
+ hb = hit[min(hit)][0]
+ defines += [("HIT_W", app.size(hb)[0]), ("HIT_H", app.size(hb)[1]), ("HIT_HX", app.hotspot(hb)[0]),
+ ("HIT_HY", app.hotspot(hb)[1])]
+ for nm in ("feel top", "feel bottom", "feel left", "feel right"):
+ a = app.anims(app.obj(nm, "overworld"))
+ h = a[min(a)][0]
+ key = nm.split()[1].upper()
+ defines += [(f"FEEL_{key}_W", app.size(h)[0]), (f"FEEL_{key}_H", app.size(h)[1]),
+ (f"FEEL_{key}_HX", app.hotspot(h)[0]), (f"FEEL_{key}_HY", app.hotspot(h)[1])]
+ start = next((x, y) for o, x, y, l in f.placed if app.objects[o][1] == "8bit hitbox")
+ defines += [("START_X", start[0]), ("START_Y", start[1]), ("MAP_W", f.w), ("MAP_H", f.h), ("CELL", CELL)]
+ # the section: counts, then ground (i16 x, y, u16 w, h, sprite), pictures (i16 x, y, u16 sprite), objects
+ # (u8 kind, number, i16 x0, y0, x1, y1, u16 sprite, sprite 2), walls (bits, rows of the map)
+ rows = walls.shape[0]
+ stride = (walls.shape[1] + 7) // 8
+ wb = np.packbits(walls, axis=1, bitorder="little")
+ out = struct.pack("<HHHHHH", len(ground), len(inst), len(objs), rows, stride, 0)
+ for g in ground:
+ out += struct.pack("<hhHHH", *g) + b"\0\0"
+ for t in inst:
+ out += struct.pack("<hhH", t[3], t[4], t[5])
+ for o in objs:
+ out += struct.pack("<BBhhhhHH", *o)
+ out += wb.tobytes()
+ print(f"world: ground {len(ground)}, pictures {len(inst)}, objects {len(objs)}, sprites {len(SPR)} "
+ f"({sum(len(b) for b in SPR)} bytes), walls {wb.nbytes}")
+ return out, defines