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.

Five Nights at Freddy's 4

Mason363794f3da78d2f
diff --git a/Makefile b/Makefile
index 58c629e0..f59a887b 100644
--- a/Makefile
+++ b/Makefile
@@ -18,7 +18,7 @@ PY ?= python3
CARGO ?= cargo
B = build/data
# Conventional games honor a configurable output directory; special layouts are kept local.
-GAMES_REDIRECT = angrybirds badtime balatro blockblast breakout buckshot celeste championisland chess connectfour cookieclicker coreball dinorun donkeykong doodlejump doom dune famidash finalearth2 flappybird flappydunk fnaf fnaf2 fnaf3 fnf g2048 hillclimb hollowknight invaders isaac jetpackjoyride leveldevil mahjong meowdoku minesweeper monkeymart numblocks numpowder numvisuals pacman paperclips polytrack portal pvz rider snake snowrider sokoban solitaire sonic stickmanhook subway sudoku suika templerun tombofthemask towerblock turborush twoplayer undertale uno uttt
+GAMES_REDIRECT = angrybirds badtime balatro blockblast breakout buckshot celeste championisland chess connectfour cookieclicker coreball dinorun donkeykong doodlejump doom dune famidash finalearth2 flappybird flappydunk fnaf fnaf2 fnaf3 fnaf4 fnf g2048 hillclimb hollowknight invaders isaac jetpackjoyride leveldevil mahjong meowdoku minesweeper monkeymart numblocks numpowder numvisuals pacman paperclips polytrack portal pvz rider snake snowrider sokoban solitaire sonic stickmanhook subway sudoku suika templerun tombofthemask towerblock turborush twoplayer undertale uno uttt
GAMES_OUT = dinorun
GAME_REDIRECT_ARG = $(if $(filter $(1),$(GAMES_OUT)),OUT=../../$(B)/games/$(1),BUILD_DIR=../../$(B)/games/$(1))
# the RAM the oldest calculator software that runs apps gives them (23.2: 148928 bytes; 25.2 gives 153676).
@@ -29,7 +29,7 @@ RAM_LIMIT = 148928
# custom builds of Epsilon 25.2's source give apps less: 133652 bytes; every game fits there too, in NumPlay and on
# its own (their big buffers are on the stack, 32 KB apart from that RAM, or in the RAM the software has left)
CUSTOM_RAM = 133652
-BIG_APPS = Celeste HollowKnight Undertale ChampionIsland FinalEarth2 NumPowder NumBlocks NumDrive SubwaySurfers FiveNightsAtFreddys Doom BindingOfIsaac HillClimbRacing PlantsVsZombies SonicTheHedgehog CookieClicker LevelDevil JetpackJoyride StickmanHook DonkeyKong Dune MonkeyMart TombOfTheMask UNO FridayNightFunkin TurboRush AngryBirds PolyTrack UniversalPaperclips BadTimeSimulator Mahjong Rider SnowRider3D TempleRun FiveNightsAtFreddys2 FiveNightsAtFreddys3 Famidash UniversalPaperclips-French
+BIG_APPS = Celeste HollowKnight Undertale ChampionIsland FinalEarth2 NumPowder NumBlocks NumDrive SubwaySurfers FiveNightsAtFreddys Doom BindingOfIsaac HillClimbRacing PlantsVsZombies SonicTheHedgehog CookieClicker LevelDevil JetpackJoyride StickmanHook DonkeyKong Dune MonkeyMart TombOfTheMask UNO FridayNightFunkin TurboRush AngryBirds PolyTrack UniversalPaperclips BadTimeSimulator Mahjong Rider SnowRider3D TempleRun FiveNightsAtFreddys2 FiveNightsAtFreddys3 FiveNightsAtFreddys4 Famidash UniversalPaperclips-French
# the calculator's space for installed apps: from the end of its software (64 KiB aligned) to 64 KiB before the
# end of its 4 MiB slot of flash, 0x903F0000. The software's size sets the start: 0x90200000 is the latest a
# NumPlay counts on (1.94 MB, APP_SPACE); Epsilon 26.4 on an N0120 ends at 0x90180000 (2.44 MB, the
@@ -335,6 +335,7 @@ APP_snowrider = $(B)/games/snowrider/snowrider.nwa:SnowRider3D.nwa
APP_templerun = $(B)/games/templerun/templerun.nwa:TempleRun.nwa
APP_fnaf2 = $(B)/games/fnaf2/fnaf2.nwa:FiveNightsAtFreddys2.nwa
APP_fnaf3 = $(B)/games/fnaf3/fnaf3.nwa:FiveNightsAtFreddys3.nwa
+APP_fnaf4 = $(B)/games/fnaf4/fnaf4.nwa:FiveNightsAtFreddys4.nwa
APP_famidash = $(B)/games/famidash/famidash.nwa:Famidash.nwa
# the big games' modules are made from these (the kit)
$(foreach g,$(XL_GAMES),$(eval MOD_$(g) = $$(word 1,$$(subst :, ,$$(APP_$(g))))))
@@ -382,6 +383,7 @@ apps: | $(B)
$(MAKE) -C games/templerun build NWLINK="$(NWLINK)" BUILD_DIR=../../$(B)/games/templerun
$(MAKE) -C games/fnaf2 build NWLINK="$(NWLINK)" BUILD_DIR=../../$(B)/games/fnaf2
$(MAKE) -C games/fnaf3 build NWLINK="$(NWLINK)" BUILD_DIR=../../$(B)/games/fnaf3
+ $(MAKE) -C games/fnaf4 build NWLINK="$(NWLINK)" BUILD_DIR=../../$(B)/games/fnaf4
$(MAKE) -C games/famidash build NWLINK="$(NWLINK)" BUILD_DIR=../../$(B)/games/famidash
cd games/tetris/tetris && NWLINK="$(NWLINK)" $(CARGO) build --release --quiet
cp $(word 1,$(subst :, ,$(APP_numdash))) $(B)/apps/$(word 2,$(subst :, ,$(APP_numdash)))
@@ -428,6 +430,7 @@ apps: | $(B)
cp $(word 1,$(subst :, ,$(APP_templerun))) $(B)/apps/$(word 2,$(subst :, ,$(APP_templerun)))
cp $(word 1,$(subst :, ,$(APP_fnaf2))) $(B)/apps/$(word 2,$(subst :, ,$(APP_fnaf2)))
cp $(word 1,$(subst :, ,$(APP_fnaf3))) $(B)/apps/$(word 2,$(subst :, ,$(APP_fnaf3)))
+ cp $(word 1,$(subst :, ,$(APP_fnaf4))) $(B)/apps/$(word 2,$(subst :, ,$(APP_fnaf4)))
cp $(word 1,$(subst :, ,$(APP_famidash))) $(B)/apps/$(word 2,$(subst :, ,$(APP_famidash)))
arm-none-eabi-strip --strip-unneeded $(B)/apps/Tetris.nwa
@@ -514,6 +517,7 @@ clean:
-$(MAKE) -C games/templerun clean
-$(MAKE) -C games/fnaf2 clean
-$(MAKE) -C games/fnaf3 clean
+ -$(MAKE) -C games/fnaf4 clean
-$(MAKE) -C games/famidash clean
-cd games/tetris/tetris && $(CARGO) clean
-$(foreach g,$(STD_GAMES),$(MAKE) -C games/$(g) clean;)
diff --git a/README.md b/README.md
index 9a916e67..ef5da69c 100644
--- a/README.md
+++ b/README.md
@@ -6,7 +6,7 @@
<p align="center">
<b>29 free games for your NumWorks calculator, in one app.</b><br>
- Plus 35 big games that install on their own. For the N0110, N0115 and N0120, in English, French and Chinese.
+ Plus 36 big games that install on their own. For the N0110, N0115 and N0120, in English, French and Chinese.
</p>
<p align="center">
@@ -154,9 +154,10 @@ These are too big to fit next to NumPlay, so each one is its own app. Install it
<tr>
<td align="center"><a href="games/famidash/README.md"><img src="docs/media/thumb_famidash.png" width="200" alt="Famidash"><br><b>Famidash</b></a><br><sub>Geometry Dash for the NES: 173 levels, every mode, practice mode</sub><br><a href="https://github.com/Mason363/NumPlay/releases/latest/download/Famidash.nwa">Download</a></td>
<td align="center"><a href="games/fnaf3/README.md"><img src="docs/media/thumb_fnaf3.png" width="200" alt="Five Nights at Freddy's 3"><br><b>Five Nights at Freddy's 3</b></a><br><sub>Fazbear's Fright: Springtrap, the phantoms, the lure and the vents</sub><br><a href="https://github.com/Mason363/NumPlay/releases/latest/download/FiveNightsAtFreddys3.nwa">Download</a></td>
- <td align="center"><a href="https://github.com/Mason363/NumWorks-Super-Mario-64"><b>Super Mario 64</b></a><br><sub>In a repository of its own: NumWorks-Super-Mario-64</sub></td>
+ <td align="center"><a href="games/fnaf4/README.md"><img src="docs/media/thumb_fnaf4.png" width="200" alt="Five Nights at Freddy's 4"><br><b>Five Nights at Freddy's 4</b></a><br><sub>The bedroom: listen at the doors, the closet, the bed, Fun with Plushtrap</sub><br><a href="https://github.com/Mason363/NumPlay/releases/latest/download/FiveNightsAtFreddys4.nwa">Download</a></td>
</tr>
<tr>
+ <td align="center"><a href="https://github.com/Mason363/NumWorks-Super-Mario-64"><b>Super Mario 64</b></a><br><sub>In a repository of its own: NumWorks-Super-Mario-64</sub></td>
<td align="center"><a href="https://github.com/Mason363/NumWorks-Super-Mario-Bros"><b>Super Mario Bros.</b></a><br><sub>All 32 stages, in a repository of its own: NumWorks-Super-Mario-Bros</sub></td>
<td align="center"><a href="#roadmap"><b>More on the way</b></a><br><sub>Minecraft 1.18.2 and more: see the roadmap</sub></td>
</tr>
@@ -321,6 +322,7 @@ Read **[Make your own NumWorks game](docs/make-a-game.md)** to go from there, an
- [x] Famidash: its newest and fullest version, HUGE, with 173 levels
- [x] ColecoVision games in Retro-Go
- [x] Five Nights at Freddy's 3
+- [x] Five Nights at Freddy's 4
- [ ] Full Minecraft 1.18.2 as a standalone app
- [ ] Among Us, against bots
- [ ] Cat Ninja
@@ -342,7 +344,7 @@ Read **[Make your own NumWorks game](docs/make-a-game.md)** to go from there, an
- [ ] Castle Crashers
- [ ] Hotline Miami
- [ ] More of Retro-Go: Game & Watch, SNES and Mega Drive
-- [ ] Five Nights at Freddy's 4 and FNAF World
+- [ ] FNAF World
- [ ] Brawl Stars, against bots
- [ ] Papers, Please, with the story and Endless
- [ ] Mario Kart
@@ -407,6 +409,7 @@ NumPlay is a fan project, made out of love for these games and for the NumWorks
- **[Level Devil](https://store.steampowered.com/app/3242750/)** by Unept: NumPlay's Level Devil is written in C with no code from the game, but its 80 rooms (their tiles, traps and timing) are the game's own, taken from its web build by games/leveldevil/tools/fetch.py, and its runner is drawn from the game's sprites.
- **Five Nights at Freddy's 2** by Scott Cawthon inspired NumPlay's Five Nights at Freddy's 2, which uses the game's own pictures, from its Clickteam HTML5 build as the fan port [fnaf-2_html5](https://github.com/VocalNutria9174/fnaf-2_html5) (VocalNutria9174) keeps it, two of them from fredtheking's [FNaF2-RaylibCs](https://github.com/fredtheking/FNaF2-RaylibCs), and the DejaVu fonts ([license](LICENSES/DejaVu.txt)). Its AI levels, paths, music box, flashlight and Withered Foxy follow what the game's players read out of its events, written down on the [Technical FNaF Wiki](https://technicalfnaf.fandom.com) and the [Five Nights at Freddy's Wiki](https://freddy-fazbears-pizza.fandom.com). Not affiliated with Scott Cawthon.
- **Five Nights at Freddy's 3** by Scott Cawthon inspired NumPlay's Five Nights at Freddy's 3, which uses the game's own pictures and runs its nights as the game's own events do, both read from its Android package. Not affiliated with Scott Cawthon.
+- **Five Nights at Freddy's 4** by Scott Cawthon inspired NumPlay's Five Nights at Freddy's 4, which uses the game's own pictures and runs its nights as the game's own events do, both read from its iOS package. Not affiliated with Scott Cawthon.
- **Pong** by Atari (1972) inspired NumPlay's 2 Players, with air hockey, tanks in a maze in the spirit of Tank Trouble and the light cycles of Tron. All four are written in C for NumPlay and drawn from shapes, with no code or art from them.
- **[Cookie Clicker](https://orteil.dashnet.org/cookieclicker/)** by Orteil and Opti (DashNet) inspired NumPlay's Cookie Clicker, which uses the game's own pictures, texts and numbers (version 2.058, from its public mirror [ozh/cookieclicker](https://github.com/ozh/cookieclicker)) and the **Merriweather**, **Kavoon** and **Noto Sans** fonts (SIL Open Font License: [Merriweather](LICENSES/OFL-1.1-Merriweather.txt), [Kavoon](LICENSES/OFL-1.1-Kavoon.txt), [Noto Sans](LICENSES/OFL-1.1-NotoSans.txt)). Not affiliated with Orteil or DashNet.
@@ -435,7 +438,7 @@ NumPlay is a fan project, made out of love for these games and for the NumWorks
NumPlay is licensed under the [GNU General Public License v3.0](LICENSE). Copyright (c) 2026 Mason Chen. Code and fonts from others keep their own licenses: the `UNLICENSE` files in the games' folders and the [LICENSES](LICENSES) folder. The names, artwork and music of the games NumPlay is inspired by belong to their makers and are not covered by it.
-<sub>Unofficial fan games, not affiliated with NumWorks, RobTop Games (Geometry Dash), Hipster Whale (Crossy Road), the makers of Drive Mad, LocalThunk or Playstack (Balatro), Mike Klubnika or Critical Reflex (Buckshot Roulette), Hungry Studio (Block Blast!), Aladdin X (Suika Game), Voodoo (Flappy Dunk), Lima Sky (Doodle Jump), Mojang or Microsoft (Minecraft), Maddy Makes Games (Celeste), Team Cherry (Hollow Knight), Toby Fox (Undertale), jcw87 (Bad Time Simulator), Imangi Studios (Temple Run), id Software (Doom), Edmund McMillen, Florian Himsl or Nicalis (The Binding of Isaac), PopCap Games or Electronic Arts (Plants vs. Zombies), Scott Cawthon (Five Nights at Freddy's, Five Nights at Freddy's 2, Five Nights at Freddy's 3), SEGA (Sonic the Hedgehog, Master System, Game Gear, SG-1000), SYBO or Kiloo (Subway Surfers), Fingersoft (Hill Climb Racing), Unept (Level Devil), Halfbrick (Jetpack Joyride), Madbox (Stickman Hook), Nintendo (Donkey Kong, Game Boy, NES), Team Lava (Dune!), Inlogic Software (Dune Rider), TinyDobbins (Monkey Mart), Playgendary (Tomb of the Mask), Mattel (UNO), the Funkin' Crew (Friday Night Funkin'), W Production (Turbo Rush), Rovio Entertainment (Angry Birds), Kodub (PolyTrack), Frank Lantz or Everybody House Games (Universal Paperclips), the makers of Snow Rider 3D, Ketchapp (Rider), TFDSoft (Famidash), Brodie Lockard or Activision (Shanghai), Atari (Pong), Disney (Tron), Orteil or DashNet (Cookie Clicker), Taito or Midway (Space Invaders), Thinking Rabbit or Falcon (Sokoban), Oakever Games (Meowdoku), Florian van Strien (The Final Earth 2), The Powder Toy's developers (The Powder Toy), MateoConLechuga (Portal Returns), Valve (Portal), .GEARS (Flappy Bird), Bandai Namco (Pac-Man), Hasbro (Connect Four), Google (Snake, Solitaire, Block Breaker, Chrome Dino, Doodle Champion Island Games), STUDIO4°C or Microsoft (Minesweeper), ducalex (Retro-Go), Coleco (ColecoVision). Tetris is a trademark of The Tetris Company, Chrome of Google LLC, Minecraft of Mojang Synergies AB, Pac-Man of Bandai Namco, Connect Four of Hasbro, DOOM of ZeniMax Media, Sonic the Hedgehog, Master System, Game Gear and SG-1000 of SEGA, Space Invaders of Taito, UNO of Mattel, Angry Birds of Rovio Entertainment, and Donkey Kong, Game Boy, Game Boy Color and NES of Nintendo.</sub>
+<sub>Unofficial fan games, not affiliated with NumWorks, RobTop Games (Geometry Dash), Hipster Whale (Crossy Road), the makers of Drive Mad, LocalThunk or Playstack (Balatro), Mike Klubnika or Critical Reflex (Buckshot Roulette), Hungry Studio (Block Blast!), Aladdin X (Suika Game), Voodoo (Flappy Dunk), Lima Sky (Doodle Jump), Mojang or Microsoft (Minecraft), Maddy Makes Games (Celeste), Team Cherry (Hollow Knight), Toby Fox (Undertale), jcw87 (Bad Time Simulator), Imangi Studios (Temple Run), id Software (Doom), Edmund McMillen, Florian Himsl or Nicalis (The Binding of Isaac), PopCap Games or Electronic Arts (Plants vs. Zombies), Scott Cawthon (Five Nights at Freddy's, Five Nights at Freddy's 2, Five Nights at Freddy's 3, Five Nights at Freddy's 4), SEGA (Sonic the Hedgehog, Master System, Game Gear, SG-1000), SYBO or Kiloo (Subway Surfers), Fingersoft (Hill Climb Racing), Unept (Level Devil), Halfbrick (Jetpack Joyride), Madbox (Stickman Hook), Nintendo (Donkey Kong, Game Boy, NES), Team Lava (Dune!), Inlogic Software (Dune Rider), TinyDobbins (Monkey Mart), Playgendary (Tomb of the Mask), Mattel (UNO), the Funkin' Crew (Friday Night Funkin'), W Production (Turbo Rush), Rovio Entertainment (Angry Birds), Kodub (PolyTrack), Frank Lantz or Everybody House Games (Universal Paperclips), the makers of Snow Rider 3D, Ketchapp (Rider), TFDSoft (Famidash), Brodie Lockard or Activision (Shanghai), Atari (Pong), Disney (Tron), Orteil or DashNet (Cookie Clicker), Taito or Midway (Space Invaders), Thinking Rabbit or Falcon (Sokoban), Oakever Games (Meowdoku), Florian van Strien (The Final Earth 2), The Powder Toy's developers (The Powder Toy), MateoConLechuga (Portal Returns), Valve (Portal), .GEARS (Flappy Bird), Bandai Namco (Pac-Man), Hasbro (Connect Four), Google (Snake, Solitaire, Block Breaker, Chrome Dino, Doodle Champion Island Games), STUDIO4°C or Microsoft (Minesweeper), ducalex (Retro-Go), Coleco (ColecoVision). Tetris is a trademark of The Tetris Company, Chrome of Google LLC, Minecraft of Mojang Synergies AB, Pac-Man of Bandai Namco, Connect Four of Hasbro, DOOM of ZeniMax Media, Sonic the Hedgehog, Master System, Game Gear and SG-1000 of SEGA, Space Invaders of Taito, UNO of Mattel, Angry Birds of Rovio Entertainment, and Donkey Kong, Game Boy, Game Boy Color and NES of Nintendo.</sub>
## Gallery
diff --git a/docs/media/thumb_fnaf4.png b/docs/media/thumb_fnaf4.png
new file mode 100644
index 00000000..0ba44d9a
Binary files /dev/null and b/docs/media/thumb_fnaf4.png differ
diff --git a/docs/play.md b/docs/play.md
index b62ec46b..838595f4 100644
--- a/docs/play.md
+++ b/docs/play.md
@@ -771,6 +771,23 @@ Five Nights at Freddy's 2 comes as its own app, `FiveNightsAtFreddys2.nwa`. Last
Last from 12 to 6 AM at Fazbear's Fright. Springtrap comes room by room: play the audio on a camera next to his and he follows it, and seal the vent he crawls into. Reboot the audio, the cameras and the ventilation on the maintenance panel when they fail; with the ventilation down the dark comes in waves and he comes closer. Look away from a phantom on a camera before it jumps out. Night 5 opens the 6th.
+<br clear="right">
+
+## Five Nights at Freddy's 4
+
+<img src="../games/fnaf4/docs/shot.png" width="320" align="right" alt="Five Nights at Freddy's 4: the bedroom, the closet ahead">
+
+| Key | What it does |
+| --- | --- |
+| **Left / Right** (or 4 / 6) | Look left and right, at a door |
+| **OK** | Run to the door you face, or the closet |
+| **Down** | Turn to the bed, run back, turn around |
+| **OK** held | The flashlight |
+| **Up** held | Hold the door or the closet shut |
+| **Back** | Pause (Resume, Quit game) |
+
+Last from 12 to 6 AM in the bedroom. At a door, listen with the light off: breathing means someone stands right there, so hold the door shut until the steps go; no breathing, light the hall. Shut the closet on Foxy, light the Freddles off the bed. Fredbear comes up a hall on the 5th night: hold that door shut. After each of the first five nights, stop Plushtrap on the X to start the next at 2 AM. Night 5 opens the 6th and the Extras.
+
<br clear="right">
## Famidash
diff --git a/games/fnaf4/.gitignore b/games/fnaf4/.gitignore
new file mode 100644
index 00000000..edd4c316
--- /dev/null
+++ b/games/fnaf4/.gitignore
@@ -0,0 +1,4 @@
+output/
+build/
+ref/
+__pycache__/
diff --git a/games/fnaf4/Makefile b/games/fnaf4/Makefile
new file mode 100644
index 00000000..89665b7f
--- /dev/null
+++ b/games/fnaf4/Makefile
@@ -0,0 +1,81 @@
+# Five Nights at Freddy's 4 on the NumWorks calculator.
+# make output/fnaf4.nwa
+# make check link it like the calculator does (output/fnaf4.bin)
+# make host build/rules and build/pictures: 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 Application.cci (CCI=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
+CCI ?=
+
+# 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)/fnaf4.nwa
+
+# apps get 133652 bytes of RAM on custom builds of Epsilon 25.2 (148928 or more on official ones)
+check: $(BUILD_DIR)/fnaf4.nwa
+ $(Q) $(NWLINK) nwa-bin --ram-length 133652 $< $(BUILD_DIR)/fnaf4.bin
+ @echo "BIN $(BUILD_DIR)/fnaf4.bin: $$(wc -c < $(BUILD_DIR)/fnaf4.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)/fnaf4.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 nights and random keys; tests/pics.c draws every picture
+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/pictures build/rules
+build/pictures: src/pic.c src/gfx.c src/plat_host.c tests/pics.c src/data.S src/data.bin $(HEADERS)
+ $(Q) mkdir -p $(dir $@)
+ $(Q) cc $(HOST_FLAGS) $(HOST_SAN) src/pic.c src/gfx.c src/plat_host.c tests/pics.c src/data.S -lm -o $@
+
+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 $(CCI)
+
+clean:
+ $(Q) rm -rf $(BUILD_DIR) build
diff --git a/games/fnaf4/README.md b/games/fnaf4/README.md
new file mode 100644
index 00000000..197f619b
--- /dev/null
+++ b/games/fnaf4/README.md
@@ -0,0 +1,72 @@
+<p align="center">
+ <img src="src/icon.png" width="84" alt="Five Nights at Freddy's 4 icon">
+</p>
+
+<h1 align="center">Five Nights at Freddy's 4</h1>
+
+<p align="center">
+ <b>Survive the nights in the bedroom, on the NumWorks calculator.</b><br>
+ Nights 1 to 6, the Nightmare and 20/20/20/20, Fun with Plushtrap and the box.
+</p>
+
+<p align="center">
+ <a href="https://github.com/Mason363/NumPlay/releases/latest/download/FiveNightsAtFreddys4.nwa"><b>Download FiveNightsAtFreddys4.nwa</b></a>
+ &nbsp;·&nbsp; <a href="#controls">Controls</a>
+</p>
+
+## Highlights
+
+* **The game's own nights:** Nightmare Bonnie, Chica, Foxy, the Freddles, Fredbear and Nightmare move as the game's own events move them, read out of its iOS package, with each night's AI.
+* **Two doors, the closet, the bed.** Listen at a door before the light, hold it shut on breathing, shut the closet on Foxy, light the Freddles off the bed.
+* **Fun with Plushtrap** after each of the first five nights: stop him on the X and the next night starts at 2 AM.
+* **Extras** once the 5th night is beaten: the animatronics, the making of Foxy and Fredbear, the jumpscares, Plushtrap, the Nightmare and 20/20/20/20. Then the ending and the box.
+
+<table>
+ <tr>
+ <td align="center"><img src="docs/shot.png" width="390" alt="The bedroom, the closet ahead"><br><sub>The bedroom</sub></td>
+ <td align="center"><img src="docs/door.png" width="390" alt="Fredbear down the left hall in the flashlight"><br><sub>A door</sub></td>
+ </tr>
+ <tr>
+ <td align="center"><img src="docs/closet.png" width="390" alt="Foxy in the closet"><br><sub>The closet</sub></td>
+ <td align="center"><img src="docs/bed.png" width="390" alt="Three Freddles on the bed"><br><sub>The bed</sub></td>
+ </tr>
+</table>
+
+## How to play
+
+Last from 12 to 6 AM, a minute an hour.
+
+At a door, listen first with the light off. Breathing means someone stands right there: hold the door shut until the steps go. No breathing, light the hall to send away whoever is down it. Foxy runs into the closet when your back is turned: light it, and hold its door shut while he is out. Turn to the bed and light it often, or the Freddles pile up. Fredbear comes up a hall: hold that door shut, or chase him off the bed with the light and out of the closet with its door.
+
+## Controls
+
+| Key | What it does |
+| --- | --- |
+| ← → | Look left and right, at a door |
+| OK | Run to the door you face, or the closet |
+| ↓ | Turn to the bed, run back, turn around |
+| OK held | The flashlight |
+| ↑ held | Hold the door or the closet shut |
+| Back | Pause |
+| Home | Keep the night and quit |
+
+## Good to know
+
+* **Too big to install next to NumPlay.** Your saves in each are kept.
+* **No sound:** the calculator has no speaker. What you would hear is written at the bottom left: breathing at a door, steps on either side, Foxy running, the kitchen, laughing.
+* **The pictures are the game's,** at half size: the screen shows 640 of its 800 pixels.
+
+## Credits
+
+Inspired by Five Nights at Freddy's 4 by Scott Cawthon, not affiliated with him.
+
+* The pictures and the rules come from the game's iOS package (its Clickteam application): `tools/ccn.py` reads its pictures and objects, and `tools/pack.py` makes them into `src/data.bin`. The nights follow the game's own events, read out of the same file.
+* The words are drawn in the DejaVu fonts ([license](../../LICENSES/DejaVu.txt)).
+
+Made by Mason Chen as part of NumPlay.
+
+## License
+
+The game's code is licensed under the GNU General Public License v3.0: see the `LICENSE` file at the root of the repository. The game's pictures keep their own terms (see Credits).
+
+Build: `make` (needs `arm-none-eabi-gcc` and Node.js for nwlink), `make test` on a computer.
diff --git a/games/fnaf4/docs/bed.png b/games/fnaf4/docs/bed.png
new file mode 100644
index 00000000..090deb30
Binary files /dev/null and b/games/fnaf4/docs/bed.png differ
diff --git a/games/fnaf4/docs/closet.png b/games/fnaf4/docs/closet.png
new file mode 100644
index 00000000..44fe6c0d
Binary files /dev/null and b/games/fnaf4/docs/closet.png differ
diff --git a/games/fnaf4/docs/door.png b/games/fnaf4/docs/door.png
new file mode 100644
index 00000000..ef886083
Binary files /dev/null and b/games/fnaf4/docs/door.png differ
diff --git a/games/fnaf4/docs/plushtrap.png b/games/fnaf4/docs/plushtrap.png
new file mode 100644
index 00000000..0293027b
Binary files /dev/null and b/games/fnaf4/docs/plushtrap.png differ
diff --git a/games/fnaf4/docs/shot.png b/games/fnaf4/docs/shot.png
new file mode 100644
index 00000000..fb5f485f
Binary files /dev/null and b/games/fnaf4/docs/shot.png differ
diff --git a/games/fnaf4/src/anims.h b/games/fnaf4/src/anims.h
new file mode 100644
index 00000000..86c0027f
--- /dev/null
+++ b/games/fnaf4/src/anims.h
@@ -0,0 +1,213 @@
+/* Made by tools/pack.py: the game's animations (AN_*), its own speeds and plays. Included once (night.c). */
+#ifndef FNAF4_ANIMS_H
+#define FNAF4_ANIMS_H
+#include <stdint.h>
+
+typedef struct {
+ uint16_t first; /* in ANIM_PICS */
+ uint8_t n, speed, plays, wide; /* a picture lasts 100 / speed frames; plays 0: for ever; wide: the bedroom's */
+} AnimDef;
+
+enum {
+ AN_ROOM_0,
+ AN_ROOM_12,
+ AN_ROOM_13,
+ AN_ROOM_14,
+ AN_ROOM_15,
+ AN_ROOM_16,
+ AN_ROOM_17,
+ AN_ROOM_19,
+ AN_OFF4,
+ AN_ON4,
+ AN_CREAK,
+ AN_DARKL,
+ AN_DARKR,
+ AN_DARKC,
+ AN_CARPET,
+ AN_LSTART,
+ AN_RSTART,
+ AN_BHIDE,
+ AN_CHIDE,
+ AN_BITE,
+ AN_LEAVE3,
+ AN_LEAVE2,
+ AN_LEAVE1,
+ AN_PEEKL_12,
+ AN_PEEKR_12,
+ AN_PEEKL_13,
+ AN_PEEKR_13,
+ AN_PEEKL_14,
+ AN_PEEKR_14,
+ AN_PEEKL_15,
+ AN_PEEKR_15,
+ AN_PEEKL_16,
+ AN_PEEKR_16,
+ AN_PEEKL_17,
+ AN_PEEKR_17,
+ AN_PEEKL_18,
+ AN_PEEKR_18,
+ AN_PEEKL_19,
+ AN_PEEKR_19,
+ AN_PEEKL_20,
+ AN_PEEKR_20,
+ AN_PEEKL_21,
+ AN_PEEKR_21,
+ AN_CLOSET_0,
+ AN_CLOSET_12,
+ AN_CLOSET_13,
+ AN_CLOSET_14,
+ AN_CLOSET_15,
+ AN_CLOSET_16,
+ AN_CLOSET_17,
+ AN_CLOSET_18,
+ AN_CLOSET_19,
+ AN_CLOSET_20,
+ AN_CLOSET_21,
+ AN_CLOSET_22,
+ AN_CLOSET_23,
+ AN_BED_0,
+ AN_BED_12,
+ AN_BED_14,
+ AN_BED_16,
+ AN_BED_18,
+ AN_BED_19,
+ AN_BED_20,
+ AN_BED_21,
+ AN_BED_22,
+ AN_BED_23,
+ AN_BED_24,
+ AN_BED_25,
+ AN_JUMP_0,
+ AN_JUMP_12,
+ AN_JUMP_13,
+ AN_JUMP_14,
+ AN_FREDDYATK,
+ AN_CUPCAKE,
+ AN_BONNIEATK,
+ AN_FREDBEAR,
+ AN_PLUSH_0,
+ AN_PLUSH_12,
+ AN_PLUSH_13,
+ AN_PLUSH_14,
+ AN_PLUSH_15,
+ AN_PLUSH_16,
+ AN_PLUSH_17,
+ AN_PLUSH_18,
+ AN_PLUSH_19,
+ AN_PLUSH_20,
+ AN_PLUSH_21,
+ AN_PLUSH_22,
+ AN_PLUSH_23,
+ AN_COUNT
+};
+
+static const uint16_t ANIM_PICS[] = {
+ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
+ 16, 17, 18, 19, 20, 21, 8, 22, 23, 24, 25, 26, 27, 28, 29, 30,
+ 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46,
+ 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62,
+ 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78,
+ 79, 80, 81, 80, 82, 83, 79, 84, 77, 85, 86, 87, 88, 89, 90, 91,
+ 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107,
+ 108, 107, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122,
+ 123, 124, 125, 126, 127, 118, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137,
+ 138, 139, 140, 141, 142, 141, 143, 144, 145, 144, 146, 147, 148, 149, 150, 151,
+ 148, 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, 175, 180, 181,
+ 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197,
+ 198, 199, 195, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209,
+};
+
+static const AnimDef ANIMS[AN_COUNT] = {
+ {0, 1, 50, 0, 1}, /* ROOM_0 */
+ {1, 1, 50, 1, 1}, /* ROOM_12 */
+ {2, 1, 50, 0, 1}, /* ROOM_13 */
+ {3, 1, 50, 1, 1}, /* ROOM_14 */
+ {4, 1, 50, 1, 1}, /* ROOM_15 */
+ {5, 1, 50, 0, 1}, /* ROOM_16 */
+ {6, 1, 50, 1, 1}, /* ROOM_17 */
+ {7, 2, 50, 1, 1}, /* ROOM_19 */
+ {9, 2, 20, 1, 1}, /* OFF4 */
+ {11, 2, 20, 1, 1}, /* ON4 */
+ {13, 2, 20, 1, 1}, /* CREAK */
+ {15, 3, 20, 1, 1}, /* DARKL */
+ {18, 3, 20, 1, 1}, /* DARKR */
+ {21, 2, 20, 1, 1}, /* DARKC */
+ {23, 8, 20, 1, 0}, /* CARPET */
+ {31, 7, 20, 1, 0}, /* LSTART */
+ {38, 5, 20, 1, 0}, /* RSTART */
+ {43, 4, 20, 1, 0}, /* BHIDE */
+ {47, 4, 20, 1, 0}, /* CHIDE */
+ {51, 6, 20, 1, 0}, /* BITE */
+ {57, 2, 50, 1, 0}, /* LEAVE3 */
+ {59, 2, 50, 1, 0}, /* LEAVE2 */
+ {61, 2, 50, 1, 0}, /* LEAVE1 */
+ {63, 1, 50, 0, 0}, /* PEEKL_12 */
+ {64, 1, 20, 0, 0}, /* PEEKR_12 */
+ {65, 1, 50, 0, 0}, /* PEEKL_13 */
+ {66, 5, 20, 1, 0}, /* PEEKR_13 */
+ {71, 3, 20, 1, 0}, /* PEEKL_14 */
+ {74, 1, 20, 0, 0}, /* PEEKR_14 */
+ {75, 3, 20, 1, 0}, /* PEEKL_15 */
+ {78, 3, 20, 1, 0}, /* PEEKR_15 */
+ {81, 1, 50, 0, 0}, /* PEEKL_16 */
+ {82, 1, 50, 0, 0}, /* PEEKR_16 */
+ {83, 3, 20, 1, 0}, /* PEEKL_17 */
+ {86, 3, 20, 1, 0}, /* PEEKR_17 */
+ {89, 3, 25, 1, 0}, /* PEEKL_18 */
+ {92, 3, 25, 1, 0}, /* PEEKR_18 */
+ {95, 1, 50, 0, 0}, /* PEEKL_19 */
+ {96, 1, 50, 0, 0}, /* PEEKR_19 */
+ {97, 1, 50, 0, 0}, /* PEEKL_20 */
+ {98, 1, 50, 1, 0}, /* PEEKR_20 */
+ {99, 1, 50, 0, 0}, /* PEEKL_21 */
+ {100, 1, 50, 0, 0}, /* PEEKR_21 */
+ {101, 5, 20, 1, 0}, /* CLOSET_0 */
+ {106, 1, 50, 0, 0}, /* CLOSET_12 */
+ {107, 1, 50, 0, 0}, /* CLOSET_13 */
+ {108, 3, 20, 1, 0}, /* CLOSET_14 */
+ {111, 2, 20, 1, 0}, /* CLOSET_15 */
+ {113, 1, 20, 1, 0}, /* CLOSET_16 */
+ {114, 1, 50, 0, 0}, /* CLOSET_17 */
+ {115, 1, 50, 0, 0}, /* CLOSET_18 */
+ {116, 1, 50, 0, 0}, /* CLOSET_19 */
+ {117, 1, 50, 0, 0}, /* CLOSET_20 */
+ {118, 1, 50, 1, 0}, /* CLOSET_21 */
+ {119, 1, 50, 0, 0}, /* CLOSET_22 */
+ {120, 1, 50, 0, 0}, /* CLOSET_23 */
+ {121, 3, 20, 1, 0}, /* BED_0 */
+ {124, 3, 90, 0, 0}, /* BED_12 */
+ {127, 2, 90, 0, 0}, /* BED_14 */
+ {129, 2, 90, 0, 0}, /* BED_16 */
+ {131, 1, 50, 0, 0}, /* BED_18 */
+ {132, 1, 50, 0, 0}, /* BED_19 */
+ {133, 2, 20, 1, 0}, /* BED_20 */
+ {135, 1, 50, 0, 0}, /* BED_21 */
+ {136, 1, 50, 0, 0}, /* BED_22 */
+ {137, 1, 50, 0, 0}, /* BED_23 */
+ {138, 1, 50, 0, 0}, /* BED_24 */
+ {139, 1, 50, 0, 0}, /* BED_25 */
+ {140, 6, 25, 3, 0}, /* JUMP_0 */
+ {146, 4, 25, 3, 0}, /* JUMP_12 */
+ {150, 4, 25, 3, 0}, /* JUMP_13 */
+ {154, 7, 25, 2, 0}, /* JUMP_14 */
+ {161, 5, 25, 3, 0}, /* FREDDYATK */
+ {166, 6, 25, 4, 0}, /* CUPCAKE */
+ {172, 5, 25, 5, 0}, /* BONNIEATK */
+ {177, 6, 25, 3, 0}, /* FREDBEAR */
+ {183, 1, 50, 1, 0}, /* PLUSH_0 */
+ {184, 1, 50, 0, 0}, /* PLUSH_12 */
+ {185, 1, 50, 0, 0}, /* PLUSH_13 */
+ {186, 4, 50, 1, 0}, /* PLUSH_14 */
+ {190, 3, 50, 1, 0}, /* PLUSH_15 */
+ {193, 3, 50, 1, 0}, /* PLUSH_16 */
+ {196, 3, 50, 1, 0}, /* PLUSH_17 */
+ {199, 3, 50, 1, 0}, /* PLUSH_18 */
+ {202, 4, 50, 1, 0}, /* PLUSH_19 */
+ {206, 4, 50, 1, 0}, /* PLUSH_20 */
+ {210, 1, 50, 0, 0}, /* PLUSH_21 */
+ {211, 1, 50, 0, 0}, /* PLUSH_22 */
+ {212, 10, 25, 1, 0}, /* PLUSH_23 */
+};
+
+#endif
diff --git a/games/fnaf4/src/data.S b/games/fnaf4/src/data.S
new file mode 100644
index 00000000..95294077
--- /dev/null
+++ b/games/fnaf4/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 _fnaf4_data
+_fnaf4_data:
+ .incbin DATA_BIN
+ .p2align 2
+#else
+ .section .rodata.fnaf4_data,"a"
+ .balign 4
+ .global fnaf4_data
+fnaf4_data:
+ .incbin DATA_BIN
+ .balign 4
+#endif
+#ifdef __ELF__
+ .section .note.GNU-stack,"",%progbits
+#endif
diff --git a/games/fnaf4/src/data.bin b/games/fnaf4/src/data.bin
new file mode 100644
index 00000000..d5f52b78
Binary files /dev/null and b/games/fnaf4/src/data.bin differ
diff --git a/games/fnaf4/src/data.h b/games/fnaf4/src/data.h
new file mode 100644
index 00000000..a59e6bb5
--- /dev/null
+++ b/games/fnaf4/src/data.h
@@ -0,0 +1,116 @@
+/* Made by tools/pack.py: what is in data.bin. */
+#ifndef FNAF4_DATA_H
+#define FNAF4_DATA_H
+
+#define SEC_HUFF 0
+#define SEC_QUANT 1
+#define SEC_PICS 2
+#define SEC_TABLE 3
+#define SEC_BANK 4
+#define SEC_FONTS 5
+#define SEC_IMGS 6
+#define PIC_NIGHTMARE 210
+#define PIC_TITLE 211
+#define PIC_TITLE_FAINT 212
+#define PIC_TITLE_GLITCH1 213
+#define PIC_TITLE_GLITCH2 214
+#define PIC_TITLE_GLITCH3 215
+#define PIC_WHATNIGHT 216
+#define PIC_GAMEOVER 217
+#define PIC_TOOBAD 218
+#define PIC_PLUSHCARD 219
+#define PIC_LOCKBOX 220
+#define PIC_LOCKBOX1 221
+#define PIC_LOCKBOX2 222
+#define PIC_LOCKBOX3 223
+#define PIC_LOCKBOX4 224
+#define PIC_LOCKBOX5 225
+#define PIC_LOCKBOX6 226
+#define PIC_LOCKBOX7 227
+#define PIC_LOCKBOX8 228
+#define PIC_LOCKBOX9 229
+#define PIC_LOCKBOX10 230
+#define PIC_LOCKBOX11 231
+#define PIC_LOCKBOX12 232
+#define PIC_LOCKBOX13 233
+#define PIC_LOCKBOX14 234
+#define PIC_LOCKBOX15 235
+#define PIC_LOCKBOX_OPEN 236
+#define PIC_ENDING0 237
+#define PIC_ENDING1 238
+#define PIC_ENDING2 239
+#define PIC_ENDING3 240
+#define PIC_ENDING4 241
+#define PIC_ENDING5 242
+#define PIC_ENDING6 243
+#define PIC_ENDING7 244
+#define PIC_ANIMATRONIC0 245
+#define PIC_ANIMATRONIC1 246
+#define PIC_ANIMATRONIC2 247
+#define PIC_ANIMATRONIC3 248
+#define PIC_ANIMATRONIC4 249
+#define PIC_ANIMATRONIC5 250
+#define PIC_ANIMATRONIC6 251
+#define PIC_ANIMATRONIC7 252
+#define PIC_MAKINGFOXY0 253
+#define PIC_MAKINGFOXY1 254
+#define PIC_MAKINGFOXY2 255
+#define PIC_MAKINGFOXY3 256
+#define PIC_MAKINGFOXY4 257
+#define PIC_MAKINGFOXY5 258
+#define PIC_MAKINGFOXY6 259
+#define PIC_MAKINGFREDBEAR0 260
+#define PIC_MAKINGFREDBEAR1 261
+#define PIC_MAKINGFREDBEAR2 262
+#define PIC_MAKINGFREDBEAR3 263
+#define PIC_MAKINGFREDBEAR4 264
+#define PIC_MAKINGFREDBEAR5 265
+#define PIC_MAKINGFREDBEAR6 266
+#define PIC_PLUSHTRAP 267
+#define PIC_COUNT 268
+#define FONT_HUD 0
+#define FONT_BIG 1
+#define FONT_TEXT 2
+#define FONT_CLOCK 3
+#define FONT_HUGE 4
+#define FONT_SERIF 5
+#define IMG_WARNING 0
+#define TITLE_X0 80
+#define IMG_M_NEW 1
+#define IMG_M_CONTINUE 2
+#define IMG_M_SIXTH 3
+#define IMG_M_EXTRA 4
+#define IMG_M_ANIMATRONICS 5
+#define IMG_M_MAKINGFOXY 6
+#define IMG_M_MAKINGFREDBEAR 7
+#define IMG_M_JUMPSCARES 8
+#define IMG_M_PLUSHTRAP 9
+#define IMG_M_NIGHTMARE 10
+#define IMG_M_TWENTY 11
+#define IMG_M_EXIT 12
+#define MENU_RED 8912896
+#define IMG_REDLINE 13
+#define IMG_STAR 14
+#define IMG_NIGHTWORD 15
+#define IMG_CLOCK 16
+#define IMG_AM 17
+#define IMG_GREAT 18
+#define IMG_DIGIT0 19
+#define IMG_DIGIT1 20
+#define IMG_DIGIT2 21
+#define IMG_DIGIT3 22
+#define IMG_DIGIT4 23
+#define IMG_DIGIT5 24
+#define IMG_DIGIT6 25
+#define IMG_DIGIT7 26
+#define IMG_DIGIT8 27
+#define IMG_DIGIT9 28
+#define IMG_COLON 29
+#define CLOCK_RED 16252928
+#define RATTLE_N 16
+#define IMG_FORGOTTEN 30
+#define IMG_ARROW 31
+#define BED_X0 32
+#define BED_W 432
+
+#endif
diff --git a/games/fnaf4/src/game.c b/games/fnaf4/src/game.c
new file mode 100644
index 00000000..92812c2e
--- /dev/null
+++ b/games/fnaf4/src/game.c
@@ -0,0 +1,428 @@
+/* Five Nights at Freddy's 4: the scenes around the nights, the keys and the saves.
+ *
+ * As the game: its warning, the title (New Game, Continue, the 6th night and Extras once the 5th is beaten, a star
+ * for each of nights 5 to 8), the night's card, the night, 6 AM on the alarm clock, Fun with Plushtrap after the
+ * first five nights, game over, the ending after the 6th night, the box after the Nightmare. */
+#include <stdio.h>
+#include <string.h>
+#include "game.h"
+#include "gfx.h"
+#include "data.h"
+#include "plat.h"
+
+Game g;
+
+static uint32_t seed = 0x4F4A2B1u;
+uint32_t rnd(void) {
+ seed = seed * 1664525u + 1013904223u;
+ return seed >> 8;
+}
+uint32_t rnd_n(uint32_t n) { return n ? rnd() % n : 0; }
+
+static bool pressed(uint32_t k) { return (g.pressed & k) != 0; }
+#define OKS (K_OK | K_EXE)
+#define UPS (K_UP | K_DIGIT(8))
+#define DOWNS (K_DOWN | K_DIGIT(2))
+#define GREY_TEXT RGB(0x9A9A9A)
+#define MENU RGB(MENU_RED)
+static void game_band(void);
+
+void caption(const char *s) {
+ for (int i = 0; i < 3; i++) g.cap[i] = g.cap[i + 1], g.cap_t[i] = g.cap_t[i + 1];
+ g.cap[3] = s, g.cap_t[3] = 3;
+}
+
+static void go(int scene) { g.scene = scene, g.t = 0, g.menu = 0; }
+
+void start_night(int night, int shadow) {
+ night_begin(night, shadow);
+ memset(g.cap, 0, sizeof g.cap);
+ go(SC_CARD);
+}
+
+void game_init(void) {
+ memset(&g, 0, sizeof g);
+ g.running = true;
+ seed ^= plat_millis() * 2654435761u;
+ save_restore_copy();
+ save_load();
+ if (save_resume_load()) g.scene = SC_NIGHT, g.paused = 1;
+}
+
+/* ------------------------------------------------------------ the title */
+enum { M_NEW, M_CONTINUE, M_SIXTH, M_EXTRA };
+static int title_items(uint8_t *items) {
+ int n = 0;
+ items[n++] = M_NEW, items[n++] = M_CONTINUE;
+ if (g.beat5) items[n++] = M_SIXTH, items[n++] = M_EXTRA;
+ return n;
+}
+static int continue_night(void) { return g.level < 1 ? 1 : g.level > 5 ? 5 : g.level; }
+
+static void title_step(void) {
+ uint8_t items[4];
+ int n = title_items(items);
+ 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)) g.running = false;
+ if (!pressed(OKS)) return;
+ switch (items[g.menu]) {
+ case M_NEW: g.level = 1, save_progress(), start_night(1, 0); break;
+ case M_CONTINUE: start_night(continue_night(), 0); break;
+ case M_SIXTH: start_night(6, 0); break;
+ case M_EXTRA: go(SC_EXTRAS), g.ex_sel = 0, g.ex_lr = 0; break;
+ }
+}
+
+static void title_draw(void) {
+ /* (the logo flickers: fainter now and then, and a glitch of 1 in 6 half-seconds) */
+ int k = (int)(g.t * 2), r = (int)(rnd() % 20);
+ int pic = (k * 7 + 3) % 6 == 0 ? PIC_TITLE_GLITCH1 + (k % 3) : r < 6 ? PIC_TITLE_FAINT : PIC_TITLE;
+ pic_draw(pic, 0, 0);
+ uint8_t items[4];
+ int n = title_items(items);
+ static const uint8_t ids[4] = {IMG_M_NEW, IMG_M_CONTINUE, IMG_M_SIXTH, IMG_M_EXTRA};
+ for (int i = 0; i < n; i++) {
+ int y = 104 + 23 * i;
+ if (i == g.menu)
+ gfx_img(IMG_REDLINE, -70, y + gfx_img_h(ids[items[i]]) / 2 - gfx_img_h(IMG_REDLINE) / 2, RGB((0x30 + rnd() % 0xA0) << 16));
+ gfx_img(ids[items[i]], 90, y, MENU);
+ if (items[i] == M_CONTINUE) {
+ char t[12];
+ snprintf(t, sizeof t, "Night %d", continue_night());
+ gfx_text_s(FONT_HUD, 90 + gfx_img_w(IMG_M_CONTINUE) + 8, y, t, GREY_TEXT);
+ }
+ }
+ uint8_t stars[4] = {g.beat5, g.beat6, g.beat7, g.beat8};
+ for (int i = 0; i < 4; i++)
+ if (stars[i]) gfx_img(IMG_STAR, 6 + 40 * i, SCREEN_H - 6 - gfx_img_h(IMG_STAR), RGB(0x8B0000));
+}
+
+/* ------------------------------------------------------------ extras */
+enum { X_ANIMATRONICS, X_FOXY, X_FREDBEAR, X_JUMPSCARES, X_PLUSHTRAP, X_NIGHTMARE, X_EXIT };
+static const uint8_t ex_ids[7] = {IMG_M_ANIMATRONICS, IMG_M_MAKINGFOXY, IMG_M_MAKINGFREDBEAR, IMG_M_JUMPSCARES,
+ IMG_M_PLUSHTRAP, IMG_M_NIGHTMARE, IMG_M_EXIT};
+static bool ex_open(int i) { return i <= X_FOXY || i == X_EXIT || g.beat6; }
+static const char *const names[7] = {"Nightmare Freddy", "Nightmare Bonnie", "Nightmare Chica", "Nightmare Foxy",
+ "Nightmare Fredbear", "Plushtrap", "Nightmare"};
+static void extras_step(void) {
+ int n = 7;
+ if (pressed(UPS)) do g.ex_sel = (uint8_t)((g.ex_sel + n - 1) % n); while (!ex_open(g.ex_sel));
+ if (pressed(DOWNS)) do g.ex_sel = (uint8_t)((g.ex_sel + 1) % n); while (!ex_open(g.ex_sel));
+ if (pressed(UPS | DOWNS)) g.ex_lr = 0, g.t = 0;
+ int max = g.ex_sel <= X_JUMPSCARES ? 6 : 0;
+ if (pressed(K_LEFT | K_DIGIT(4)) && g.ex_lr > 0) g.ex_lr--, g.t = 0;
+ if (pressed(K_RIGHT | K_DIGIT(6)) && g.ex_lr < max) g.ex_lr++, g.t = 0;
+ if (pressed(K_BACK)) go(SC_TITLE);
+ if (!pressed(OKS)) return;
+ switch (g.ex_sel) {
+ case X_ANIMATRONICS:
+ if (g.ex_lr == 6 && g.beat7) g.twenty ^= 1; /* (the game's double click on the Nightmare) */
+ break;
+ case X_PLUSHTRAP: plush_begin(true), go(SC_PLUSHCARD); break;
+ case X_NIGHTMARE: start_night(g.twenty ? 8 : 7, g.twenty ? 2 : 1); break;
+ case X_EXIT: go(SC_TITLE); break;
+ }
+}
+
+static void extras_draw(void) {
+ gfx_fill(0, 0, SCREEN_W, SCREEN_H, BLACK);
+ for (int i = 0; i < 7; i++) {
+ int y = 10 + 22 * i + (i == X_EXIT ? 14 : 0);
+ int id = i == X_NIGHTMARE && g.twenty ? IMG_M_TWENTY : ex_ids[i];
+ if (i == g.ex_sel) gfx_img(IMG_REDLINE, -150, y + gfx_img_h(id) / 2 - gfx_img_h(IMG_REDLINE) / 2, RGB(0xA00000));
+ gfx_img(id, 8, y, ex_open(i) ? MENU : RGB(0x301010));
+ }
+ int cx = 230;
+ int lr = g.ex_lr;
+ switch (g.ex_sel) {
+ case X_ANIMATRONICS:
+ pic_draw(PIC_ANIMATRONIC0 + (lr == 6 && !g.beat7 ? 7 : lr), cx - 88, 4);
+ gfx_text_c(FONT_TEXT, cx, 216, lr == 6 && !g.beat7 ? "???" : names[lr], WHITE);
+ break;
+ case X_FOXY: pic_draw(PIC_MAKINGFOXY0 + lr, cx - 88, 20); break;
+ case X_FREDBEAR: pic_draw(PIC_MAKINGFREDBEAR0 + lr, cx - 88, 20); break;
+ case X_JUMPSCARES: {
+ int an = scare_anim(lr);
+ int f = (int)(g.t * 60), len = an >= 0 ? anim_frames(an) : 1;
+ int id = an < 0 ? PIC_NIGHTMARE : anim_pic(an, f >= len ? anim_len(an) - 1 : f * anim_len(an) / len);
+ pic_part(id, cx - 88, 20, 72, 16, 176, 176);
+ gfx_text_c(FONT_TEXT, cx, 216, names[lr], WHITE);
+ break;
+ }
+ case X_PLUSHTRAP:
+ pic_draw(PIC_PLUSHTRAP, cx - 88, 20);
+ gfx_text_c(FONT_TEXT, cx, 210, "OK play", WHITE);
+ break;
+ case X_NIGHTMARE: gfx_text_c(FONT_TEXT, cx, 110, g.twenty ? "OK 20/20/20/20" : "OK the Nightmare", WHITE); break;
+ }
+ if (g.ex_sel <= X_JUMPSCARES) {
+ int max = 6;
+ if (lr > 0) gfx_text(FONT_BIG, cx - 100, 96, "<", MENU);
+ if (lr < max) gfx_text(FONT_BIG, cx + 92, 96, ">", MENU);
+ }
+ const char *keys = g.ex_sel <= X_JUMPSCARES ? "Up Down choose Left Right turn Back title" : "Up Down choose OK pick Back title";
+ gfx_text(FONT_HUD, 8, SCREEN_H - 13, keys, GREY_TEXT);
+}
+
+/* ------------------------------------------------------------ the night and around it */
+static void captions_draw(void) {
+ int y = SCREEN_H - 30;
+ if (g.hold) gfx_text_s(FONT_TEXT, 8, y, g.hold, WHITE), y -= 13;
+ for (int i = 3; i >= 0; i--) {
+ if (!g.cap[i] || g.cap_t[i] <= 0) continue;
+ gfx_text_s(FONT_TEXT, 8, y, g.cap[i], WHITE);
+ y -= 13;
+ }
+}
+
+static void pause_step(void) {
+ if (g.confirm) {
+ if (pressed(OKS)) {
+ if (g.scene == SC_NIGHT) save_resume();
+ go(SC_TITLE), g.paused = 0, g.confirm = 0;
+ }
+ if (pressed(K_BACK)) g.confirm = 0;
+ return;
+ }
+ if (pressed(UPS | DOWNS)) g.pause_item ^= 1;
+ if (pressed(K_BACK)) g.paused = 0;
+ if (pressed(OKS)) {
+ if (g.pause_item == 0) g.paused = 0;
+ else g.confirm = 1;
+ }
+}
+
+static void pause_draw(void) {
+ gfx_dim(0, 60, SCREEN_W, 120, 22);
+ if (g.confirm) {
+ gfx_text_c(FONT_TEXT, SCREEN_W / 2, 90, "Quit the night?", WHITE);
+ gfx_text_c(FONT_HUD, SCREEN_W / 2, 120, "OK quit Back stay", WHITE);
+ return;
+ }
+ gfx_text_c(FONT_BIG, SCREEN_W / 2, 74, "Paused", WHITE);
+ gfx_text_c(FONT_TEXT, SCREEN_W / 2, 110, g.pause_item == 0 ? "> Resume <" : "Resume", WHITE);
+ gfx_text_c(FONT_TEXT, SCREEN_W / 2, 134, g.pause_item == 1 ? "> Quit game <" : "Quit game", WHITE);
+}
+
+/* 6 AM (the "night win" frame): the night's star saved, the next night reached */
+static void six_begin(void) {
+ int night = g.n.night;
+ g.level = (uint8_t)(night + 1);
+ if (night == 5) g.beat5 = 1;
+ if (night == 6) g.beat6 = 1;
+ if (night == 7) g.beat7 = 1;
+ if (night == 8) g.beat8 = 1;
+ save_progress();
+ go(SC_SIX);
+}
+
+static void six_done(void) {
+ int night = g.n.night;
+ if (night <= 5) plush_begin(false), go(SC_PLUSHCARD);
+ else if (night == 6) g.text = 0, g.gone = 0, g.talk_t = 0, g.wait = 0, go(SC_END);
+ else if (night == 7) g.wait = 0, go(SC_BOX);
+ else go(SC_TITLE);
+}
+
+/* the next night after Fun with Plushtrap (its "night" was saved at 6 AM) */
+static void after_plush(void) {
+ if (g.p.from_extras) go(SC_EXTRAS);
+ else start_night(g.level, 0);
+}
+
+/* the ending: the words come one at a time ("text counter", a second at a time while none shows), OK for the next
+ * (as the game's touch, once the box is still); each answer takes a toy away */
+static const char *const lines[14] = {NULL, "Can you hear me?", "I don't know if you can hear me.", "....I'm sorry.",
+ NULL, "You're broken.", NULL, "We are still your friends.", NULL,
+ "Do you still believe that?", NULL, "I'm still here.", NULL,
+ "I will put you back together."};
+static void end_step(void) {
+ if (g.wait) g.wait--;
+ if (g.text == 0) {
+ int was = (int)g.talk_t;
+ g.talk_t += 1.0f / 60;
+ int s = (int)g.talk_t;
+ static const uint8_t at[6] = {3, 6, 9, 12, 15, 18}, to[6] = {1, 5, 7, 9, 11, 13};
+ for (int i = 0; i < 6; i++)
+ if (s == at[i] && was != s) g.text = to[i], g.wait = 50;
+ if (g.talk_t >= 30) go(SC_TITLE);
+ return;
+ }
+ if (pressed(OKS) && !g.wait) {
+ g.text++, g.wait = 50;
+ if (g.text == 4) g.text = 0;
+ else if (g.text >= 6 && g.text % 2 == 0) g.text = 0, g.gone++;
+ }
+}
+static void end_draw(void) {
+ pic_draw(g.talk_t >= 25 ? PIC_ENDING7 : g.talk_t >= 21 ? PIC_ENDING6 : PIC_ENDING0 + g.gone, 0, 0);
+ const char *l = g.text < 14 ? lines[g.text] : NULL;
+ if (l) {
+ gfx_fill(0, 0, SCREEN_W, 64, RGB(0x05050A));
+ gfx_text_c(FONT_SERIF, SCREEN_W / 2, 22, l, g.text <= 3 ? RGB(0x787878) : RGB(0xFFFFA0));
+ if (!g.wait && (int)(g.t * 4) % 2) gfx_img(IMG_ARROW, SCREEN_W - 26, 44, WHITE);
+ }
+}
+
+void game_step(uint32_t keys) {
+ g.pressed = keys & ~g.held;
+ g.held = keys;
+ if (keys & K_HOME) {
+ if (g.scene == SC_NIGHT && !g.n.gameover) save_resume();
+ g.running = false;
+ return;
+ }
+ for (int i = 0; i < 4; i++)
+ if (g.cap_t[i] > 0) g.cap_t[i] -= 1.0f / 60;
+ switch (g.scene) {
+ case SC_WARN:
+ if (g.t > 2 || pressed(OKS | K_BACK)) go(SC_TITLE);
+ break;
+ case SC_TITLE: title_step(); break;
+ case SC_EXTRAS: extras_step(); break;
+ case SC_CARD:
+ if (g.t > 2.1f) go(SC_NIGHT);
+ break;
+ case SC_NIGHT: {
+ if (g.paused) {
+ pause_step();
+ break;
+ }
+ if (pressed(K_BACK)) {
+ g.paused = 1, g.pause_item = 0;
+ break;
+ }
+ night_step();
+ Night *n = &g.n;
+ int top = night_top();
+ bool fredbear = top == O_FREDBEAR;
+ if (fredbear && n->shadow) go(SC_NIGHTMARE); /* 413 */
+ else if (top >= O_JUMP && n->ob[top].done) go(SC_OVER); /* 193 to 196, 277, 289, 290, 359 */
+ else if (n->hour == 6) six_begin(); /* 370 */
+ break;
+ }
+ case SC_OVER:
+ if (g.t > 7 || (g.t > 1 && pressed(OKS | K_BACK))) go(SC_TITLE);
+ break;
+ case SC_NIGHTMARE:
+ if (g.t > 5) go(SC_WARN);
+ break;
+ case SC_SIX:
+ if (g.t > 10 || (g.t > 4 && pressed(OKS))) six_done();
+ break;
+ case SC_PLUSHCARD:
+ if (g.t > 4 || (g.t > 1 && pressed(OKS))) go(SC_PLUSH);
+ break;
+ case SC_PLUSH:
+ if (g.paused) {
+ pause_step();
+ break;
+ }
+ if (pressed(K_BACK)) {
+ g.paused = 1, g.pause_item = 0;
+ break;
+ }
+ plush_step();
+ if (plush_done() == 1) after_plush();
+ if (plush_done() == 2) go(SC_TOOBAD);
+ break;
+ case SC_TOOBAD:
+ if (g.t > 6 || (g.t > 1 && pressed(OKS))) after_plush();
+ break;
+ case SC_END: end_step(); break;
+ case SC_BOX:
+ if (pressed(OKS) && !g.wait) g.wait = RATTLE_N * 2; /* (still locked: the locks shake) */
+ if (g.wait) g.wait--;
+ if (g.t > 20) go(SC_TITLE);
+ break;
+ }
+ g.t += 1.0f / 60;
+}
+
+void game_draw(void) { gfx_frame(game_band); }
+
+static void key_line(const char *s) {
+ gfx_dim(0, SCREEN_H - 14, SCREEN_W, 14, 20);
+ gfx_text(FONT_HUD, 6, SCREEN_H - 13, s, WHITE);
+}
+
+/* (gfx_frame calls this for each band) */
+static void game_band(void) {
+ switch (g.scene) {
+ case SC_WARN:
+ gfx_fill(0, 0, SCREEN_W, SCREEN_H, BLACK);
+ gfx_text_c(FONT_SERIF, SCREEN_W / 2, 96, "WARNING!", RGB(0xC00000));
+ gfx_text_c(FONT_TEXT, SCREEN_W / 2, 122, "This game contains flashing lights, loud noises,", RGB(0xC00000));
+ gfx_text_c(FONT_TEXT, SCREEN_W / 2, 136, "and lots of jumpscares!", RGB(0xC00000));
+ break;
+ case SC_TITLE: title_draw(); break;
+ case SC_EXTRAS: extras_draw(); break;
+ case SC_CARD: {
+ pic_draw(PIC_WHATNIGHT, 0, 0);
+ gfx_fill(0, 13, 170, 38, BLACK);
+ gfx_img(IMG_NIGHTWORD, 12, 16, WHITE);
+ char t[4];
+ snprintf(t, sizeof t, "%d", g.n.night);
+ gfx_text(FONT_HUGE, 16 + gfx_img_w(IMG_NIGHTWORD), 6, t, WHITE);
+ if (g.t > 2) gfx_img(IMG_CLOCK, SCREEN_W - 26, SCREEN_H - 26, WHITE);
+ break;
+ }
+ case SC_NIGHT:
+ view_night();
+ captions_draw();
+ if (night_top() < O_JUMP) {
+ const char *k = night_keys();
+ if (k) key_line(k);
+ }
+ if (g.paused) pause_draw();
+ break;
+ case SC_OVER: pic_draw(PIC_GAMEOVER, 0, 0); break;
+ case SC_NIGHTMARE:
+ pic_draw(PIC_NIGHTMARE, 0, 0);
+ gfx_static(0, 0, SCREEN_W, SCREEN_H, 6 + (int)rnd_n(8), (uint32_t)(g.t * 60));
+ break;
+ case SC_SIX: {
+ /* the alarm clock: each digit spins until it stops (2, 2.5, 3, 3.5 s) on 06:00, which blinks from 4 s */
+ gfx_fill(0, 0, SCREEN_W, SCREEN_H, BLACK);
+ static const uint8_t final[4] = {0, 6, 0, 0};
+ static const int16_t cx[4] = {80, 129, 195, 244};
+ bool shown = g.t < 4 || (int)((g.t - 4) / 0.24f) % 2 == 0;
+ for (int i = 0; i < 4 && shown; i++) {
+ int d = g.t >= 2 + 0.5f * i ? final[i] : (int)((rnd() >> 4) % 10);
+ int id = IMG_DIGIT0 + d;
+ gfx_img(id, cx[i] - gfx_img_w(id) / 2, 120 - gfx_img_h(id) / 2, RGB(CLOCK_RED));
+ }
+ if (shown) gfx_img(IMG_COLON, 164 - gfx_img_w(IMG_COLON) / 2, 120 - gfx_img_h(IMG_COLON) / 2, RGB(CLOCK_RED));
+ break;
+ }
+ case SC_PLUSHCARD:
+ pic_draw(PIC_PLUSHCARD, 0, 0);
+ gfx_fill(0, 176, SCREEN_W, 64, BLACK);
+ gfx_text_c(FONT_TEXT, SCREEN_W / 2, 186, "Hold OK for the flashlight.", WHITE);
+ gfx_text_c(FONT_TEXT, SCREEN_W / 2, 202, "Stop Plushtrap on the X with it", WHITE);
+ gfx_text_c(FONT_TEXT, SCREEN_W / 2, 216, "to skip 2 hours of the next night.", WHITE);
+ break;
+ case SC_PLUSH:
+ view_plush();
+ captions_draw();
+ key_line("OK light Back pause");
+ if (g.paused) pause_draw();
+ break;
+ case SC_TOOBAD: pic_draw(PIC_TOOBAD, 0, 0); break;
+ case SC_END: end_draw(); break;
+ case SC_BOX: {
+ int k = g.wait ? (RATTLE_N * 2 - g.wait) / 2 : 0;
+ pic_draw(k > 0 && k < RATTLE_N ? PIC_LOCKBOX1 + k - 1 : PIC_LOCKBOX, 0, 0);
+ if (g.t > 15) {
+ int a = (int)((g.t - 15) / 0.06f);
+ a = a > 75 ? 75 : a;
+ int v = 0xFF * a / 255;
+ gfx_img(IMG_FORGOTTEN, SCREEN_W / 2 - gfx_img_w(IMG_FORGOTTEN) / 2, 62 - gfx_img_h(IMG_FORGOTTEN) / 2,
+ (uint16_t)RGB(v << 16 | v << 8 | v));
+ }
+ if (g.t < 15) key_line("OK the locks");
+ break;
+ }
+ }
+}
diff --git a/games/fnaf4/src/game.h b/games/fnaf4/src/game.h
new file mode 100644
index 00000000..304e6bd6
--- /dev/null
+++ b/games/fnaf4/src/game.h
@@ -0,0 +1,158 @@
+/* Five Nights at Freddy's 4: the game's state and its parts.
+ *
+ * game.c: the scenes (the warning, the title, extras, the night's card, 6 AM, Fun with Plushtrap, game over, the
+ * ending and the box), keys and saves. night.c: a night as the game's own events run it (the bedroom, its two doors,
+ * the closet and the bed; Bonnie, Chica, Foxy, the Freddles, Fredbear and Nightmare), 60 steps a second, in the
+ * events' order. view.c: drawing it. The game's names for its objects and counters are kept in the comments. */
+#ifndef FNAF4_GAME_H
+#define FNAF4_GAME_H
+#include <stdbool.h>
+#include <stdint.h>
+
+/* where an animatronic can be (the markers it overlaps); P_AWAY: off the map (its AI is 0) */
+enum { P_AWAY, P_LRC, P_LRL, P_LRR, P_KITCHEN, P_LHF, P_RHF, P_LHN, P_RHN, P_CLOSET, P_BED };
+
+/* the night's objects that come and go (each its animation, AN_* in anims.h); O_ROOM is the bedroom ("Active") */
+enum {
+ O_ROOM, O_DARKL, O_DARKR, O_DARKC, O_OFF4, O_ON4, O_CREAK, O_CARPET, O_LSTART, O_RSTART, O_PEEKL, O_PEEKR,
+ O_CLOSET, O_BED, O_BHIDE, O_CHIDE, O_LEAVE3, O_LEAVE2, O_LEAVE1, O_BITE, O_JUMP, O_FREDDYATK, O_CUPCAKE,
+ O_BONNIEATK, O_FREDBEAR, O_COUNT
+};
+
+typedef struct {
+ uint8_t alive, vis;
+ uint8_t an; /* AN_* */
+ uint8_t img; /* its picture */
+ uint8_t cnt; /* the speed counter: a picture each 100 */
+ uint8_t plays; /* plays left (0: for ever) */
+ uint8_t done; /* its animation is over */
+ uint16_t z; /* made after the ones lower (drawn over them) */
+} Ob;
+
+typedef struct {
+ uint8_t loc; /* P_* */
+ uint8_t s0, s1, s5, s6, s7; /* its alterable values A, B, F, G, H */
+} Anim;
+
+/* A night, all of it: kept as it is when Home quits (save.c), so the next start goes on from there. */
+typedef struct {
+ uint8_t night; /* "Night": 1 to 8 (7 is the Nightmare, 8 the 20/20/20/20) */
+ uint8_t shadow; /* "shadow": 0, 1 (the Nightmare), 2 (20/20/20/20) */
+ uint8_t hour; /* "hour": 12, then 1 to 6 */
+ uint8_t ai_bonnie, ai_chica, ai_foxy, ai_freddy, ai_fredbear; /* "Bonnie AI" ... "Fredbear AI" */
+ uint8_t force_bonnie, force_chica; /* the hour each comes to the door once (nights 2 to 4) */
+ uint8_t s0; /* "follow" A: where you are and what you do (the game's numbers, 0 to 45, 99) */
+ int16_t x; /* "follow" X: where the bedroom view looks, 400 to 600 */
+ uint8_t s3; /* "follow" D */
+ uint8_t what_side; /* "what side": 1 at the left door, 2 going left, 3 the bed's side, 4 going right, 5 right */
+ uint8_t flash, shut; /* "flashlight", "close door" */
+ uint8_t listening; /* "listening mode": 1 the left door, 2 the right */
+ uint8_t left_shut, right_shut;
+ uint8_t view_left, view_right, view_closet, view_bed; /* "viewing left hall" ... */
+ uint8_t door_lock; /* "in closet" F: the doors held on them, nobody moves (1) or they went (2) */
+ uint8_t kitchen2, kitchen3, kitchen4; /* "kitchen" C, D, E: the lights on Fredbear */
+ uint8_t gameover, got_you, foxy_got_you, fredcheck, force_turn;
+ uint8_t bed_foxy; /* (385: Foxy gets you for looking at the bed 15 seconds) */
+ uint8_t random; /* "random": the empty bed's picture */
+ int16_t freddy; /* "Freddy counter": the Freddles */
+ Anim bonnie, chica;
+ uint8_t foxy, foxy_s0, foxy_s1, foxy_s2, foxy_s3, foxy_s5; /* "foxy": where, A, B, C (the closet), D, F */
+ uint8_t fred, fred_s0, fred_s1; /* "Fredbear": where, A (his side), B (to move) */
+ uint8_t fred_s4, fred_s5, fred_s6, fred_s7, fred_s12, fred_s13, fred_s14, fred_s18, fred_s19;
+ uint8_t fred_s8, fred_s9; /* frames the light is on him in a hall */
+ uint8_t flash_vis; /* "black flash": shown, A to F, S (frames) */
+ int16_t bf0, bf1, bf2, bf3, bf6, bf18;
+ int16_t bf_alpha; /* its transparency: 0 black, 255 none */
+ int16_t fade; /* "black flash 2": the night's start, from black */
+ uint8_t warning; /* "door warning" (the first night until 2 AM) */
+ uint8_t total; /* "total danger" */
+ uint16_t zc;
+ uint8_t jump_kind; /* (the scare playing, for the game over) */
+ uint8_t dead; /* the scare is over: game over */
+ Ob ob[O_COUNT];
+ uint16_t every[44]; /* frames left of each "every" timer */
+ uint32_t last[52]; /* the step each "only once while true" was last true */
+ uint8_t once[4]; /* "run this event once" done */
+ uint32_t frame; /* steps since the night began */
+} Night;
+
+/* Fun with Plushtrap */
+typedef struct {
+ uint8_t loc; /* "plushtrap" overlapping: 0 chair, 1 hall 1, 2 far left, 3 far right, 4 hall 2,
+ 5 close left, 6 close right, 7 hall 3 (the X), 8 got you */
+ uint8_t light; /* "light on" */
+ uint8_t s0, s1; /* "Active" A, B */
+ int16_t active; /* "becoming active" */
+ uint8_t move, aggressive, random;
+ int16_t counter; /* "Counter": seconds left */
+ uint16_t s2; /* "Active" C: frames since GREAT! */
+ uint8_t an, img, cnt, plays, done; /* "Active"'s animation */
+ uint8_t from_extras; /* "minigame play" */
+ uint32_t frame;
+ uint16_t every[3];
+} Plush;
+
+/* scenes */
+enum { SC_WARN, SC_TITLE, SC_EXTRAS, SC_CARD, SC_NIGHT, SC_OVER, SC_SIX, SC_PLUSHCARD, SC_PLUSH, SC_TOOBAD,
+ SC_END, SC_BOX, SC_NIGHTMARE };
+
+typedef struct {
+ int scene;
+ float t; /* seconds in the scene */
+ uint32_t held, pressed;
+ bool running;
+ /* the save (Ini "fn4"): the night reached and the stars */
+ uint8_t level, beat5, beat6, beat7, beat8;
+ uint8_t reward; /* "reward": Plushtrap caught, the next night starts at 2 AM */
+ uint8_t twenty; /* "shadow freddy" B: the extras' Nightmare is 20/20/20/20 */
+ uint8_t menu, paused, confirm, pause_item;
+ uint8_t ex_sel, ex_lr; /* extras: "selection", "left/right" */
+ uint8_t text, gone; /* the ending's "text", the toys gone */
+ float talk_t; /* its "text counter" */
+ uint8_t wait; /* frames before OK does something again */
+ const char *cap[4]; /* what is heard, as captions (the newest last) */
+ float cap_t[4];
+ const char *hold; /* heard while it lasts (breathing, the kitchen) */
+ Night n;
+ Plush p;
+} Game;
+
+extern Game g;
+
+/* game.c */
+void game_init(void);
+void game_step(uint32_t keys);
+void game_draw(void);
+uint32_t rnd(void);
+uint32_t rnd_n(uint32_t n); /* Random(n): 0..n-1 */
+void start_night(int night, int shadow);
+void caption(const char *s);
+
+/* night.c */
+void night_begin(int night, int shadow);
+void night_step(void);
+int night_top(void); /* the object on top (O_*), -1 none */
+int ob_pic(int o); /* an object's picture now */
+bool ob_wide(int o); /* drawn in the bedroom (it pans) */
+int anim_pic(int an, int k); /* an animation's picture k */
+int anim_len(int an); /* its pictures */
+int anim_count(void);
+int anim_frames(int an); /* frames one play lasts */
+const char *night_keys(void);
+void plush_begin(bool from_extras);
+void plush_step(void);
+int plush_done(void); /* 1 caught on the X, 2 lost */
+int plush_pic(void);
+int scare_anim(int k); /* extras' jumpscares: the animatronics' in their order (-1 Nightmare's picture) */
+
+/* view.c */
+void view_night(void);
+void view_plush(void);
+
+/* save.c */
+void save_restore_copy(void);
+void save_progress(void);
+void save_load(void);
+void save_resume(void); /* the night as it is (Home) */
+bool save_resume_load(void);
+#endif
diff --git a/games/fnaf4/src/gfx.c b/games/fnaf4/src/gfx.c
new file mode 100644
index 00000000..3a516a68
--- /dev/null
+++ b/games/fnaf4/src/gfx.c
@@ -0,0 +1,167 @@
+/* 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);
+}
diff --git a/games/fnaf4/src/gfx.h b/games/fnaf4/src/gfx.h
new file mode 100644
index 00000000..41fee25d
--- /dev/null
+++ b/games/fnaf4/src/gfx.h
@@ -0,0 +1,53 @@
+/* Five Nights at Freddy's 4: 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 FNAF4_GFX_H
+#define FNAF4_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 at (x, y), or the part (sx, sy, w, h) of it */
+void pic_draw(int id, int x, int y);
+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);
+#endif
diff --git a/games/fnaf4/src/icon.png b/games/fnaf4/src/icon.png
new file mode 100644
index 00000000..fa7df2f4
Binary files /dev/null and b/games/fnaf4/src/icon.png differ
diff --git a/games/fnaf4/src/main.c b/games/fnaf4/src/main.c
new file mode 100644
index 00000000..21e3bdfb
--- /dev/null
+++ b/games/fnaf4/src/main.c
@@ -0,0 +1,46 @@
+/* Five Nights at Freddy's 4 for the NumWorks calculator.
+ *
+ * Inspired by Five Nights at Freddy's 4 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 4";
+const uint32_t eadk_api_level __attribute__((section(".rodata.eadk_api_level"))) = 0;
+extern const uint8_t fnaf4_data[];
+const uint8_t *fnaf4_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();
+ fnaf4_bin = fnaf4_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/fnaf4/src/night.c b/games/fnaf4/src/night.c
new file mode 100644
index 00000000..a9e16310
--- /dev/null
+++ b/games/fnaf4/src/night.c
@@ -0,0 +1,688 @@
+/* Five Nights at Freddy's 4: a night, as the game's own events run it (its "level" frame, 458 events, read out of
+ * its iOS package; gamesrc spec level_events.txt), 60 steps a second and in the events' order. The numbers in the
+ * comments are the events'.
+ *
+ * You are in the bedroom. Its two doors open on halls, Bonnie comes up the left one and Chica the right; listen at
+ * a door (no light): breathing means one stands there, so hold the door shut until the steps go; no breathing, the
+ * light sends one in the far hall away. Foxy runs into the closet when your back is turned; shut its door on him.
+ * The Freddles gather on the bed when you don't look; the light makes them go. On the 5th night and after 4 AM on
+ * the 6th, Fredbear (Nightmare after it) comes up a hall when you listen at the other door, then to the closet or
+ * the bed. Their moves are the game's: a chance every few seconds, out of 20, against each one's AI. */
+#include <string.h>
+#include "game.h"
+#include "plat.h"
+#include "data.h"
+#include "anims.h"
+
+#define N g.n
+
+/* ------------------------------------------------------------ the game's objects and their animations */
+int anim_pic(int an, int k) { return ANIM_PICS[ANIMS[an].first + k]; }
+int anim_len(int an) { return ANIMS[an].n; }
+int anim_count(void) { return AN_COUNT; }
+int anim_frames(int an) {
+ int s = ANIMS[an].speed ? ANIMS[an].speed : 1;
+ return ANIMS[an].n * (ANIMS[an].plays ? ANIMS[an].plays : 1) * 100 / s;
+}
+
+static const uint8_t first_anim[O_COUNT] = {
+ AN_ROOM_0, AN_DARKL, AN_DARKR, AN_DARKC, AN_OFF4, AN_ON4, AN_CREAK, AN_CARPET, AN_LSTART, AN_RSTART,
+ AN_PEEKL_12, AN_PEEKR_12, AN_CLOSET_0, AN_BED_0, AN_BHIDE, AN_CHIDE, AN_LEAVE3, AN_LEAVE2, AN_LEAVE1, AN_BITE,
+ AN_JUMP_0, AN_FREDDYATK, AN_CUPCAKE, AN_BONNIEATK, AN_FREDBEAR};
+
+static void set_anim(int o, int an) { /* (the same animation goes on) */
+ Ob *b = &N.ob[o];
+ if (b->an == an) return;
+ b->an = (uint8_t)an, b->img = 0, b->cnt = 0, b->plays = ANIMS[an].plays, b->done = 0;
+}
+static void create(int o) {
+ Ob *b = &N.ob[o];
+ memset(b, 0, sizeof *b);
+ b->alive = b->vis = 1;
+ b->z = ++N.zc;
+ b->an = 0xFF;
+ set_anim(o, first_anim[o]);
+}
+static void destroy(int o) { N.ob[o].alive = 0; }
+static bool alive(int o) { return N.ob[o].alive; }
+static bool over(int o, int an) { return N.ob[o].alive && N.ob[o].an == an && N.ob[o].done; } /* (C-2) */
+static bool playing(int o, int an) { return N.ob[o].alive && N.ob[o].an == an && !N.ob[o].done; }
+
+static void animate(void) {
+ for (int o = 0; o < O_COUNT; o++) {
+ Ob *b = &N.ob[o];
+ const AnimDef *d = &ANIMS[b->an];
+ if (!b->alive || b->done || !d->speed) continue;
+ b->cnt = (uint8_t)(b->cnt + d->speed);
+ while (b->cnt >= 100) {
+ b->cnt = (uint8_t)(b->cnt - 100);
+ if (b->img + 1 < d->n) b->img++;
+ else if (b->plays == 1) {
+ b->done = 1;
+ break;
+ } else {
+ if (b->plays) b->plays--;
+ b->img = 0;
+ }
+ }
+ }
+}
+
+int scare_anim(int k) {
+ static const int8_t a[7] = {AN_JUMP_14, AN_JUMP_13, AN_JUMP_12, AN_JUMP_0, AN_FREDBEAR, AN_PLUSH_23, -1};
+ return a[k];
+}
+
+int ob_pic(int o) { return anim_pic(N.ob[o].an, N.ob[o].img); }
+bool ob_wide(int o) { return ANIMS[N.ob[o].an].wide; }
+
+int night_top(void) {
+ int top = -1;
+ for (int o = 0; o < O_COUNT; o++)
+ if (N.ob[o].alive && N.ob[o].vis && (top < 0 || N.ob[o].z > N.ob[top].z)) top = o;
+ return top;
+}
+
+/* ------------------------------------------------------------ the events' conditions */
+/* "every N ms": each event its own count, which runs only while the conditions before it hold */
+enum { T_SECOND, T_FOXY5, T_BONNIE5, T_CHICA5, T_FRED3, T_FRED2, T_BONNIE10, T_CHICA10, T_BONNIE3, T_CHICA3,
+ T_FREDDY4, T_FREDDY50, T_FREDDY3, T_FOXY1, T_DANGER, T_D2, T_D3, T_D4, T_D5, T_CHICA_S6, T_BONNIE_S6,
+ T_FRED_L3, T_FRED_R3, T_FRED_S4, T_FRED_S5, T_CLOSET_L, T_CLOSET_R, T_FRED_S7, T_LAUGH, T_FRED_S6B,
+ T_FRED_S6C, T_FRED_S12, T_HOUR, T_TURN_B, T_TURN_C, T_FRED_S13, T_FREDDY200, T_FRED_S14, T_FRED30A,
+ T_FRED30B, T_FRED_S19L, T_FRED_S19R, T_COUNT };
+_Static_assert(T_COUNT <= sizeof(((Night *)0)->every) / sizeof(uint16_t), "timers");
+static bool every(int id, int ms) {
+ uint16_t p = (uint16_t)(ms * 60 / 1000);
+ if (!N.every[id]) N.every[id] = p;
+ if (--N.every[id]) return false;
+ N.every[id] = p;
+ return true;
+}
+/* "only one action when event loops": true when the event was not true the step before */
+static bool edge(int id) {
+ bool r = N.last[id] != N.frame;
+ N.last[id] = N.frame + 1;
+ return r;
+}
+/* "run this event once" */
+static bool once(int id) {
+ if (N.once[id >> 3] >> (id & 7) & 1) return false;
+ N.once[id >> 3] |= (uint8_t)(1 << (id & 7));
+ return true;
+}
+static bool chance(int out_of, int ai) { return (int)rnd_n((uint32_t)out_of) + 1 <= ai; } /* Random(n)+1 <= AI */
+
+/* ------------------------------------------------------------ what you'd hear */
+static void heard(const char *s) { caption(s); }
+
+/* ------------------------------------------------------------ a night */
+void night_begin(int night, int shadow) {
+ memset(&N, 0, sizeof N);
+ N.night = (uint8_t)night, N.shadow = (uint8_t)shadow;
+ N.hour = 12, N.x = 500, N.random = 4, N.what_side = 3; /* (66, 394) */
+ N.warning = 1;
+ create(O_ROOM);
+}
+
+static void moved(Anim *a, uint8_t to) { a->loc = to, a->s1 = 0; }
+
+/* the bedroom, the doors, the closet, the bed: you (events 3 to 101) */
+static void you(void) {
+ uint32_t held = g.held, pr = g.pressed;
+ bool ok = pr & (K_OK | K_EXE), back = pr & (K_DOWN | K_DIGIT(2));
+ if (N.x > 400 && (held & (K_LEFT | K_DIGIT(4))) && N.s0 < 7) N.x -= 10; /* 3 */
+ if (N.x < 600 && (held & (K_RIGHT | K_DIGIT(6))) && N.s0 < 7) N.x += 10; /* 4 */
+ if (N.x == 400 && N.s0 == 0) N.s0 = 1, set_anim(O_ROOM, AN_ROOM_12); /* 5 */
+ if (over(O_ROOM, AN_ROOM_12) && N.s0 == 1) set_anim(O_ROOM, AN_ROOM_13), N.s0 = 2;
+ if (N.s0 == 2 && N.x > 400) N.s0 = 3, set_anim(O_ROOM, AN_ROOM_14);
+ if (over(O_ROOM, AN_ROOM_14) && N.s0 == 3) N.s0 = 0, set_anim(O_ROOM, AN_ROOM_0);
+ if (N.s0 == 0 && N.x == 600) N.s0 = 4, set_anim(O_ROOM, AN_ROOM_15); /* 9 */
+ if (over(O_ROOM, AN_ROOM_15) && N.s0 == 4) N.s0 = 5, set_anim(O_ROOM, AN_ROOM_16);
+ if (N.s0 == 5 && N.x < 600) N.s0 = 6, set_anim(O_ROOM, AN_ROOM_17);
+ if (over(O_ROOM, AN_ROOM_17) && N.s0 == 6) N.s0 = 0, set_anim(O_ROOM, AN_ROOM_0);
+ /* to a door (13 to 23) */
+ if (ok && N.x == 400 && N.s0 == 2) N.s0 = 7, create(O_DARKL), ok = false;
+ if (ok && N.x == 600 && N.s0 == 5) N.s0 = 14, create(O_DARKR), ok = false;
+ if (over(O_DARKL, AN_DARKL) && N.s0 == 7)
+ N.s0 = 8, N.ob[O_ROOM].vis = 0, create(O_CARPET), N.what_side = 2, destroy(O_DARKL), N.x = 500;
+ if (over(O_DARKR, AN_DARKR) && N.s0 == 14)
+ N.s0 = 15, N.ob[O_ROOM].vis = 0, create(O_CARPET), N.what_side = 4, destroy(O_DARKR), N.x = 500;
+ if (over(O_CARPET, AN_CARPET) && N.s0 == 8)
+ destroy(O_CARPET), N.s0 = 9, N.what_side = 1, create(O_LSTART), N.x = 500;
+ if (over(O_CARPET, AN_CARPET) && N.s0 == 15)
+ destroy(O_CARPET), N.s0 = 16, N.what_side = 5, create(O_RSTART), N.x = 500;
+ if (over(O_LSTART, AN_LSTART) && N.s0 == 9) N.s0 = 10, create(O_PEEKL), destroy(O_LSTART);
+ /* the left door (24 to 44) */
+ if (N.s0 == 10 && !N.flash) set_anim(O_PEEKL, AN_PEEKL_12);
+ if (N.s0 == 10 && N.foxy != P_LHF && N.bonnie.loc != P_LHF && N.fred != P_LHF && N.flash)
+ set_anim(O_PEEKL, AN_PEEKL_13), N.view_left = 1;
+ if (N.s0 == 10 && N.fred == P_LHF && N.kitchen2 <= 1 && !N.shadow && N.flash) set_anim(O_PEEKL, AN_PEEKL_19), N.view_left = 1;
+ if (N.s0 == 10 && N.fred == P_LHF && N.kitchen2 > 1 && !N.shadow && N.flash) set_anim(O_PEEKL, AN_PEEKL_20), N.view_left = 1;
+ if (N.s0 == 10 && N.fred == P_LHF && N.shadow && N.flash) set_anim(O_PEEKL, AN_PEEKL_21), N.view_left = 1;
+ if (N.s0 == 10 && N.foxy == P_LHF && N.bonnie.loc != P_LHF && N.flash)
+ set_anim(O_PEEKL, AN_PEEKL_18), N.view_left = 1, N.s0 = 35, N.foxy = P_LRC;
+ if (N.s0 == 10 && N.bonnie.loc == P_LHF && N.flash)
+ N.view_left = 1, N.s0 = 40, N.bonnie.loc = P_LRC, create(O_BHIDE);
+ if (back && N.s0 == 10 && !N.flash && !N.shut) N.s0 = 11, set_anim(O_PEEKL, AN_PEEKL_14), back = false;
+ if (over(O_PEEKL, AN_PEEKL_14) && N.s0 == 11) create(O_CARPET), destroy(O_PEEKL), N.s0 = 12, N.what_side = 2;
+ for (int side = 0; side < 2; side++) { /* 36 to 41: back in the bedroom, from the left door then the right */
+ uint8_t from = side ? 19 : 12;
+ if (!over(O_CARPET, AN_CARPET) || N.s0 != from) continue;
+ if (N.foxy_got_you) {
+ if (!N.gameover) destroy(O_CARPET), N.foxy_s5 = 2, N.s0 = 39, create(O_JUMP), N.gameover = 1;
+ } else if (N.foxy_s5 != 1) {
+ N.s0 = 13, destroy(O_CARPET), N.ob[O_ROOM].vis = 1, set_anim(O_ROOM, AN_ROOM_19), N.fredcheck = 1;
+ } else {
+ N.s0 = 37, destroy(O_CARPET), N.foxy_s5 = 2, create(O_CREAK);
+ heard("The closet creaks");
+ }
+ }
+ if (over(O_CARPET, AN_CARPET) && N.s0 == 31) { /* 42, 43: back from the closet */
+ if (N.foxy_got_you) {
+ if (!N.gameover) destroy(O_CARPET), create(O_JUMP), N.s0 = 39, N.foxy_s5 = 2, N.gameover = 1;
+ } else
+ destroy(O_CARPET), N.s0 = 0, N.ob[O_ROOM].vis = 1, set_anim(O_ROOM, AN_ROOM_19), N.fredcheck = 1, N.x = 500;
+ }
+ if (over(O_ROOM, AN_ROOM_19) && N.s0 == 13) N.s0 = 0, set_anim(O_ROOM, AN_ROOM_0), N.x = 750, N.ob[O_ROOM].vis = 1;
+ if (N.x < 400) N.x = 400; /* 46 */
+ if (N.x > 600) N.x = 600;
+ if (N.s0 == 12 || N.s0 == 13) N.x = 750;
+ if (over(O_CREAK, AN_CREAK) && N.s0 == 37) set_anim(O_ROOM, AN_ROOM_0), N.ob[O_ROOM].vis = 1, N.s0 = 0, destroy(O_CREAK);
+ if (N.s0 == 13 && edge(0)) N.s3 = 0; /* 51 */
+ if (N.s0 == 13) N.s3++;
+ if (N.s0 == 13 && N.s3 > 10) set_anim(O_ROOM, AN_ROOM_0), N.ob[O_ROOM].vis = 1;
+ if (playing(O_ROOM, AN_ROOM_19)) N.s3 = 0;
+ /* the right door (55 to 77) */
+ if (over(O_RSTART, AN_RSTART) && N.s0 == 16) N.s0 = 17, create(O_PEEKR), destroy(O_RSTART);
+ if (N.s0 == 17 && !N.flash) set_anim(O_PEEKR, AN_PEEKR_12);
+ if (N.s0 == 17 && N.foxy != P_RHF && N.chica.loc != P_RHF && N.fred != P_RHF && N.flash)
+ set_anim(O_PEEKR, AN_PEEKR_14), N.view_right = 1;
+ if (N.s0 == 17 && N.fred == P_RHF && N.kitchen3 <= 1 && !N.shadow && N.flash) set_anim(O_PEEKR, AN_PEEKR_19), N.view_right = 1;
+ if (N.s0 == 17 && N.fred == P_RHF && N.kitchen3 > 1 && !N.shadow && N.flash) set_anim(O_PEEKR, AN_PEEKR_20), N.view_right = 1;
+ if (N.s0 == 17 && N.fred == P_RHF && N.shadow && N.flash) set_anim(O_PEEKR, AN_PEEKR_21), N.view_right = 1;
+ if (N.s0 == 17 && N.foxy == P_RHF && N.chica.loc != P_RHF && N.flash)
+ set_anim(O_PEEKR, AN_PEEKR_18), N.view_right = 1, N.s0 = 36, N.foxy = P_LRC;
+ if (N.s0 == 17 && N.chica.loc == P_RHF && N.flash)
+ N.view_right = 1, N.s0 = 41, N.chica.loc = P_LRC, create(O_CHIDE);
+ if (back && N.s0 == 17 && !N.flash && !N.shut) N.s0 = 18, set_anim(O_PEEKR, AN_PEEKR_13), back = false;
+ if (over(O_PEEKR, AN_PEEKR_13) && N.s0 == 18) create(O_CARPET), N.s0 = 19, destroy(O_PEEKR), N.what_side = 4;
+ if (N.s0 == 0 && edge(1)) N.what_side = 3; /* 65 */
+ if (N.s0 == 10 && N.shut) N.s0 = 20, set_anim(O_PEEKL, AN_PEEKL_15); /* 70 */
+ if (over(O_PEEKL, AN_PEEKL_15) && N.s0 == 20) N.s0 = 21, set_anim(O_PEEKL, AN_PEEKL_16);
+ if (N.s0 == 21 && !N.shut) N.s0 = 22, set_anim(O_PEEKL, AN_PEEKL_17);
+ if (over(O_PEEKL, AN_PEEKL_17) && N.s0 == 22) N.s0 = 10, set_anim(O_PEEKL, AN_PEEKL_12);
+ if (N.s0 == 17 && N.shut) N.s0 = 23, set_anim(O_PEEKR, AN_PEEKR_15);
+ if (over(O_PEEKR, AN_PEEKR_15) && N.s0 == 23) N.s0 = 24, set_anim(O_PEEKR, AN_PEEKR_16);
+ if (N.s0 == 24 && !N.shut) N.s0 = 25, set_anim(O_PEEKR, AN_PEEKR_17);
+ if (over(O_PEEKR, AN_PEEKR_17) && N.s0 == 25) N.s0 = 17, set_anim(O_PEEKR, AN_PEEKR_12);
+ /* the closet (78 to 98) */
+ if (ok && N.s0 == 0) N.s0 = 26, create(O_DARKC);
+ if (over(O_DARKC, AN_DARKC) && N.s0 == 26) create(O_CARPET), N.ob[O_ROOM].vis = 0, N.s0 = 27, destroy(O_DARKC);
+ if (over(O_CARPET, AN_CARPET) && N.s0 == 27) N.s0 = 28, destroy(O_CARPET), create(O_CLOSET);
+ if (over(O_CLOSET, AN_CLOSET_0) && N.s0 == 28) N.s0 = 29, set_anim(O_CLOSET, AN_CLOSET_12);
+ if (N.s0 == 29 && N.foxy != P_CLOSET && N.flash) set_anim(O_CLOSET, AN_CLOSET_13);
+ if (N.s0 == 29 && N.foxy == P_CLOSET && N.flash) {
+ static const uint8_t by_stage[4] = {AN_CLOSET_21, AN_CLOSET_18, AN_CLOSET_19, AN_CLOSET_20};
+ set_anim(O_CLOSET, by_stage[N.foxy_s3 & 3]);
+ }
+ if (N.s0 == 29 && N.fred == P_CLOSET && N.flash) set_anim(O_CLOSET, N.shadow ? AN_CLOSET_23 : AN_CLOSET_22);
+ if (N.s0 == 29 && !N.flash) set_anim(O_CLOSET, AN_CLOSET_12);
+ if (back && N.s0 == 29 && !N.flash && !N.shut) N.s0 = 30, set_anim(O_CLOSET, AN_CLOSET_14), back = false;
+ if (over(O_CLOSET, AN_CLOSET_14) && N.s0 == 30) destroy(O_CLOSET), create(O_CARPET), N.s0 = 31;
+ if (N.s0 == 29 && N.shut && edge(2)) N.s0 = 32, set_anim(O_CLOSET, AN_CLOSET_15);
+ if (over(O_CLOSET, AN_CLOSET_15) && N.s0 == 32) N.s0 = 33, set_anim(O_CLOSET, AN_CLOSET_17);
+ if (N.s0 == 33 && !N.shut) N.s0 = 34, set_anim(O_CLOSET, AN_CLOSET_16);
+ if (over(O_CLOSET, AN_CLOSET_16) && N.s0 == 34) N.s0 = 29, set_anim(O_CLOSET, AN_CLOSET_12);
+ /* the bed (198 to 213) */
+ if (back && (N.s0 == 0 || N.s0 == 2 || N.s0 == 5) && !N.flash && !N.shut) N.s0 = 41, create(O_OFF4), back = false;
+ if (over(O_OFF4, AN_OFF4) && N.s0 == 41) create(O_BED), N.s0 = 42, destroy(O_OFF4);
+ if (over(O_BED, AN_BED_0) && N.s0 == 42) N.s0 = 43, set_anim(O_BED, AN_BED_19);
+ if (back && N.s0 == 43 && !N.flash && !N.shut) N.s0 = 44, set_anim(O_BED, AN_BED_20);
+}
+
+/* Foxy (103 to 138) */
+static void foxy(void) {
+ if (every(T_SECOND, 1000)) {
+ N.foxy_s0 = (uint8_t)(rnd_n(10) + 1), N.bonnie.s0 = (uint8_t)(rnd_n(2) + 1);
+ N.chica.s0 = (uint8_t)(rnd_n(2) + 1), N.fred_s0 = (uint8_t)(rnd_n(2) + 1);
+ }
+ if (N.foxy == P_LRC && N.foxy_s0 <= 5 && N.foxy_s1) N.foxy = P_LRL, N.foxy_s1 = 0, heard("Running, right to left");
+ if (N.foxy == P_LRC && N.foxy_s0 > 5 && N.foxy_s1) N.foxy = P_LRR, N.foxy_s1 = 0, heard("Running, left to right");
+ if (N.foxy == P_LRR && N.foxy_s0 <= 9 && N.foxy_s1) N.foxy = P_LRL, N.foxy_s1 = 0, heard("Running, right to left");
+ if (N.foxy == P_LRR && N.foxy_s0 == 10 && N.foxy_s1 && !N.view_right)
+ N.foxy = P_RHF, N.foxy_s1 = 0, heard("Running, to the right hall");
+ if (N.foxy == P_LRL && N.foxy_s0 == 10 && N.foxy_s1 && !N.view_left)
+ N.foxy = P_LHF, N.foxy_s1 = 0, heard("Running, to the left hall");
+ if (N.foxy == P_LRL && N.foxy_s0 <= 9 && N.foxy_s1) N.foxy = P_LRR, N.foxy_s1 = 0, heard("Running, left to right");
+ if (every(T_FOXY5, 5000) && chance(10, N.ai_foxy)) N.foxy_s1 = 1;
+ if (!N.flash) N.view_left = N.view_right = N.view_closet = 0; /* 117 */
+ if (over(O_PEEKL, AN_PEEKL_18)) N.s0 = 10, set_anim(O_PEEKL, AN_PEEKL_13);
+ if (N.foxy == P_LHF && N.what_side == 5 && edge(3)) heard("Running into the closet"), N.foxy = P_CLOSET;
+ if (N.foxy == P_RHF && N.what_side == 1 && edge(4)) heard("Running into the closet"), N.foxy = P_CLOSET;
+ if (N.foxy == P_CLOSET && edge(5)) N.foxy_s2 = 0;
+ if (N.foxy == P_CLOSET && N.foxy_s1 && !N.view_closet) N.foxy_s2++, N.foxy_s1 = 0;
+ if (N.s0 == 29 && N.flash) N.view_closet = 1;
+ if (N.s0 == 33 && N.foxy == P_CLOSET && every(T_FOXY1, 1000) && N.foxy_s2) N.foxy_s2--; /* (129: not below 0) */
+ if (N.foxy_s2 > 10) N.foxy_s2 = 10;
+ N.foxy_s3 = N.foxy_s2 < 2 ? 0 : N.foxy_s2 < 4 ? 1 : N.foxy_s2 < 6 ? 2 : 3; /* 131 to 134 */
+ if (over(O_PEEKR, AN_PEEKR_18) && N.s0 == 36) N.s0 = 17, set_anim(O_PEEKR, AN_PEEKR_14);
+ if (N.foxy == P_CLOSET && once(0)) N.foxy_s5 = 1, N.foxy_s2 = (uint8_t)(3 + rnd_n(5));
+ N.foxy_got_you = N.foxy_s2 >= 10;
+}
+
+/* Bonnie and Chica (139 to 197) */
+static void steps(int side, bool soft) {
+ static const char *const s[4] = {"Footsteps, left", "Footsteps, right", "Soft steps, left", "Soft steps, right"};
+ heard(s[side + 2 * soft]);
+}
+
+static void bonnie_chica(void) {
+ if (every(T_BONNIE5, 5000) && chance(20, N.ai_bonnie) && N.listening != 1 && N.door_lock != 2 && !N.left_shut)
+ N.bonnie.s1 = 1;
+ if (every(T_CHICA5, 5000) && chance(20, N.ai_chica) && N.listening != 2 && N.door_lock != 2 && !N.right_shut)
+ N.chica.s1 = 1;
+ bool fred_free = N.fred != P_CLOSET && N.fred != P_BED && N.fred != P_LHF && N.fred != P_RHF;
+ if (every(T_FRED3, 3000) && !N.shadow && chance(20, N.ai_fredbear) && fred_free) N.fred_s1 = 1;
+ if (every(T_FRED2, 2000) && N.shadow && chance(20, N.ai_fredbear) && fred_free) N.fred_s1 = 1;
+ if (N.listening == 1) N.bonnie.s1 = 0;
+ if (N.door_lock == 1) N.bonnie.s1 = N.chica.s1 = 0;
+ if (N.listening == 2) N.chica.s1 = 0;
+ Anim *b = &N.bonnie, *c = &N.chica;
+ if (b->s1 && b->loc == P_LRC) moved(b, P_LRL), steps(0, true);
+ if (b->loc == P_LRL && b->s1 && b->s0 == 1) moved(b, P_LRC), steps(0, true);
+ if (b->loc == P_LRL && b->s1 && b->s0 == 2 && !N.view_left) moved(b, P_LHF), steps(0, false);
+ if (b->s1 && b->loc == P_LHF) moved(b, P_LHN), steps(0, false);
+ if (every(T_BONNIE10, 10000) && b->s1 && b->loc == P_LHN && N.listening != 1) moved(b, P_LHF), steps(0, false);
+ if (c->s1 && c->loc == P_LRC) moved(c, P_LRR), steps(1, true);
+ if (c->s1 && c->loc == P_KITCHEN) moved(c, P_LRR), steps(1, true);
+ if (c->s1 && c->loc == P_LRR && c->s0 == 1) moved(c, P_KITCHEN), steps(1, true);
+ if (c->s1 && c->loc == P_LRR && c->s0 == 2 && !N.view_right) moved(c, P_RHF), steps(1, false);
+ if (c->s1 && c->loc == P_RHF) moved(c, P_RHN), steps(1, false);
+ if (every(T_CHICA10, 10000) && c->s1 && c->loc == P_RHN && N.listening != 2) moved(c, P_RHF), steps(1, false);
+ if (over(O_BHIDE, AN_BHIDE) && N.s0 == 40) N.s0 = 10, set_anim(O_PEEKL, AN_PEEKL_13), destroy(O_BHIDE);
+ if (N.s0 == 40 && N.foxy == P_LHF) N.foxy = P_LRC;
+ if (over(O_CHIDE, AN_CHIDE) && N.s0 == 41) N.s0 = 17, set_anim(O_PEEKR, AN_PEEKR_14), destroy(O_CHIDE);
+ if (N.s0 != 10 && N.s0 != 17) N.listening = 0; /* 174 */
+ if (N.flash || N.shut) N.listening = 0;
+ if (N.s0 == 10 && !N.flash && !N.shut) N.listening = 1;
+ if (N.s0 == 17 && !N.flash && !N.shut) N.listening = 2;
+ if (N.listening == 1 && b->loc == P_LHN) g.hold = "Breathing"; /* 180, 181 */
+ if (N.listening == 2 && c->loc == P_RHN) g.hold = "Breathing";
+ N.left_shut = N.s0 == 21, N.right_shut = N.s0 == 24; /* 182 to 185 */
+ if (b->s5 == 1 && N.left_shut && !N.door_lock) b->loc = P_LHN, N.door_lock = 1;
+ if (every(T_BONNIE3, 3000) && b->s5 == 2 && N.left_shut && !N.door_lock && b->loc == P_LHN)
+ b->loc = P_LRL, steps(0, false), b->s1 = 0, N.door_lock = 2;
+ if (c->s5 == 1 && N.right_shut && !N.door_lock) c->loc = P_RHN, N.door_lock = 1;
+ if (every(T_CHICA3, 3000) && c->s5 == 2 && N.right_shut && !N.door_lock && c->loc == P_RHN)
+ c->loc = P_LRR, steps(1, false), c->s1 = 0, N.door_lock = 2;
+ if (b->loc == P_LHN && N.view_left && !N.got_you && !N.gameover) /* 190 */
+ N.got_you = 1, create(O_JUMP), set_anim(O_JUMP, AN_JUMP_13), N.gameover = 1;
+ if (c->loc == P_RHN && N.view_right && !N.got_you && !N.gameover)
+ c->loc = P_LRR, N.got_you = 2, create(O_JUMP), set_anim(O_JUMP, AN_JUMP_12), N.gameover = 1;
+ if (N.gameover && edge(6)) N.s0 = 99;
+ if (!N.right_shut && !N.left_shut) N.door_lock = 0; /* 197 */
+}
+
+/* the bed and the Freddles (204 to 246) */
+static void bed(void) {
+ if (over(O_BED, AN_BED_20) && N.s0 == 44) {
+ if (!N.chica.s7 && !N.bonnie.s7) N.s0 = 45, destroy(O_BED), create(O_ON4), N.fredcheck = 1;
+ else if (N.chica.s7 && !N.gameover) destroy(O_BED), create(O_CUPCAKE), N.gameover = 1;
+ else if (N.bonnie.s7 && !N.gameover) destroy(O_BED), N.gameover = 1, create(O_BONNIEATK);
+ }
+ if (over(O_ON4, AN_ON4) && N.s0 == 45) set_anim(O_ROOM, AN_ROOM_0), N.s0 = 0, N.ob[O_ROOM].vis = 1, destroy(O_ON4);
+ if (N.s0 == 43 && !N.flash) set_anim(O_BED, AN_BED_19), N.view_bed = 0;
+ if (N.s0 == 43 && N.flash) N.view_bed = 1;
+ if (every(T_FREDDY4, 4000) && !N.view_bed) N.freddy += N.ai_freddy; /* 216 */
+ if (N.freddy < 0) N.freddy = 0;
+ if (N.s0 != 43) N.view_bed = 0;
+ if (N.view_bed && every(T_FREDDY50, 50)) N.freddy--;
+ if (N.view_bed) {
+ int an = -1;
+ if (N.freddy <= 10) an = N.random >= 4 ? AN_BED_18 : N.random == 1 ? AN_BED_23 : N.random == 2 ? AN_BED_24 : AN_BED_25;
+ if (N.freddy > 10 && N.freddy <= 20) an = AN_BED_16, N.random = 4;
+ if (N.freddy > 20 && N.freddy <= 30) an = AN_BED_14, N.random = 4;
+ if (N.freddy > 30) an = AN_BED_12, N.random = 4;
+ if (N.fred == P_BED) an = N.shadow ? AN_BED_22 : AN_BED_21;
+ set_anim(O_BED, an);
+ }
+ if (N.view_bed && N.freddy == 30 && edge(7)) create(O_LEAVE3);
+ if (N.view_bed && N.freddy == 20 && edge(8)) create(O_LEAVE2);
+ if (N.view_bed && N.freddy == 10 && edge(9)) create(O_LEAVE1);
+ if (over(O_LEAVE3, AN_LEAVE3)) destroy(O_LEAVE3);
+ if (over(O_LEAVE2, AN_LEAVE2)) destroy(O_LEAVE2);
+ if (over(O_LEAVE1, AN_LEAVE1)) destroy(O_LEAVE1);
+ if (N.s0 == 43 && N.view_bed && N.freddy >= 60 && !N.gameover)
+ N.gameover = 1, create(O_JUMP), set_anim(O_JUMP, AN_JUMP_14);
+ if (every(T_FREDDY3, 3000) && N.s0 == 43 && !N.view_bed && N.freddy >= 60 && !N.gameover)
+ N.gameover = 1, create(O_JUMP), set_anim(O_JUMP, AN_JUMP_14);
+ if (N.s0 == 29 && N.foxy == P_CLOSET && N.foxy_s3 == 3 && N.flash && once(1)) create(O_BITE);
+ if (over(O_BITE, AN_BITE)) destroy(O_BITE);
+ if (over(O_BED, AN_BED_20) && (N.foxy_got_you || N.bed_foxy) && !N.gameover) /* 245 */
+ N.gameover = 1, N.foxy_s5 = 2, N.s0 = 39, create(O_JUMP);
+ if (N.s0 == 43 && !N.gameover && N.foxy_got_you) N.force_turn = 1;
+}
+
+/* the dark that flickers in as they come closer, and the black before a scare (247 to 278) */
+static void attack(int o) {
+ static const uint8_t gone[] = {O_OFF4, O_ON4, O_CREAK, O_BHIDE, O_CHIDE, O_DARKC, O_DARKR, O_DARKL, O_LSTART,
+ O_RSTART, O_CARPET, O_PEEKL, O_PEEKR, O_CLOSET, O_BED};
+ N.gameover = 1;
+ for (unsigned i = 0; i < sizeof gone; i++) destroy(gone[i]);
+ N.flash_vis = 0, N.bf3 = 0;
+ create(o);
+}
+
+static void danger(void) {
+ if (N.bf0 > 0) N.bf1++, N.bf0--;
+ if (N.bf1 > 10) N.bf1 = 0;
+ if (!N.bf1) N.flash_vis = 0;
+ if (N.bf1 > 0) N.flash_vis = 1, N.bf_alpha = (int16_t)(rnd_n(50) + 175 - N.bf1 * 15 - N.bf2);
+ if (!N.bf0) N.bf1 = 0;
+ uint8_t bd = N.bonnie.loc == P_LHF ? 1 : N.bonnie.loc == P_LHN ? 2 : 0;
+ if (!bd) N.bonnie.s6 = N.bonnie.s7 = 0; /* 254 */
+ uint8_t cd = N.chica.loc == P_RHF ? 1 : N.chica.loc == P_RHN ? 2 : 0;
+ uint8_t fd = N.foxy == P_CLOSET ? 2 : 0;
+ uint8_t fr = N.freddy < 20 ? 0 : N.freddy < 30 ? 1 : N.freddy < 50 ? 3 : 5;
+ if (N.freddy >= 30 && N.freddy < 50) N.bf2 = 50;
+ if (every(T_DANGER, 200)) N.total = (uint8_t)(bd + cd + fd + fr);
+ if (N.total == 2 && every(T_D2, 5000) && (int)rnd_n(10) < N.total) N.bf0 = (int16_t)(rnd_n(5) + 5);
+ if (N.total == 3 && every(T_D3, 4000) && (int)rnd_n(10) < N.total) N.bf0 = (int16_t)(rnd_n(10) + 10);
+ if (N.total == 4 && every(T_D4, 3000) && (int)rnd_n(10) < N.total) N.bf0 = (int16_t)(rnd_n(10) + 10);
+ if (N.total >= 5 && every(T_D5, 2000) && (int)rnd_n(10) < N.total) N.bf0 = (int16_t)(rnd_n(30) + 10);
+ if (N.gameover) N.flash_vis = 0; /* 268 */
+ if (N.freddy >= 50) N.bf2 = 100;
+ if (N.freddy < 30) N.bf2 = 0;
+ if (N.freddy >= 80 && edge(10)) N.bf3 = (int16_t)(50 + rnd_n(100));
+ if (N.freddy < 80 && !N.ai_fredbear) N.bf3 = 0;
+ if (N.gameover) N.bf3 = 0;
+ if (N.bf3 > 0) N.bf0 = 10, N.bf3--;
+ if (N.bf3 == 1 && !N.gameover && !N.ai_fredbear && edge(11)) attack(O_FREDDYATK);
+ if (N.bf3 == 1 && !N.gameover && N.ai_fredbear && edge(12)) attack(O_FREDBEAR);
+ if (N.bf3 > 0 && N.bf3 < 30) N.bf_alpha = 0, N.flash_vis = 1;
+}
+
+/* who comes on: their AI over 0 puts them in the living room, 0 takes them away (279 to 296) */
+static void comings(void) {
+ if (N.ai_bonnie && edge(13)) N.bonnie.loc = P_LRC;
+ if (!N.ai_bonnie) N.bonnie.loc = P_AWAY;
+ if (N.ai_chica && edge(14)) N.chica.loc = P_LRC;
+ if (!N.ai_chica) N.chica.loc = P_AWAY;
+ if (N.ai_foxy && edge(15)) N.foxy = P_LRC;
+ if (!N.ai_foxy) N.foxy = P_AWAY;
+ Anim *b = &N.bonnie, *c = &N.chica;
+ if (c->loc != P_RHN && c->loc != P_RHF && c->s6 < 20) c->s6 = 0;
+ if (c->loc == P_RHN && every(T_CHICA_S6, 1000)) c->s6++;
+ if (c->s6 >= 20 - N.night && N.view_bed) c->s7 = 1;
+ if (N.view_right) c->s6 = 0;
+ if (b->loc == P_LHN && every(T_BONNIE_S6, 1000)) b->s6++;
+ if (N.view_left) b->s6 = b->s7 = 0;
+ if (b->s6 > 20 - N.night && N.view_bed) b->s7 = 1;
+ if (c->loc == P_KITCHEN) g.hold = N.listening == 2 ? "Pots and pans, close" : "Pots and pans";
+}
+
+/* Fredbear, and Nightmare (297 to 365) */
+static void fredbear(void) {
+ if (N.ai_fredbear && edge(16)) N.fred = P_LRC;
+ if (N.fred == P_LRC && N.fred_s1 && N.fred_s0 == 1) N.fred_s1 = 0, N.fred = P_LRL, heard("Running, right to left");
+ if (N.fred == P_LRC && N.fred_s1 && N.fred_s0 == 2) N.fred_s1 = 0, N.fred = P_LRR, heard("Running, left to right");
+ if (N.fred == P_LRL && N.fred_s1 && N.fred_s0 == 1 && !N.view_left) N.fred_s1 = 0, N.fred = P_LHF;
+ if (N.fred == P_LRL && N.fred_s1 && N.fred_s0 == 2) N.fred_s1 = 0, N.fred = P_LRR, heard("Running, left to right");
+ if (N.fred == P_LRR && N.fred_s1 && N.fred_s0 == 1) N.fred_s1 = 0, N.fred = P_LRL, heard("Running, right to left");
+ if (N.fred == P_LRR && N.fred_s1 && N.fred_s0 == 2 && !N.view_right) N.fred_s1 = 0, N.fred = P_RHF;
+ if (N.s0 == 10 && N.view_left && !N.kitchen2 && edge(17)) N.kitchen2++, N.kitchen4 = 1; /* 305 */
+ if (N.s0 == 10 && !N.view_left && N.kitchen2 == 1 && N.kitchen4 == 1 && edge(18)) N.kitchen2++;
+ if (N.s0 == 17 && N.view_right && !N.kitchen3 && edge(19)) N.kitchen3++, N.kitchen4 = 1;
+ if (N.s0 == 17 && !N.view_right && N.kitchen3 == 1 && N.kitchen4 == 1 && edge(20)) N.kitchen3++;
+ if (every(T_FRED_L3, 3000) && N.fred == P_LHF && N.left_shut) N.fred = P_LRR, heard("Running, left to right");
+ if (every(T_FRED_R3, 3000) && N.fred == P_RHF && N.right_shut) N.fred = P_LRL, heard("Running, right to left");
+ if (N.fred != P_LHF && edge(21)) N.fred_s4 = 0;
+ if (N.fred != P_RHF && edge(22)) N.fred_s5 = 0;
+ if (N.fred == P_LHF && every(T_FRED_S4, 1000)) N.fred_s4++;
+ if (N.fred == P_RHF && every(T_FRED_S5, 1000)) N.fred_s5++;
+ if (N.fred_s4 >= 10 && N.listening == 2) N.fred = N.fred_s0 == 1 ? P_CLOSET : N.fred_s0 == 2 ? P_BED : N.fred;
+ if (N.fred_s5 >= 10 && N.listening == 1) N.fred = N.fred_s0 == 1 ? P_CLOSET : N.fred_s0 == 2 ? P_BED : N.fred;
+ if (N.fred == P_LHF && edge(23)) N.fred_s8 = 0;
+ if (N.fred == P_RHF && edge(24)) N.fred_s9 = 0;
+ if (N.fred == P_LHF && N.view_left && N.fred_s8 < 255) N.fred_s8++;
+ if (N.fred == P_RHF && N.view_right && N.fred_s9 < 255) N.fred_s9++;
+ int stare = N.night == 5 ? 30 : N.night == 6 ? 25 : N.night >= 7 ? 20 : 255; /* 328 to 333 */
+ if (N.fred_s8 > stare && edge(25)) N.bf3 = 50;
+ if (N.fred_s9 > stare && edge(26)) N.bf3 = 50;
+ if (every(T_CLOSET_L, 3000) && N.fred == P_CLOSET && N.s0 == 33 && N.fred_s0 == 1)
+ N.fred = P_LRL, heard("Running, right to left");
+ if (every(T_CLOSET_R, 3000) && N.fred == P_CLOSET && N.s0 == 33 && N.fred_s0 == 2)
+ N.fred = P_LRR, heard("Running, left to right");
+ if (N.fred == P_BED && edge(27)) N.fred_s7 = 0;
+ if (every(T_FRED_S7, 1000) && N.fred == P_BED && N.view_bed) N.fred_s7++;
+ if (N.fred == P_BED && N.fred_s7 > 1 && (N.fred_s0 == 1 || N.fred_s0 == 2)) { /* 338, 339 */
+ heard(N.fred_s0 == 1 ? "Running, right to left" : "Running, left to right");
+ N.fred = N.fred_s0 == 1 ? P_LRL : P_LRR;
+ N.bf6 = 20, N.flash_vis = 1, N.bf_alpha = 0, N.bf18 = 5;
+ }
+ if (N.bf6 > 0) N.bf_alpha = (int16_t)rnd_n(50), N.bf6--, N.flash_vis = 1;
+ if (N.bf18 > 0) N.bf18--, N.flash_vis = 1, N.bf_alpha = 0;
+ if (N.ai_fredbear && N.fred != P_BED && every(T_LAUGH, 10000) && rnd_n(10) == 1) heard("Laughing");
+ if (N.fred != P_BED && edge(28)) N.fred_s6 = 0;
+ if (N.fred != P_CLOSET && edge(29)) N.fred_s6 = 0;
+ if (N.fred == P_BED && every(T_FRED_S6B, 1000)) N.fred_s6++;
+ if (N.fred == P_CLOSET && every(T_FRED_S6C, 1000)) N.fred_s6++;
+ if (N.fredcheck && N.fred_s6 >= 10 && !N.gameover) N.gameover = 1, create(O_FREDBEAR);
+ if (N.fredcheck && N.fred_s6 < 10) N.fredcheck = 0;
+ if (N.fred_s6 >= 20 - N.shadow * 10 && edge(30)) N.bf3 = 50;
+ if (N.fred_s12 >= 25 && edge(31)) N.bf3 = 50;
+ if (N.gameover && edge(32)) { /* 363 */
+ static const uint8_t gone[] = {O_CARPET, O_PEEKL, O_PEEKR, O_CLOSET, O_BED, O_OFF4, O_ON4, O_CREAK, O_BHIDE,
+ O_DARKC, O_CHIDE, O_DARKR, O_DARKL, O_LSTART, O_RSTART, O_LEAVE3, O_LEAVE2,
+ O_LEAVE1, O_BITE};
+ for (unsigned i = 0; i < sizeof gone; i++) destroy(gone[i]);
+ }
+ if (N.ai_fredbear && every(T_FRED_S12, 1000) && N.fred_s12 < 255) N.fred_s12++;
+ if (alive(O_CARPET) && edge(33)) N.fred_s12 = N.fred_s13 = N.fred_s14 = 0;
+}
+
+/* the hours and who is on (366 to 392) */
+static void hours(void) {
+ if (every(T_HOUR, 60000)) N.hour++;
+ if (N.hour > 12) N.hour = 1;
+ if (N.fade < 255) N.fade = (int16_t)(N.fade + 5);
+ int n = N.night, h = N.hour;
+ if (n == 1 && h == 2 && edge(34)) N.ai_bonnie = 1, N.ai_chica = 1, N.ai_freddy = 1;
+ if (n == 1 && h == 3 && edge(35)) N.ai_bonnie += 2, N.ai_chica += 1, N.ai_freddy += 1;
+ if (n == 2 && edge(36)) N.ai_bonnie = 5, N.ai_chica = 5, N.ai_freddy = 2, N.ai_foxy = 1;
+ if (n == 2 && h == 3 && edge(37)) N.ai_freddy += 1, N.ai_bonnie += 2, N.ai_chica += 2, N.ai_foxy += 3;
+ if (n == 3 && edge(38)) N.ai_foxy = 10, N.ai_freddy = 3, N.ai_bonnie = 7, N.ai_chica = 7;
+ if (n == 3 && h == 3 && edge(39)) N.ai_bonnie += 3, N.ai_chica += 3;
+ if (n == 4 && edge(40)) N.ai_freddy = 4, N.ai_bonnie = 10, N.ai_foxy = 5, N.ai_chica = 10;
+ if (n == 4 && h == 3 && edge(41)) N.ai_chica += 2, N.ai_bonnie += 2, N.ai_foxy += 5;
+ /* 379 (only at the bed: in the game a turn forced while you are elsewhere leaves you stuck) */
+ if (N.force_turn && (N.s0 == 43 || N.s0 == 44)) set_anim(O_BED, AN_BED_20), N.s0 = 44;
+ N.force_turn = 0;
+ if (every(T_TURN_B, 4000) && N.s0 == 43 && N.bonnie.s7) N.force_turn = 1;
+ if (every(T_TURN_C, 4000) && N.s0 == 43 && N.chica.s7) N.force_turn = 1;
+ if (every(T_FRED_S13, 1000) && N.fred_s13 < 255) N.fred_s13++;
+ if (N.fred_s13 >= 30 && !N.view_bed && N.night > 1 && every(T_FREDDY200, 200)) N.freddy++;
+ if (every(T_FRED_S14, 1000) && N.view_bed && N.fred_s14 < 255) N.fred_s14++;
+ if (N.fred_s14 >= 15) N.foxy = P_CLOSET, N.foxy_got_you = 1, N.bed_foxy = 1, N.force_turn = 1; /* 385 */
+ if (g.reward && n < 6 && edge(42)) g.reward = 0, N.hour = 2;
+ if (n == 6 && edge(43)) N.ai_bonnie = 12, N.ai_foxy = 10, N.ai_freddy = 5, N.ai_chica = 12;
+ if (n == 6 && h == 4 && edge(44)) N.ai_bonnie = N.ai_chica = N.ai_foxy = N.ai_freddy = 0, N.ai_fredbear = 15;
+ if (N.shadow == 1 && edge(45))
+ N.ai_bonnie = 15, N.ai_fredbear = 0, N.night = 7, N.ai_chica = 15, N.ai_foxy = 15, N.ai_freddy = 6;
+ if (N.shadow == 1 && h == 4 && edge(46)) N.ai_freddy = N.ai_foxy = N.ai_chica = N.ai_bonnie = 0, N.ai_fredbear = 20;
+ if (N.shadow == 2 && edge(45))
+ N.ai_bonnie = 20, N.ai_fredbear = 0, N.night = 8, N.ai_chica = 20, N.ai_foxy = 20, N.ai_freddy = 6;
+ if (N.shadow == 2 && h == 4 && edge(46)) N.ai_freddy = N.ai_foxy = N.ai_chica = N.ai_bonnie = 0, N.ai_fredbear = 20;
+ if (N.s0 == 0 && edge(47)) N.random = (uint8_t)(rnd_n(100) + 1);
+}
+
+static void late(void) {
+ if (N.ai_fredbear) N.freddy = 0; /* 414 */
+ int n = N.night;
+ if (n >= 2 && n <= 4 && once(2)) N.force_bonnie = (uint8_t)(rnd_n(4) + 2), N.force_chica = (uint8_t)(rnd_n(3) + 3);
+ uint8_t h = N.hour == 12 ? 0 : N.hour;
+ if (N.s0 == 0 && N.force_bonnie && N.force_bonnie <= h && !N.got_you && N.hour != 12 && once(3))
+ N.bonnie.loc = P_LHN, N.bonnie.s1 = 0;
+ if (N.s0 == 0 && N.force_chica && N.force_chica <= h && !N.got_you && N.hour != 12 && once(4))
+ N.chica.loc = P_RHN, N.chica.s1 = 0;
+ if (N.bonnie.loc == P_LHF) N.bonnie.s5 = 1; /* 420 to 423 */
+ if (N.bonnie.loc == P_LHN) N.bonnie.s5 = 2;
+ if (N.chica.loc == P_RHF) N.chica.s5 = 1;
+ if (N.chica.loc == P_RHN) N.chica.s5 = 2;
+ if (alive(O_CARPET) && edge(49)) N.kitchen2 = N.kitchen4 = N.kitchen3 = 0;
+ if (n == 5 && once(5)) N.fred_s18 = 4;
+ if ((n == 6 || n == 7) && once(6)) N.fred_s18 = 2;
+ bool free = N.fred != P_CLOSET && N.fred != P_BED;
+ if (N.ai_fredbear && N.fred_s18 && free && N.fred_s0 == 1 && every(T_FRED30A, 30000) && rnd_n(2) == 1)
+ N.fred_s18--, N.fred = P_CLOSET, heard("Laughing");
+ if (N.ai_fredbear && N.fred_s18 && free && N.fred_s0 == 2 && every(T_FRED30B, 30000) && rnd_n(2) == 1)
+ N.fred_s18--, N.fred = P_BED, heard("Laughing");
+ if (N.fred != P_LHF && N.fred != P_RHF) N.fred_s19 = 0; /* 430 to 433 */
+ if (N.fred == P_LHF && every(T_FRED_S19L, 1000)) N.fred_s19++;
+ if (N.fred == P_RHF && every(T_FRED_S19R, 1000)) N.fred_s19++;
+ if (N.fred_s19 >= 20 - n) N.fred_s19 = 0, N.bf3 = 50;
+ if (N.night > 1 || (N.hour > 2 && N.hour != 12)) N.warning = 0; /* 441, 442 */
+}
+
+/* the keys, read at the step's end as the game reads them (443 to 456) */
+static void keys(void) {
+ bool light = N.s0 == 10 || N.s0 == 17 || N.s0 == 29 || N.s0 == 43;
+ bool door = N.s0 == 10 || N.s0 == 17 || N.s0 == 29 || N.s0 == 20 || N.s0 == 21 || N.s0 == 23 || N.s0 == 24 ||
+ N.s0 == 32 || N.s0 == 33;
+ bool up = g.held & (K_UP | K_DIGIT(8));
+ N.shut = door && up;
+ N.flash = light && !up && (g.held & (K_OK | K_EXE | K_DIGIT(5)));
+ if (N.s0 == 0 && edge(50)) N.x = 500; /* 457 */
+}
+
+void night_step(void) {
+ N.frame++;
+ g.hold = NULL;
+ you();
+ if (N.night == 5 && once(7)) N.ai_fredbear = 12; /* 102 */
+ foxy();
+ bonnie_chica();
+ bed();
+ danger();
+ comings();
+ fredbear();
+ hours();
+ late();
+ keys();
+ animate();
+}
+
+const char *night_keys(void) {
+ switch (N.s0) {
+ case 0: return "Left Right look OK closet Down bed";
+ case 2: case 5: return "OK the door Down bed";
+ case 10: case 17: case 20: case 21: case 22: case 23: case 24: case 25: return "OK light Up hold the door Down back";
+ case 29: case 32: case 33: case 34: return "OK light Up hold the closet Down back";
+ case 43: return "OK light Down turn around";
+ }
+ return NULL;
+}
+
+/* ------------------------------------------------------------ Fun with Plushtrap (its frame's 62 events) */
+/* He walks from his chair down the hall to the X, through the rooms on either side; the light stops him, and
+ * sends him back to the chair from the hall's start. Catch him on the X with the light and the next night
+ * starts at 2 AM. */
+#define P g.p
+enum { PL_CHAIR, PL_HALL1, PL_FARL, PL_FARR, PL_HALL2, PL_CLOSEL, PL_CLOSER, PL_HALL3, PL_GOT };
+
+static void plush_anim(int an) {
+ if (P.an == an) return;
+ P.an = (uint8_t)an, P.img = 0, P.cnt = 0, P.plays = ANIMS[an].plays, P.done = 0;
+}
+static bool plush_over(int an) { return P.an == an && P.done; }
+static bool plush_every(int id, int ms) {
+ uint16_t p = (uint16_t)(ms * 60 / 1000);
+ if (!P.every[id]) P.every[id] = p;
+ if (--P.every[id]) return false;
+ P.every[id] = p;
+ return true;
+}
+
+void plush_begin(bool from_extras) {
+ memset(&P, 0, sizeof P);
+ P.an = 0xFF;
+ plush_anim(AN_PLUSH_0);
+ P.from_extras = from_extras;
+ P.random = (uint8_t)(rnd_n(2) + 1); /* 6 */
+ P.aggressive = (uint8_t)rnd_n(3); /* 60 */
+ g.reward = 0; /* 61 */
+ int n = g.n.night; /* 52 to 57 */
+ P.counter = from_extras ? 30 : n <= 1 ? 90 : n == 2 ? 60 : n == 3 ? 45 : 30;
+}
+
+/* returns 1 when caught on the X (GREAT!, then the next night), 2 when lost (TOO BAD.) */
+static int plush_events(void) {
+ bool held = g.held & (K_OK | K_EXE | K_DIGIT(5));
+ if (!held && P.s0 != 99 && P.s0 != 98 && !(P.an == AN_PLUSH_20 && !P.done)) P.light = 0, P.s0 = 0; /* 0 */
+ if (held) P.light = 1;
+ if (plush_every(0, 1000) && !g.reward) P.counter--;
+ if (plush_every(1, 1000)) P.random = (uint8_t)(rnd_n(2) + 1);
+ if (!P.light) P.active = (int16_t)(P.active + 1 + P.aggressive); /* 7 */
+ if (plush_every(2, 2000) && P.active >= 400 + (int)rnd_n(100))
+ P.active = 200, P.move = 1, P.aggressive = (uint8_t)rnd_n(3);
+ static const char *const quick = "Quick steps", *const rl = "Running, right to left", *const lr = "Running, left to right";
+ if (P.loc == PL_CHAIR && P.move) P.move = 0, P.loc = PL_HALL1, caption(quick);
+ if (P.loc == PL_HALL1 && P.move && P.random == 1) P.loc = PL_FARL, P.move = 0, caption(rl);
+ if (P.loc == PL_HALL1 && P.move && P.random == 2) P.loc = PL_FARR, P.move = 0, caption(lr);
+ if (P.loc == PL_FARR && P.move) P.loc = PL_HALL2, P.move = 0, caption(quick);
+ if (P.loc == PL_FARL && P.move) P.loc = PL_HALL2, P.move = 0, caption(quick);
+ if (P.loc == PL_HALL2 && P.move && P.random == 1) P.loc = PL_CLOSEL, P.move = 0, caption(rl);
+ if (P.loc == PL_HALL2 && P.move && P.random == 2) P.loc = PL_CLOSER, P.move = 0, caption(lr);
+ if (P.loc == PL_CLOSEL && P.move) P.loc = PL_HALL3, P.move = 0, caption(lr);
+ if (P.loc == PL_CLOSER && P.move) P.move = 0, P.loc = PL_HALL3, caption(lr);
+ if (P.loc == PL_HALL3 && P.move) P.move = 0, P.loc = PL_GOT, caption(lr);
+ if (P.loc == PL_HALL1 && P.light) P.loc = PL_CHAIR, P.s0 = 2, plush_anim(AN_PLUSH_14), caption(quick); /* 19 */
+ if (P.s0 == 0) plush_anim(AN_PLUSH_0);
+ if (P.s0 == 1 && P.loc == PL_CHAIR) plush_anim(AN_PLUSH_12);
+ if (P.s0 == 1 && P.loc == PL_HALL2) plush_anim(AN_PLUSH_21);
+ if (P.s0 == 1 && P.loc == PL_HALL3) plush_anim(AN_PLUSH_22);
+ if (P.s0 == 1 && P.loc != PL_CHAIR && P.loc != PL_HALL2 && P.loc != PL_HALL3) plush_anim(AN_PLUSH_13);
+ if (plush_over(AN_PLUSH_14) && P.s0 == 2) P.s0 = 1;
+ if (held && P.s0 == 0 && P.active > 200) { /* 26 to 31 */
+ static const uint8_t caught[9] = {0, 0, AN_PLUSH_15, AN_PLUSH_16, AN_PLUSH_19, AN_PLUSH_18, AN_PLUSH_17, AN_PLUSH_20, 0};
+ if (caught[P.loc]) P.s0 = 3, plush_anim(caught[P.loc]);
+ if (P.loc == PL_HALL2 || P.loc == PL_HALL3) caption("A thud");
+ }
+ for (int an = AN_PLUSH_15; an <= AN_PLUSH_19; an++)
+ if (plush_over(an) && P.s0 == 3) P.s0 = 1;
+ if (plush_over(AN_PLUSH_20) && P.s0 == 3) P.s0 = 98, g.reward = 1; /* 37 */
+ if (P.light) P.active = 0; /* 39 */
+ if (held && P.s0 == 0) P.s0 = 1;
+ if (P.loc == PL_HALL3 && !P.light) P.active = (int16_t)(P.active + 5); /* 43 */
+ if (P.loc == PL_GOT && P.light && P.s0 != 99) P.s0 = 99, plush_anim(AN_PLUSH_23);
+ if (plush_over(AN_PLUSH_23)) return 2;
+ if (P.s0 == 98) plush_anim(AN_PLUSH_22), P.s2++;
+ if (P.s2 > 150) return 1;
+ if (P.counter <= 0 && P.s0 != 98) return 2;
+ if (P.loc == PL_HALL3) P.aggressive = 2; /* 59 */
+ return 0;
+}
+
+static int plush_result;
+void plush_step(void) {
+ P.frame++;
+ int r = plush_events();
+ const AnimDef *d = &ANIMS[P.an];
+ if (!P.done && d->speed) {
+ P.cnt = (uint8_t)(P.cnt + d->speed);
+ while (P.cnt >= 100) {
+ P.cnt = (uint8_t)(P.cnt - 100);
+ if (P.img + 1 < d->n) P.img++;
+ else if (P.plays == 1) {
+ P.done = 1;
+ break;
+ } else {
+ if (P.plays) P.plays--;
+ P.img = 0;
+ }
+ }
+ }
+ plush_result = r;
+}
+int plush_done(void) { return plush_result; }
+int plush_pic(void) { return anim_pic(P.an, P.img); }
diff --git a/games/fnaf4/src/pic.c b/games/fnaf4/src/pic.c
new file mode 100644
index 00000000..c11e957f
--- /dev/null
+++ b/games/fnaf4/src/pic.c
@@ -0,0 +1,264 @@
+/* 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 != fnaf4_bin) {
+ for (int k = 0; k < 4; k++) h[k] = huff_tab(k);
+ loaded = fnaf4_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;
+ const uint8_t *table, *base_table; /* base_table: the picture whose squares it shares, or NULL */
+ int count; /* its own squares then */
+} Info;
+
+static Info info(int id) {
+ const uint8_t *p = section(SEC_PICS) + 12 * id, *t = section(SEC_TABLE);
+ Info i = {p[0], p[1], p[2], t + rd32(p + 8), NULL, (int)rd16(p + 6)};
+ uint32_t base = rd16(p + 4);
+ if (base != 0xFFFF) i.base_table = t + rd32(section(SEC_PICS) + 12 * base + 8);
+ 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)[12 * id]; }
+int pic_h(int id) { return 16 * section(SEC_PICS)[12 * id + 1]; }
+
+void pic_part(int id, int x, int y, int sx, int sy, int w, int h) {
+ Info in = info(id);
+ /* clip to the screen, the band and the picture */
+ 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;
+ 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++) {
+ const uint8_t *data = bank + square_at(&in, my * in.mw + mx);
+ 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 (r1 - r0 == 16 && c1 - c0 == 16) { /* all of it shows: straight 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);
+ for (int c = c0; c < c1; c++) *d++ = *s++;
+ }
+ }
+}
+
+void pic_draw(int id, int x, int y) { pic_part(id, x, y, 0, 0, pic_w(id), pic_h(id)); }
diff --git a/games/fnaf4/src/plat.h b/games/fnaf4/src/plat.h
new file mode 100644
index 00000000..d6971ab6
--- /dev/null
+++ b/games/fnaf4/src/plat.h
@@ -0,0 +1,42 @@
+/* Five Nights at Freddy's 4: 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 FNAF4_PLAT_H
+#define FNAF4_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: mute the call */
+ K_0 = 1 << 8, /* the digits: K_0 << n */
+ K_EXE = 1 << 18, /* EXE: the monitor down, the panel's exit */
+ 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/fnaf4/src/plat_eadk.c b/games/fnaf4/src/plat_eadk.c
new file mode 100644
index 00000000..52991778
--- /dev/null
+++ b/games/fnaf4/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/fnaf4/src/plat_host.c b/games/fnaf4/src/plat_host.c
new file mode 100644
index 00000000..f3f5a8c5
--- /dev/null
+++ b/games/fnaf4/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/fnaf4/src/res.h b/games/fnaf4/src/res.h
new file mode 100644
index 00000000..bb2d2906
--- /dev/null
+++ b/games/fnaf4/src/res.h
@@ -0,0 +1,15 @@
+/* Five Nights at Freddy's 4: data.bin (tools/pack.py), read where it lies in flash. */
+#ifndef FNAF4_RES_H
+#define FNAF4_RES_H
+#include <stdint.h>
+#include "data.h"
+
+extern const uint8_t *fnaf4_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 fnaf4_bin + rd32(fnaf4_bin + 8 + 4 * s); }
+#endif
diff --git a/games/fnaf4/src/save.c b/games/fnaf4/src/save.c
new file mode 100644
index 00000000..57397e80
--- /dev/null
+++ b/games/fnaf4/src/save.c
@@ -0,0 +1,174 @@
+/* Saves: the progress (fnaf4.sav: the night reached, the stars), the night as it was when Home quit
+ * (fnaf4res.sav, read once on the next start), and a copy of both 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 SAVE_NAME "fnaf4.sav"
+#define RESUME_NAME "fnaf4res.sav"
+#define COPY_NAME "fnaf4_saves.py"
+#define MAGIC 0x34464E46u /* "FNF4" */
+#define VERSION 1
+
+typedef struct { /* the game's Ini "fn4": night, beat5 to beat8; the extras' 20/20/20/20, Plushtrap's reward */
+ uint32_t magic;
+ uint8_t version, level, beat5, beat6;
+ uint8_t beat7, beat8, twenty, reward;
+} Progress;
+
+typedef struct {
+ uint32_t magic;
+ uint32_t size;
+ Night n;
+} Resume;
+
+static const char *const kept[] = {SAVE_NAME, RESUME_NAME};
+#define NKEPT (int)(sizeof kept / sizeof kept[0])
+static const char copy_head[] = "# Five Nights at Freddy's 4's saves: keep this file\n";
+static const char b64[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
+
+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 || 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]);
+ }
+}
+
+void save_progress(void) {
+ Progress p;
+ memset(&p, 0, sizeof p);
+ p.magic = MAGIC, p.version = VERSION;
+ p.level = g.level, p.beat5 = g.beat5, p.beat6 = g.beat6, p.beat7 = g.beat7, p.beat8 = g.beat8;
+ p.twenty = g.twenty, p.reward = g.reward;
+ plat_save(SAVE_NAME, &p, sizeof p);
+ copy_write();
+}
+
+void save_load(void) {
+ uint32_t len;
+ const uint8_t *d = plat_load(SAVE_NAME, &len);
+ g.level = 1;
+ if (!d || len != sizeof(Progress)) return;
+ Progress p;
+ memcpy(&p, d, sizeof p);
+ if (p.magic != MAGIC || p.version != VERSION) return;
+ g.level = p.level >= 1 && p.level <= 9 ? p.level : 1;
+ g.beat5 = p.beat5 & 1, g.beat6 = p.beat6 & 1, g.beat7 = p.beat7 & 1, g.beat8 = p.beat8 & 1;
+ g.twenty = p.twenty & g.beat7, g.reward = p.reward & 1;
+}
+
+void save_resume(void) {
+ Resume r;
+ memset(&r, 0, sizeof r);
+ r.magic = MAGIC, r.size = sizeof(Night), r.n = g.n;
+ plat_save(RESUME_NAME, &r, sizeof r);
+ copy_write();
+}
+
+/* a kept night that can be played on: every place, state and number in its range */
+static bool night_valid(const Night *n) { /* (a resume file that doesn't hold together is dropped) */
+ if (n->night < 1 || n->night > 8 || n->shadow > 2 || n->hour < 1 || n->hour > 12 || n->hour == 6) return false;
+ if (n->x < 400 || n->x > 750 || n->s0 > 99 || n->gameover) return false;
+ const uint8_t locs[5] = {n->bonnie.loc, n->chica.loc, n->foxy, n->fred, P_AWAY};
+ for (int i = 0; i < 5; i++)
+ if (locs[i] > P_BED) return false;
+ for (int o = 0; o < O_COUNT; o++)
+ if (n->ob[o].alive && (n->ob[o].an >= anim_count() || n->ob[o].img >= anim_len(n->ob[o].an))) return false;
+ if (!n->ob[O_ROOM].alive || night_top() < 0) return false;
+ return true;
+}
+
+bool save_resume_load(void) {
+ uint32_t len;
+ const uint8_t *d = plat_load(RESUME_NAME, &len);
+ if (!d) return false;
+ bool ok = false;
+ if (len == sizeof(Resume)) {
+ Resume r;
+ memcpy(&r, d, sizeof r);
+ if (r.magic == MAGIC && r.size == sizeof(Night)) {
+ Night keep = g.n;
+ g.n = r.n;
+ ok = night_valid(&r.n);
+ if (!ok) g.n = keep;
+ }
+ }
+ plat_remove(RESUME_NAME);
+ copy_write();
+ return ok;
+}
diff --git a/games/fnaf4/src/view.c b/games/fnaf4/src/view.c
new file mode 100644
index 00000000..a938c146
--- /dev/null
+++ b/games/fnaf4/src/view.c
@@ -0,0 +1,51 @@
+/* Five Nights at Freddy's 4: drawing the night. Each of the game's views fills its screen (the bedroom, a door, the
+ * closet, the bed, a scare), so the one made last is the one seen: the bedroom pans with where you look (the game's
+ * 1000-wide room at half size, 320 of it), the others are the middle 640 of the game's 800 at half size. Over them:
+ * the dark flickering in, the night's start from black, the hour, the first night's warning at the doors. */
+#include <stdio.h>
+#include "game.h"
+#include "gfx.h"
+#include "data.h"
+
+#define N g.n
+
+static void draw_ob(int o) {
+ if (ob_wide(o)) {
+ int x = N.x < 400 ? 400 : N.x > 600 ? 600 : N.x;
+ pic_part(ob_pic(o), 0, 0, x / 2 - 160 - BED_X0, 0, SCREEN_W, SCREEN_H);
+ } else
+ pic_draw(ob_pic(o), 0, 0);
+}
+
+static void hud(void) {
+ char t[4];
+ snprintf(t, sizeof t, "%d", N.hour);
+ int w = gfx_img_w(IMG_AM);
+ gfx_text_r(FONT_CLOCK, SCREEN_W - 10 - w, 4, t, WHITE);
+ gfx_img(IMG_AM, SCREEN_W - 6 - w, 11, WHITE);
+}
+
+void view_night(void) {
+ int top = night_top();
+ if (top < 0) gfx_fill(0, 0, SCREEN_W, SCREEN_H, BLACK);
+ else draw_ob(top);
+ bool scare = top >= O_JUMP;
+ if (N.flash_vis && !scare) {
+ int a = 255 - (N.bf_alpha < 0 ? 0 : N.bf_alpha > 255 ? 255 : N.bf_alpha);
+ gfx_dim(0, 0, SCREEN_W, SCREEN_H, a * 32 / 255);
+ }
+ if (N.fade < 255) gfx_dim(0, 0, SCREEN_W, SCREEN_H, (255 - N.fade) * 32 / 255);
+ if (N.warning && (N.s0 == 10 || N.s0 == 17))
+ gfx_img(IMG_WARNING, SCREEN_W / 2 - gfx_img_w(IMG_WARNING) / 2, 54 - gfx_img_h(IMG_WARNING) / 2, RGB(0xB8B8B8));
+ if (!scare) hud();
+}
+
+void view_plush(void) {
+ pic_draw(plush_pic(), 0, 0);
+ if (g.p.s0 == 98) gfx_img(IMG_GREAT, SCREEN_W / 2 - gfx_img_w(IMG_GREAT) / 2, 88, WHITE);
+ if (g.p.frame > 6 && g.p.counter > 0) {
+ char t[8];
+ snprintf(t, sizeof t, "%d", g.p.counter);
+ gfx_text_r(FONT_CLOCK, SCREEN_W - 10, 30, t, WHITE);
+ }
+}
diff --git a/games/fnaf4/tests/pics.c b/games/fnaf4/tests/pics.c
new file mode 100644
index 00000000..9a743f6c
--- /dev/null
+++ b/games/fnaf4/tests/pics.c
@@ -0,0 +1,30 @@
+/* Draws every picture of data.bin on a computer (build/pics/<id>.ppm), to check the codec:
+ * tests/check.py compares them with what tools/pack.py was given. */
+#include <stdio.h>
+#include "../src/gfx.h"
+#include "../src/res.h"
+
+extern const uint8_t fnaf4_data[];
+const uint8_t *fnaf4_bin;
+void host_shot(const char *path);
+
+static int cur, offx;
+static void draw(void) {
+ gfx_fill(0, gfx_y0, SCREEN_W, BAND_H, BLACK);
+ pic_draw(cur, -offx, 0);
+}
+
+int main(int argc, char **argv) {
+ static uint16_t band[SCREEN_W * BAND_H];
+ gfx_set_band_memory(band);
+ fnaf4_bin = fnaf4_data;
+ const char *dir = argc > 1 ? argv[1] : "build/pics";
+ for (cur = 0; cur < PIC_COUNT; cur++)
+ for (offx = 0; offx < pic_w(cur); offx += SCREEN_W) {
+ gfx_frame(draw);
+ char path[256];
+ snprintf(path, sizeof path, "%s/%d_%d.ppm", dir, cur, offx);
+ host_shot(path);
+ }
+ return 0;
+}
diff --git a/games/fnaf4/tests/rules.c b/games/fnaf4/tests/rules.c
new file mode 100644
index 00000000..73808121
--- /dev/null
+++ b/games/fnaf4/tests/rules.c
@@ -0,0 +1,375 @@
+/* Five Nights at Freddy's 4 on a computer (make test, with the sanitizers): the night's rules against the game's
+ * events (gamesrc spec level_events.txt), whole nights played by a bot that listens, holds the doors and lights the
+ * bed, Fun with Plushtrap, random keys on every night, 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 fnaf4_data[];
+const uint8_t *fnaf4_bin;
+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 N g.n
+
+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 night(int n, int shadow) {
+ start_night(n, shadow);
+ while (g.scene == SC_CARD) step(0);
+}
+
+/* to a door (-1 left, 1 right) or the closet (0), or the bed (2): back in the bedroom first */
+static void go_to(int where) {
+ for (int i = 0; i < 400 && N.s0 != 0; i++) step(0);
+ if (where == 2) {
+ tap(K_DOWN);
+ for (int i = 0; i < 200 && N.s0 != 43; i++) step(0);
+ return;
+ }
+ if (where) {
+ uint32_t k = where < 0 ? K_LEFT : K_RIGHT;
+ for (int i = 0; i < 200 && N.s0 != (where < 0 ? 2 : 5); i++) step(k);
+ }
+ tap(K_OK);
+ for (int i = 0; i < 400 && N.s0 != (where < 0 ? 10 : where > 0 ? 17 : 29); i++) step(0);
+}
+static void back(void) {
+ tap(K_DOWN);
+ for (int i = 0; i < 400 && N.s0 != 0; i++) step(0);
+}
+
+static void rules(void) {
+ /* the hours: a minute each, 6 AM after six */
+ night(1, 0);
+ CHECK(N.hour == 12, "12 AM to start");
+ steps(60 * 60, 0);
+ CHECK(N.hour == 1, "1 AM after a minute (%d)", N.hour);
+ CHECK(!N.ai_bonnie && !N.ai_chica && !N.ai_freddy && !N.ai_foxy, "night 1: nobody before 2 AM");
+ steps(60 * 60, 0);
+ CHECK(N.ai_bonnie == 1 && N.ai_chica == 1 && N.ai_freddy == 1, "night 1 at 2 AM: 1, 1, 1");
+ steps(60 * 60, 0);
+ CHECK(N.ai_bonnie == 3 && N.ai_chica == 2 && N.ai_freddy == 2, "night 1 at 3 AM: 3, 2, 2 (%d %d %d)", N.ai_bonnie,
+ N.ai_chica, N.ai_freddy);
+ /* the AIs by night (373 to 392) */
+ static const uint8_t ai[9][5] = {{0}, {0}, {5, 5, 1, 2, 0}, {7, 7, 10, 3, 0}, {10, 10, 5, 4, 0}, {0, 0, 0, 0, 12},
+ {12, 12, 10, 5, 0}, {15, 15, 15, 6, 0}, {20, 20, 20, 6, 0}};
+ for (int n = 2; n <= 8; n++) {
+ night(n <= 6 ? n : 7, n <= 6 ? 0 : n - 6);
+ step(0);
+ uint8_t got[5] = {N.ai_bonnie, N.ai_chica, N.ai_foxy, N.ai_freddy, N.ai_fredbear};
+ CHECK(!memcmp(got, ai[n], 5) && N.night == n, "night %d: AI %d %d %d %d %d", n, got[0], got[1], got[2], got[3], got[4]);
+ }
+ night(6, 0);
+ N.hour = 4;
+ step(0);
+ CHECK(!N.ai_bonnie && !N.ai_chica && !N.ai_foxy && !N.ai_freddy && N.ai_fredbear == 15, "night 6 at 4 AM: Fredbear alone");
+ /* looking: 10 a step, the view turns to a door at the edge */
+ night(1, 0);
+ steps(11, K_LEFT); /* (the first step looks ahead again: 457) */
+ CHECK(N.x == 400, "left: x 400 in 10 steps (%d)", N.x);
+ steps(10, K_LEFT);
+ CHECK(N.s0 == 2, "the view turns to the left door (%d)", N.s0);
+ /* to the door: the dark, the run, the door coming up (15 + 40 + 35 frames) */
+ tap(K_OK);
+ int t = 0;
+ while (N.s0 != 10 && t < 300) step(0), t++;
+ CHECK(N.s0 == 10 && t >= 80 && t <= 100, "to the left door in %d steps", t);
+ step(0);
+ CHECK(N.listening == 1, "at the door with no light: listening");
+ /* breathing when Bonnie stands at the door */
+ N.ai_bonnie = 1;
+ step(0);
+ N.bonnie.loc = P_LHN;
+ step(0);
+ CHECK(g.hold && !strcmp(g.hold, "Breathing"), "breathing");
+ /* the light on her there: she gets you */
+ steps(4, K_OK);
+ CHECK(N.gameover && N.ob[O_JUMP].alive, "the light on Bonnie at the door: the scare");
+ /* the light on her far down the hall sends her away */
+ night(3, 0);
+ go_to(-1);
+ N.bonnie.loc = P_LHF;
+ steps(4, K_OK);
+ CHECK(N.bonnie.loc == P_LRC && !N.gameover, "the light sends Bonnie back (%d)", N.bonnie.loc);
+ steps(60, 0);
+ CHECK(N.s0 == 10, "and you are at the door again (%d)", N.s0);
+ /* the door held on her at it: she leaves in 3 seconds, nobody comes until it opens */
+ N.bonnie.loc = P_LHN, N.bonnie.s5 = 2, N.door_lock = 0;
+ steps(60 * 4, K_UP);
+ CHECK(N.bonnie.loc == P_LRL && N.door_lock == 2, "holding the door: Bonnie goes (%d)", N.bonnie.loc);
+ steps(60, 0);
+ CHECK(N.door_lock == 0, "the door open: they move again");
+ /* Foxy: in the left hall when you are at the right door, he runs into the closet */
+ night(3, 0);
+ go_to(1);
+ N.foxy = P_LHF;
+ step(0);
+ CHECK(N.foxy == P_CLOSET, "Foxy runs into the closet (%d)", N.foxy);
+ /* the closet held shut takes him back a step a second */
+ back();
+ go_to(0);
+ N.ai_foxy = 1, N.foxy = P_CLOSET;
+ step(0);
+ N.foxy_s2 = 8;
+ steps(30, K_UP);
+ int s2 = N.foxy_s2;
+ steps(60 * 3, K_UP);
+ CHECK(s2 - N.foxy_s2 >= 2 && s2 - N.foxy_s2 <= 3, "the closet held: %d to %d in 3 s", s2, N.foxy_s2);
+ /* the Freddles: the AI every 4 s while you don't look, the light takes 20 a second */
+ night(4, 0);
+ N.ai_bonnie = N.ai_chica = N.ai_foxy = 0;
+ N.freddy = 0;
+ steps(60 * 8 + 1, 0);
+ CHECK(N.freddy == 8, "Freddles: 4 in 4 s, twice (%d)", N.freddy);
+ go_to(2);
+ N.freddy = 40;
+ steps(60, K_OK);
+ CHECK(N.freddy >= 19 && N.freddy <= 22, "the light on the bed: 40 to 20 in 1 s (%d)", N.freddy);
+ N.freddy = 70;
+ steps(4, K_OK);
+ CHECK(N.gameover, "70 Freddles while you look: the scare");
+ /* Fredbear on the 5th night */
+ night(5, 0);
+ step(0);
+ CHECK(N.fred == P_LRC, "night 5: Fredbear in the living room (%d)", N.fred);
+ /* 6 AM */
+ night(2, 0);
+ N.hour = 5;
+ N.every[32] = 1;
+ steps(2, 0);
+ CHECK(g.scene == SC_SIX, "6 AM ends the night (%d)", g.scene);
+ CHECK(g.level == 3, "and the next is saved (%d)", g.level);
+}
+
+/* a bot: listens at each door, holds it on breathing or lights the hall, keeps Foxy back and the bed clear */
+typedef struct { int step, t, plan; } Bot;
+static uint32_t bot_keys(Bot *b) {
+ static const int8_t round[6] = {-1, 2, 1, 2, 0, 2};
+ b->t++;
+ if (g.scene != SC_NIGHT) return b->t & 1 ? K_OK : 0;
+ if (b->step == 9) { /* leaving: Down, the light off */
+ if (N.s0 == 10 || N.s0 == 17 || N.s0 == 29 || N.s0 == 43) return b->t & 1 ? K_DOWN : 0;
+ b->step = 0, b->plan++, b->t = 0;
+ }
+ switch (N.s0) {
+ case 0: {
+ int w = round[b->plan % 6];
+ if (b->t < 4) return 0;
+ if (w == 2) return b->t & 1 ? K_DOWN : 0;
+ if (w == 0) return b->t & 1 ? K_OK : 0;
+ return w < 0 ? K_LEFT : K_RIGHT;
+ }
+ case 2: return round[b->plan % 6] < 0 ? (b->t & 1 ? K_OK : 0) : K_RIGHT;
+ case 5: return round[b->plan % 6] > 0 ? (b->t & 1 ? K_OK : 0) : K_LEFT;
+ case 10: case 17: case 20: case 21: case 22: case 23: case 24: case 25: {
+ bool breath = g.hold && !strcmp(g.hold, "Breathing");
+ if (b->step == 0) b->step = 1, b->t = 0;
+ if (b->step == 1) { /* listen */
+ if (breath) b->step = 2, b->t = 0;
+ else if (b->t > 40) b->step = 3, b->t = 0;
+ return 0;
+ }
+ if (b->step == 2) { /* hold it until the steps go */
+ if (b->t < 60 * 4) return K_UP;
+ b->step = 1, b->t = 0;
+ return 0;
+ }
+ if (b->step == 3) { /* the light down the hall */
+ if (b->t < 20) return K_OK;
+ b->step = (N.fred == P_LHF && N.s0 == 10) || (N.fred == P_RHF && N.s0 == 17) ? 5 : 9, b->t = 0;
+ return 0;
+ }
+ if (b->step == 5) { /* Fredbear in the hall: the door held until he goes */
+ if ((N.fred == P_LHF || N.fred == P_RHF) && b->t < 60 * 7) return K_UP;
+ b->step = 9, b->t = 0;
+ return 0;
+ }
+ return 0;
+ }
+ case 29: case 32: case 33: case 34:
+ if (b->step == 0) b->step = 1, b->t = 0;
+ if (b->step == 1) {
+ if (b->t < 12) return K_OK;
+ b->step = (N.foxy == P_CLOSET && N.foxy_s2 >= 2) || N.fred == P_CLOSET ? 2 : 3, b->t = 0;
+ return 0;
+ }
+ if (b->step == 2) {
+ if ((N.foxy == P_CLOSET && N.foxy_s2 > 1 && b->t < 60 * 8) || (N.fred == P_CLOSET && b->t < 60 * 7)) return K_UP;
+ b->step = 9, b->t = 0;
+ return 0;
+ }
+ b->step = 9, b->t = 0;
+ return 0;
+ case 43:
+ if (b->step == 0) b->step = 1, b->t = 0;
+ if (b->t < 6 || (N.freddy > 5 && b->t < 60 * 3) || (N.fred == P_BED && b->t < 60 * 3)) return K_OK;
+ b->step = 9, b->t = 0;
+ return 0;
+ }
+ b->step = 0;
+ return 0;
+}
+
+static void bot_nights(void) {
+ int won[9] = {0}, total = 0;
+ for (int n = 1; n <= 6; n++)
+ for (int s = 0; s < 3; s++) {
+ night(n, 0);
+ Bot b = {0};
+ int t = 0;
+ while (g.scene == SC_NIGHT && t < 60 * 60 * 7) {
+ step(bot_keys(&b)), t++;
+ if (getenv("BOT") && n == atoi(getenv("BOT")) && t % 60 == 0)
+ printf("%3d s0 %2d plan %d step %d freddy %d bonnie %d/%d chica %d/%d foxy %d/%d hold %s\n", t / 60, N.s0, b.plan,
+ b.step, N.freddy, N.bonnie.loc, N.bonnie.s6, N.chica.loc, N.chica.s6, N.foxy, N.foxy_s2, g.hold ? g.hold : "");
+ }
+ if (g.scene == SC_SIX) won[n]++, total++;
+ else if (getenv("BOT")) printf("night %d lost at %d:%02d, scene %d, s0 %d, top %d\n", n, t / 3600, t / 60 % 60, g.scene, N.s0, night_top());
+ }
+ printf("bot: nights won %d %d %d %d %d %d of 3 each\n", won[1], won[2], won[3], won[4], won[5], won[6]);
+ CHECK(won[1] >= 2 && total >= 5, "the bot wins nights (%d)", total);
+}
+
+static void plushtrap(void) {
+ /* the light on him on the X: GREAT!, the next night from 2 AM */
+ g.n.night = 2;
+ plush_begin(false);
+ g.scene = SC_PLUSH;
+ g.p.loc = 7, g.p.active = 300;
+ step(K_OK);
+ CHECK(g.p.s0 == 3, "the light on him on the X: caught (%d)", g.p.s0);
+ int t = 0;
+ while (g.scene == SC_PLUSH && t < 60 * 6) step(K_OK), t++;
+ CHECK(g.reward == 1 && g.scene == SC_CARD, "GREAT!, then the next night (%d)", g.scene);
+ while (g.scene == SC_CARD) step(0);
+ step(0);
+ CHECK(N.hour == 2, "it starts at 2 AM (%d)", N.hour);
+ /* the time running out: TOO BAD. */
+ g.n.night = 4;
+ plush_begin(false);
+ g.scene = SC_PLUSH;
+ CHECK(g.p.counter == 30, "night 4: 30 seconds (%d)", g.p.counter);
+ t = 0;
+ while (g.scene == SC_PLUSH && t < 60 * 40) step(0), t++;
+ CHECK(g.scene == SC_TOOBAD, "too late: TOO BAD. (%d)", g.scene);
+ /* at the hall's start the light sends him to his chair */
+ plush_begin(false);
+ g.scene = SC_PLUSH;
+ g.p.loc = 1;
+ steps(3, K_OK);
+ CHECK(g.p.loc == 0, "back to the chair (%d)", g.p.loc);
+}
+
+static void fuzz(int sessions) {
+ uint32_t r = 7;
+ for (int s = 0; s < sessions; s++) {
+ night(1 + s % 6, s % 7 == 6 ? 1 + s % 2 : 0);
+ for (int f = 0; f < 60 * 120 && g.scene == SC_NIGHT; f++) {
+ r = r * 1103515245u + 12345u;
+ static const uint32_t keys[] = {K_LEFT, K_RIGHT, K_UP, K_DOWN, K_OK, K_EXE, K_OK, K_UP, K_DIGIT(5), 0, 0, 0};
+ uint32_t k = keys[(r >> 16) % 12];
+ if (k == 0 || (r >> 8) % 3) step(0);
+ else steps((int)((r >> 4) % 30), k);
+ }
+ }
+ /* and every scene, for its keys */
+ for (int s = 0; s < 40; s++) {
+ g.scene = SC_TITLE;
+ for (int f = 0; f < 60 * 30; f++) {
+ r = r * 1103515245u + 12345u;
+ static const uint32_t keys[] = {K_LEFT, K_RIGHT, K_UP, K_DOWN, K_OK, K_BACK, 0, 0};
+ uint32_t k = keys[(r >> 16) % 8];
+ step((r >> 8) % 4 ? 0 : k);
+ if (!g.running) g.running = true, g.scene = SC_TITLE;
+ }
+ }
+}
+
+static void saves(void) {
+ night(3, 0);
+ steps(60 * 30, 0);
+ Night keep = g.n;
+ save_resume();
+ memset(&g.n, 0, sizeof g.n);
+ CHECK(save_resume_load() && g.n.night == 3 && g.n.frame == keep.frame && !memcmp(&g.n, &keep, sizeof keep),
+ "the night kept by Home comes back");
+ CHECK(!save_resume_load(), "and only once");
+ g.level = 4, g.beat5 = 1, g.beat6 = 0, g.beat7 = 1;
+ save_progress();
+ g.level = 1, g.beat5 = 0;
+ save_load();
+ CHECK(g.level == 4 && g.beat5 == 1 && g.beat7 == 1, "the progress comes back");
+}
+
+static void shot(const char *dir, const char *name) {
+ char p[256];
+ game_draw();
+ snprintf(p, sizeof p, "%s/%s.ppm", dir, name);
+ host_shot(p);
+}
+
+static void draw_all(const char *dir) {
+ g.scene = SC_TITLE, g.beat5 = 1, g.beat6 = 1;
+ shot(dir, "title");
+ night(3, 0);
+ steps(60, 0);
+ N.hour = 2;
+ shot(dir, "shot");
+ night(5, 0);
+ steps(60, 0);
+ N.hour = 2;
+ go_to(-1);
+ N.fred = P_LHF;
+ steps(3, K_OK);
+ shot(dir, "door");
+ night(3, 0);
+ steps(60, 0);
+ N.hour = 3, N.ai_foxy = 1, N.foxy = P_CLOSET;
+ step(0);
+ N.foxy_s2 = 6;
+ go_to(0);
+ steps(3, K_OK);
+ shot(dir, "closet");
+ night(4, 0);
+ steps(60, 0);
+ N.hour = 4, N.ai_freddy = 0;
+ go_to(2);
+ N.freddy = 35;
+ steps(2, K_OK);
+ shot(dir, "bed");
+ g.n.night = 2;
+ plush_begin(false);
+ g.scene = SC_PLUSH;
+ g.p.loc = 0;
+ steps(8, K_OK);
+ shot(dir, "plushtrap");
+}
+
+int main(int argc, char **argv) {
+ static uint16_t band[SCREEN_W * BAND_H];
+ gfx_set_band_memory(band);
+ fnaf4_bin = fnaf4_data;
+ host_save_dir("build");
+ game_init();
+ if (argc > 2 && !strcmp(argv[1], "shots")) {
+ draw_all(argv[2]);
+ return 0;
+ }
+ rules();
+ plushtrap();
+ bot_nights();
+ fuzz(60);
+ saves();
+ printf("%d checks, %d failed\n", checks, fails);
+ return fails != 0;
+}
diff --git a/games/fnaf4/tools/ccn.py b/games/fnaf4/tools/ccn.py
new file mode 100644
index 00000000..d7db4cbb
--- /dev/null
+++ b/games/fnaf4/tools/ccn.py
@@ -0,0 +1,129 @@
+"""Five Nights at Freddy's 4's Application.cci (Clickteam Fusion, from the game's iOS package): its pictures, its
+objects with their animations, and its frames with the objects in them. Read only; tools/pack.py uses it.
+
+The file is chunks (u16 id, u16 flags, u32 size, the data). The ones read here:
+- 0x6666, the pictures: u16 count, u16 the highest number, then each: u16 its number, u32 format (0: RGBA, 3: RGB with
+ rows padded), u16 width, u16 height, 4 x i16 hot spot and action point, u32 size, zlib data.
+- 0x2229, the objects: u32 count, then each a run of chunks: 0x4444 (u16 its number, i16 kind: 1 backdrop, 2 active,
+ 3 string, 7 counter), 0x4445 (its name, UTF-16), 0x4446 (its properties: an active's animations from the offset
+ at byte 12: 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, 0x3335 the name, 0x3338 the objects placed (u32 count, then 20 bytes
+ each: u16, u16 the object, i32 x, i32 y, 4 x i16)."""
+import struct
+import zlib
+
+from PIL import Image
+
+
+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
+
+
+class App:
+ def __init__(self, path):
+ 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
+ while q < len(bank):
+ h, fmt, w, hh, hx, hy, _, _, size = struct.unpack_from("<HIHHhhhhI", bank, q)
+ self.pics[h] = (fmt, w, hh, q + 22, size, hx, hy)
+ q += 22 + size
+ self.bank = bank
+ self.objects, self.by_name, self.meta = {}, {}, {}
+ 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)
+ elif sid == 0x4445:
+ name = body.decode("utf-16-le").split("\0")[0]
+ elif sid == 0x4446:
+ props = body
+ elif sid == 0x7F7F:
+ break
+ anims, meta = self._anims(props) if head[1] == 2 and props else ({}, {})
+ self.objects[head[0]] = (head[1], name, anims)
+ self.meta[head[0]] = meta
+ self.frames = {}
+ for i, c in top:
+ if i != 0x3333:
+ continue
+ sub = dict(chunks(c))
+ name = sub[0x3335].decode("utf-16-le").split("\0")[0]
+ placed = []
+ x = sub.get(0x3338, b"\0\0\0\0")
+ for k in range(struct.unpack_from("<I", x, 0)[0]):
+ _, obj, px, py = struct.unpack_from("<HHii", x, 4 + 20 * k)
+ placed.append((obj, px, py))
+ self.frames[name] = placed
+
+ @staticmethod
+ def _anims(p):
+ at = struct.unpack_from("<H", p, 12)[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)
+ if dirs[0]:
+ q = at + off + dirs[0]
+ lo, hi, rep, back, n = struct.unpack_from("<BBHHH", p, q)
+ out[a] = list(struct.unpack_from(f"<{n}H", p, q + 8))
+ meta[a] = (hi, rep, back)
+ return out, meta
+
+ def picture(self, h):
+ """a picture by its number, RGBA"""
+ fmt, w, hh, at, size = self.pics[h][:5]
+ raw = zlib.decompress(self.bank[at:at + size])
+ if fmt == 0:
+ return Image.frombytes("RGBA", (w, hh), raw[:w * hh * 4])
+ pitch = len(raw) // hh
+ return Image.frombytes("RGB", (w, hh), b"".join(raw[y * pitch:y * pitch + w * 3] for y in range(hh))).convert("RGBA")
+
+ def hotspot(self, h):
+ """a picture's hot spot: where an object placed at (x, y) has it"""
+ return self.pics[h][5:7]
+
+ def obj(self, name, frame=None):
+ """an object's number by its name (the one placed in that frame when several share it)"""
+ 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]}
+ hits = [h for h in hits if h in placed]
+ assert len(hits) == 1, (name, frame, hits)
+ return hits[0]
+
+ def anim(self, name, a=0, frame=None):
+ """an object's animation: its pictures' numbers"""
+ return self.objects[self.obj(name, frame)][2][a]
+
+ def speed(self, name, a=0, frame=None):
+ """an animation's speed (its pictures advance speed / 100 a frame), how many times it plays (0: for ever)
+ and the picture it loops back to"""
+ return self.meta[self.obj(name, frame)][a]
+
+ def placed(self, name, frame):
+ """where an object is placed in a frame (its first place)"""
+ o = self.obj(name, frame)
+ return next((x, y) for h, x, y in self.frames[frame] if h == o)
diff --git a/games/fnaf4/tools/codec.py b/games/fnaf4/tools/codec.py
new file mode 100644
index 00000000..cd60b260
--- /dev/null
+++ b/games/fnaf4/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/fnaf4/tools/pack.py b/games/fnaf4/tools/pack.py
new file mode 100644
index 00000000..4afbe12c
--- /dev/null
+++ b/games/fnaf4/tools/pack.py
@@ -0,0 +1,515 @@
+#!/usr/bin/env python3
+"""Five Nights at Freddy's 4: its pictures and fonts -> src/data.bin, src/data.h and src/anims.h.
+
+ python3 -I tools/pack.py [CCI] CCI: the game's Application.cci, from its iOS package; by default
+ ~/Documents/Assets/gamesrc/fnaf4/dl/Application.cci
+
+Every picture is the game's own, read from the application by tools/ccn.py, at half size. The bedroom is 1000 x 480
+in the game and pans: here it is 500 x 240, kept from x 32 to 464 (all the calculator's 320 ever shows of it). The
+doors, the closet, the bed and the scares are the game's 800 x 480 screen: here the middle 640 of it, 320 x 240.
+
+data.bin: "FNF4", the number of sections, their offsets, then the sections (SEC_* in data.h):
+- HUFF: the four Huffman tables (Y DC, Y AC, colour DC, colour AC), 1424 bytes each (tools/codec.py)
+- QUANT: for each quality, the Y and colour tables (64 u16 each, natural order, scaled for the IDCT)
+- PICS: 12 bytes a picture (PIC_*): its width and height in 16 x 16 squares, its quality, 0, the picture it
+ shares squares with (u16, 0xFFFF none), how many squares it has of its own then (u16) and where its table
+ starts (u32)
+- TABLE: a whole picture's squares (3 bytes each: where in BANK), or a picture sharing another's: the squares
+ that differ (u16 the square's index, then 3 bytes)
+- BANK: the squares, each from a byte boundary
+- FONTS: for each font (FONT_*) its line height, baseline and 95 glyphs (32 to 126): advance, width, height,
+ x and y from the top of the line (s8), 0, the offset of its 4-bit alpha rows (u32, from the section)
+- IMGS: small pictures with alpha (IMG_*): width, height (u16), then 4-bit alpha
+
+anims.h: the night's animations as the game plays them (AN_*): their pictures, speed (a picture lasts 100 / speed
+frames) and how many times they play (0: for ever)."""
+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 codec as C # 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, "..", "..", "..")
+CCI = os.path.expanduser("~/Documents/Assets/gamesrc/fnaf4/dl/Application.cci")
+SECTIONS = ["HUFF", "QUANT", "PICS", "TABLE", "BANK", "FONTS", "IMGS"]
+QUALITY = {"scene": 80, "scare": 70, "face": 76}
+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")]
+L = "level"
+BED_X0, BED_W = 32, 432 # the part of the half-size bedroom kept
+
+
+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, serif=False):
+ name = "DejaVu" + ("Serif" if serif else "SansMono" if mono else "Sans") + ("-Bold" if bold else "") + ".ttf"
+ return ImageFont.truetype(find_font(name), size)
+
+
+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)), mode="edge")
+
+
+def arr(im):
+ return np.asarray(im.convert("RGB")).astype(np.float64)
+
+
+# ------------------------------------------------------------------ pictures
+class Pic:
+ def __init__(self, name, a, quality, base=None, refs=()):
+ self.name, self.q, self.base = name, quality, base
+ self.w, self.h = a.shape[1], a.shape[0]
+ self.a = pad16(a)
+ self.refs = [r for r in ([base] if base else []) + list(refs) if r]
+ self.mw, self.mh = self.a.shape[1] // 16, self.a.shape[0] // 16
+
+
+PICS = []
+BY_NAME = {}
+
+
+def pic(name, a, quality="scene", base=None, refs=()):
+ p = Pic(name, np.clip(a, 0, 255), quality, base, refs)
+ PICS.append(p)
+ BY_NAME[name] = p
+ return p
+
+
+def same_square(a, b, strict):
+ d = np.abs(a - b)
+ return d.max() <= (6 if strict else 14) and d.mean() <= (1.2 if strict else 3.0)
+
+
+def encode_all():
+ qt = {k: (C.qtable(C.STD_LUMA, v), C.qtable(C.STD_CHROMA, v)) for k, v in QUALITY.items()}
+ qnames = list(QUALITY)
+ for p in 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):
+ 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:
+ if same_square(tile, r.a[my * 16:my * 16 + 16, mx * 16:mx * 16 + 16], r is not p.base):
+ 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 PICS:
+ for s in p.sq:
+ if 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 PICS:
+ p.off = []
+ for s in p.sq:
+ 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) < 1 << 24
+ 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))
+ pics, table = b"", bytearray()
+ for p in PICS:
+ 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("<BBBBHHI", p.mw, p.mh, qnames.index(p.q), 0, PICS.index(b), len(diff), len(table))
+ for k in diff:
+ table += struct.pack("<H", k) + p.off[k].to_bytes(3, "little")
+ else:
+ pics += struct.pack("<BBBBHHI", p.mw, p.mh, qnames.index(p.q), 0, 0xFFFF, 0, len(table))
+ for o in p.off:
+ table += o.to_bytes(3, "little")
+ print(f"pictures: {len(PICS)}, squares {len(bank)} bytes, tables {len(table)} bytes")
+ return huff, quant, pics, bytes(table), bytes(bank)
+
+
+# ------------------------------------------------------------------ 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)
+
+
+DEFINES = []
+
+
+def define(name, value):
+ DEFINES.append((name, value))
+
+
+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 alpha_of(im, scale):
+ """an RGBA picture's brightness times alpha, scaled, for IMGS"""
+ im = im.convert("RGBA")
+ im = im.resize((max(1, round(im.width * scale)), max(1, round(im.height * scale))), Image.LANCZOS)
+ a = np.asarray(im).astype(np.float64)
+ return a[..., 3] * a[..., :3].max(axis=2) / 255
+
+
+def colour_of(im):
+ """an RGBA picture's main colour (its brightest opaque pixels), as 0xRRGGBB"""
+ a = np.asarray(im.convert("RGBA")).reshape(-1, 4).astype(np.float64)
+ a = a[a[:, 3] > 200]
+ a = a[a[:, :3].max(axis=1) >= np.percentile(a[:, :3].max(axis=1), 75)]
+ r, g, b = (int(round(v)) for v in a[:, :3].mean(axis=0))
+ return r << 16 | g << 8 | b
+
+
+# ------------------------------------------------------------------ the game's pictures, placed
+APP = None
+
+
+def half(im):
+ return arr(im.convert("RGB").resize((im.width // 2, im.height // 2), Image.LANCZOS))
+
+
+def screen(im):
+ """the game's 800 x 480 screen at half size, its middle 320"""
+ return half(im)[:, 40:360]
+
+
+def bedroom(im):
+ """the 1000 x 480 bedroom at half size, the part kept"""
+ return half(im)[:, BED_X0:BED_X0 + BED_W]
+
+
+def on_black(w, h, *parts):
+ """a w x h black picture with (picture, x, y) parts pasted (their corner at x, y)"""
+ c = Image.new("RGBA", (w, h), (0, 0, 0, 255))
+ for im, x, y in parts:
+ layer = Image.new("RGBA", (w, h))
+ layer.paste(im.convert("RGBA"), (x, y))
+ c.alpha_composite(layer)
+ return c
+
+
+def placed(h, x, y):
+ """picture h with its hot spot at (x, y): (picture, its corner)"""
+ hx, hy = APP.hotspot(h)
+ return APP.picture(h), x - hx, y - hy
+
+
+ANIMS = [] # (key, [picture indexes], speed, plays, wide)
+BY_HANDLE = {}
+
+
+def handle_pic(h, wide, quality, first, prev):
+ """a picture of the game's by its number (the first of its animation's shares squares with the one before; the
+ others list only where they differ from the first)"""
+ key = (h, wide, quality)
+ if key not in BY_HANDLE:
+ im = APP.picture(h)
+ a = bedroom(on_black(1000, 480, (im, 500 - APP.hotspot(h)[0], 240 - APP.hotspot(h)[1]))) if wide \
+ else screen(on_black(800, 480, (im, 0, 0)))
+ base = (first.base or first) if first else None
+ BY_HANDLE[key] = pic(f"H{h}{'W' if wide else ''}", a, quality, base=base,
+ refs=[r for r in (prev, LAST.get(wide)) if r])
+ LAST[wide] = BY_HANDLE[key]
+ return BY_HANDLE[key]
+
+
+LAST = {}
+
+
+def anim(key, obj, a, wide=False, quality="scene", frame=L):
+ """one of the game's animations: its pictures (each once, however many animations show it) and timing"""
+ hs = APP.anim(obj, a, frame)
+ speed, plays, _ = APP.speed(obj, a, frame)
+ first = prev = None
+ idx = []
+ for h in hs:
+ p = handle_pic(h, wide, quality, first, prev)
+ idx.append(PICS.index(p))
+ first, prev = first or p, p
+ ANIMS.append((key, idx, speed, plays, int(wide)))
+
+
+def night_pictures():
+ for a in (0, 12, 13, 14, 15, 16, 17, 19):
+ anim(f"ROOM_{a}", "Active", a, wide=True)
+ for key, obj in (("OFF4", "off4"), ("ON4", "on4"), ("CREAK", "closetcreak"), ("DARKL", "dark left"),
+ ("DARKR", "dark right"), ("DARKC", "dark center")):
+ anim(key, obj, 0, wide=True)
+ for key, obj in (("CARPET", "carpet run"), ("LSTART", "left start"), ("RSTART", "right start"),
+ ("BHIDE", "bonnie hide"), ("CHIDE", "Chica hide"), ("BITE", "foxy bite"),
+ ("LEAVE3", "3leave"), ("LEAVE2", "2leave"), ("LEAVE1", "1leave")):
+ anim(key, obj, 0)
+ for a in range(12, 22):
+ anim(f"PEEKL_{a}", "peek left", a)
+ anim(f"PEEKR_{a}", "peek right", a)
+ for a in [0] + list(range(12, 24)):
+ anim(f"CLOSET_{a}", "closet peek", a)
+ for a in (0, 12, 14, 16, 18, 19, 20, 21, 22, 23, 24, 25):
+ anim(f"BED_{a}", "bed view", a)
+ for a in (0, 12, 13, 14):
+ anim(f"JUMP_{a}", "jumpscare", a, quality="scare")
+ for key, obj in (("FREDDYATK", "freddy bedroom attack"), ("CUPCAKE", "cupcake attack"),
+ ("BONNIEATK", "bonnie bedroom attack"), ("FREDBEAR", "fredbear scare")):
+ anim(key, obj, 0, quality="scare")
+ for a in (0, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23):
+ anim(f"PLUSH_{a}", "Active", a, frame="plushtrap game")
+ pic("NIGHTMARE", screen(APP.picture(13)), "scare")
+ img("WARNING", alpha_of(APP.picture(1175), 0.5))
+
+
+def screens():
+ # the title: the house, the logo over it (at the game's place, faint or less faint as it flickers), the
+ # screen's right 640 so the logo shows whole
+ def title(h, alpha):
+ logo = APP.picture(h).copy()
+ logo.putalpha(logo.getchannel("A").point(lambda v: v * alpha // 255))
+ c = on_black(800, 480, (APP.picture(315), 0, 0), placed(h, 804, -2))
+ return half(c)[:, 80:400]
+ t = pic("TITLE", title(658, 120), "face")
+ pic("TITLE_FAINT", title(658, 60), "face", base=t)
+ for h, n in ((659, 1), (660, 2), (661, 3)):
+ pic(f"TITLE_GLITCH{n}", title(h, 120), "face", base=t)
+ define("TITLE_X0", 80)
+ for nm, h in (("NEW", 730), ("CONTINUE", 737), ("SIXTH", 738), ("EXTRA", 731), ("ANIMATRONICS", 911),
+ ("MAKINGFOXY", 904), ("MAKINGFREDBEAR", 912), ("JUMPSCARES", 914), ("PLUSHTRAP", 913),
+ ("NIGHTMARE", 1133), ("TWENTY", 293), ("EXIT", 43)):
+ img(f"M_{nm}", alpha_of(APP.picture(h), 0.5))
+ define("MENU_RED", colour_of(APP.picture(730)))
+ img("REDLINE", alpha_of(APP.picture(746), 0.5))
+ img("STAR", alpha_of(APP.picture(937), 0.5))
+ # the night's card: the bed in the dark, the black wipe the night's number sits on, "Night", the clock
+ pic("WHATNIGHT", screen(on_black(800, 480, (APP.picture(319), 0, 0))), "face")
+ img("NIGHTWORD", alpha_of(APP.picture(670), 0.5))
+ img("CLOCK", alpha_of(APP.picture(656), 0.5))
+ img("AM", alpha_of(APP.picture(652), 0.5))
+ pic("GAMEOVER", screen(APP.picture(404)), "face")
+ pic("TOOBAD", screen(on_black(800, 480, (APP.picture(46), 0, 0), placed(867, 404, 220))), "face")
+ img("GREAT", alpha_of(APP.picture(868), 0.5))
+ # 6 AM: the alarm clock's digits (red, the game's 0 to 9) and its colon
+ for k, h in enumerate(APP.anim("num 1", 0, "night win")):
+ img(f"DIGIT{k}", alpha_of(APP.picture(h), 0.5))
+ img("COLON", alpha_of(APP.picture(678), 0.5))
+ define("CLOCK_RED", colour_of(APP.picture(663)))
+ # Fun with Plushtrap's card: the game's title line (its instructions are for a touch screen)
+ card = screen(APP.picture(44))
+ pic("PLUSHCARD", card, "face")
+ # the box after the Nightmare: the box, its two locks (and their rattle), the words
+ locks = lambda k: on_black(800, 480, (APP.picture(1294), 0, 0),
+ placed(APP.anim("Active 2", 12, "lockbox")[k], 363, 311),
+ placed(APP.anim("Active 2", 12, "lockbox")[k], 433, 312))
+ b = pic("LOCKBOX", screen(locks(0)), "face")
+ n = len(APP.anim("Active 2", 12, "lockbox"))
+ for k in range(1, n):
+ pic(f"LOCKBOX{k}", screen(locks(k)), "face", base=b)
+ define("RATTLE_N", n)
+ pic("LOCKBOX_OPEN", screen(on_black(800, 480, (APP.picture(1294), 0, 0))), "face", base=b)
+ img("FORGOTTEN", alpha_of(APP.picture(733), 0.5))
+ # the ending: the toys go one by one, the boy, the words at the top
+ toys = [("Active 5", 1168, 524, 300), ("Active 4", 1167, 564, 260), ("Active 2", 1166, 644, 320),
+ ("Active 24", 1169, 664, 260), ("Active 3", 1170, 356, 356)]
+ for k in range(len(toys) + 3):
+ parts = [(APP.picture(977), 0, 0), placed(1179, 24, 340)]
+ parts += [placed(h, x, y) for _, h, x, y in toys[k:]]
+ if k <= len(toys) + 1:
+ parts.append(placed(1173 if k == len(toys) + 1 else 1172, 205, 361))
+ c = on_black(800, 480, *parts)
+ pic(f"ENDING{k}", half(c)[:, 40:360], "face", base=BY_NAME.get("ENDING0"))
+ img("ARROW", alpha_of(APP.picture(1084), 0.5))
+ # the extras: the animatronics standing, the making of Foxy and Fredbear, Plushtrap's picture
+ def fit(h, w, hh):
+ im = APP.picture(h).convert("RGBA")
+ s = min(w / im.width, hh / im.height)
+ im = im.resize((max(1, round(im.width * s)), max(1, round(im.height * s))), Image.LANCZOS)
+ c = Image.new("RGBA", (w, hh), (0, 0, 0, 255))
+ c.alpha_composite(im, ((w - im.width) // 2, hh - im.height))
+ return arr(c)
+ for k, a in enumerate((16, 0, 12, 13, 14, 15, 17, 18)):
+ pic(f"ANIMATRONIC{k}", fit(APP.anim("animatronic", a, "extras")[0], 176, 208), "face")
+ for nm, obj in (("FOXY", "making foxy 2"), ("FREDBEAR", "making foxy 3")):
+ for k, h in enumerate(APP.anim(obj, 0, "extras")):
+ pic(f"MAKING{nm}{k}", fit(h, 176, 176), "face")
+ pic("PLUSHTRAP", fit(42, 176, 176), "face")
+
+
+def icon():
+ sys.path.insert(0, os.path.join(ROOT, "tools"))
+ from make_icon import corner_mask
+ im = APP.picture(APP.anim("animatronic", 16, "extras")[0]).convert("RGBA")
+ face = im.crop((im.width // 2 - 70, 10, im.width // 2 + 70, 150))
+ c = Image.new("RGBA", face.size, (0, 0, 0, 255))
+ c.alpha_composite(face)
+ 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, wide in ANIMS:
+ lines.append((key, len(flat), len(idx), speed, plays, wide))
+ flat += idx
+ h = ["/* Made by tools/pack.py: the game's animations (AN_*), its own speeds and plays. Included once (night.c). */",
+ "#ifndef FNAF4_ANIMS_H", "#define FNAF4_ANIMS_H", "#include <stdint.h>", "",
+ "typedef struct {", " uint16_t first; /* in ANIM_PICS */",
+ " uint8_t n, speed, plays, wide; /* a picture lasts 100 / speed frames; plays 0: for ever; wide: the bedroom's */",
+ "} 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}, {p}, {w}}}, /* {k} */" for k, f, n, s, p, w 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 CCI)
+ night_pictures()
+ screens()
+ icon()
+ huff, quant, pics, table, bank = encode_all()
+ fonts = [
+ ttf_font(font(11, bold=True, mono=True)), # FONT_HUD
+ ttf_font(font(17, mono=True)), # FONT_BIG
+ ttf_font(font(11)), # FONT_TEXT
+ ttf_font(font(24, bold=True)), # FONT_CLOCK
+ ttf_font(font(40, serif=True)), # FONT_HUGE
+ ttf_font(font(14, serif=True)), # FONT_SERIF
+ ]
+ sections = [huff, quant, pics, table, bank, pack_fonts(fonts), pack_imgs()]
+ head = b"FNF4" + 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 FNAF4_DATA_H", "#define FNAF4_DATA_H", ""]
+ h += [f"#define SEC_{n} {i}" for i, n in enumerate(SECTIONS)]
+ h += [f"#define PIC_{p.name} {i}" for i, p in enumerate(PICS) if not p.name.startswith("H")]
+ h += [f"#define PIC_COUNT {len(PICS)}"]
+ h += [f"#define FONT_{n} {i}" for i, n in enumerate(["HUD", "BIG", "TEXT", "CLOCK", "HUGE", "SERIF"])]
+ h += [f"#define {n} {v}" for n, v in DEFINES]
+ h += [f"#define BED_X0 {BED_X0}", f"#define BED_W {BED_W}"]
+ h += ["", "#endif", ""]
+ open(OUT_H, "w").write("\n".join(h))
+ write_anims()
+ print(f"data.bin: {len(out)} bytes")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/games/games.json b/games/games.json
index d0f00eca..b7116273 100644
--- a/games/games.json
+++ b/games/games.json
@@ -1407,6 +1407,28 @@
"default": false,
"xl": true
},
+ {
+ "id": "fnaf4",
+ "rank": 36,
+ "title": "Five Nights at Freddy's 4",
+ "tagline": "Survive the bedroom",
+ "credit": "Based on the game by Scott Cawthon",
+ "top": "0x1E2638",
+ "bottom": "0x06080E",
+ "accent": "0x7A8FC8",
+ "colors": 16,
+ "records": [
+ "fnaf4.sav",
+ "fnaf4res.sav",
+ "fnaf4_saves.py"
+ ],
+ "shots": [
+ "docs/shot.png"
+ ],
+ "repo": "https://github.com/Mason363/NumPlay/tree/main/games/fnaf4",
+ "default": false,
+ "xl": true
+ },
{
"id": "famidash",
"rank": 34,
diff --git a/tests/test_games.py b/tests/test_games.py
index 2b10e089..749ec92d 100644
--- a/tests/test_games.py
+++ b/tests/test_games.py
@@ -306,6 +306,10 @@ GAMES = {
presses((1500, "back")), 5000),
# New Game: the first night's card, then the office; Home keeps the night, the next start is back in it, paused
"fnaf3": ("FiveNightsAtFreddys3.nwa", "fnaf3res.sav", presses((1500, "ok")), 9000, presses((1500, "back")), 5000),
+ # the warning, New Game: the first night's card, then the bedroom; Home keeps the night, the next start is back
+ # in it, paused
+ "fnaf4": ("FiveNightsAtFreddys4.nwa", "fnaf4res.sav", presses((1500, "ok"), (2200, "ok")), 9000,
+ presses((1500, "back")), 5000),
# how to play (the first time: two pages), Play, Stereo Madness, OK held to jump, Back to pause; Home keeps the
# guide read and the time played. Next time, from the copy, Play straight away, quit with On/Off
"famidash": ("Famidash.nwa", "famidash.sav",
@@ -382,7 +386,7 @@ COPIES = {"championisland": "champion_saves.py", "numblocks": "numblocks_saves.p
"angrybirds": "angrybirds_saves.py", "polytrack": "polytrack_saves.py", "paperclips": "paperclips_saves.py",
"badtime": "badtime_saves.py", "mahjong": "mahjong_saves.py",
"rider": "rider_saves.py", "snowrider": "snowrider_saves.py", "templerun": "templerun_saves.py",
- "fnaf2": "fnaf2_saves.py", "fnaf3": "fnaf3_saves.py", "famidash": "famidash_saves.py"}
+ "fnaf2": "fnaf2_saves.py", "fnaf3": "fnaf3_saves.py", "fnaf4": "fnaf4_saves.py", "famidash": "famidash_saves.py"}
def paperclips_ok(v):
@@ -643,6 +647,9 @@ CHECKS = {
# the night kept ("FNF3", its steps at 148); after the reinstall, from the copy, it goes on
"fnaf3": (lambda v: v[:4] == b"FNF3" and struct.unpack_from("<I", v, 148)[0] > 120,
lambda v: v[:4] == b"FNF3" and struct.unpack_from("<I", v, 148)[0] > 300),
+ # the night kept ("FNF4", its steps at 652); after the reinstall, from the copy, it goes on
+ "fnaf4": (lambda v: v[:4] == b"FNF4" and struct.unpack_from("<I", v, 652)[0] > 120,
+ lambda v: v[:4] == b"FNF4" and struct.unpack_from("<I", v, 652)[0] > 300),
# "FMD1", version 1: how to play read (flags at 5), time played (564); after the reinstall, from the copy, more
"famidash": (lambda v: famidash_ok(v) and v[5] & 1 and struct.unpack_from("<I", v, 2100)[0] >= 7000,
lambda v: famidash_ok(v) and v[5] & 1 and struct.unpack_from("<I", v, 2100)[0] >= 12000),
diff --git a/tools/release.py b/tools/release.py
index 5470378b..c930fa8d 100644
--- a/tools/release.py
+++ b/tools/release.py
@@ -62,6 +62,7 @@ ALONE = {
"templerun": ("Temple Run", "the endless run from the temple: turn, jump, slide and lean, with the game's rules and numbers"),
"fnaf2": ("Five Nights at Freddy's 2", "the new pizzeria's six nights and the Custom Night: the mask, the music box, the flashlight"),
"fnaf3": ("Five Nights at Freddy's 3", "Fazbear's Fright's six nights with Springtrap and the phantoms: the lure, the vents, the maintenance panel"),
+ "fnaf4": ("Five Nights at Freddy's 4", "the bedroom's nights with the Nightmares: listen at the doors, the closet, the bed, Fun with Plushtrap"),
"famidash": ("Famidash", "TFDSoft's Geometry Dash for the NES, made for the calculator: the 173 levels of Famidash HUGE, every mode, practice mode"),
}
VARIANTS = [