CS50 2D - Lecture 5 - Legend of Zelda
Overview
CS50 Lecture 5 builds a top-down Zelda-style game in LÖVE 2D, combining entity states, AABB collision, sword hitboxes, switches, and transitions between procedurally connected dungeon rooms. The implementation also demonstrates data-driven entity definitions, stencil masking for doorway depth, and a queue-based dungeon generator that can be stepped through with Lua coroutines.
Key takeaways
- Separating entity definitions from game logic lets designers change textures, animation frames, movement speeds, and other properties without editing the underlying implementation.
- Fixed-size Zelda rooms can use boundary checks instead of per-tile collision, while a bumped flag lets the player distinguish an ordinary wall from a doorway.
- Sword combat needs direction-specific hitboxes, and temporary invulnerability prevents repeated collisions from removing multiple hearts in rapid succession.
- A smooth screen transition can keep current and adjacent rooms in memory, tween the camera and player for one second, then swap room references and reset coordinates.
- Stencil masking provides doorway depth by preventing player pixels from drawing over selected arch pixels, with debug rectangles helping verify the mask.
- A queue-based dungeon generator explores room coordinates breadth-first, while visited tracking and minimum-room safeguards prevent duplicate placements and undersized dungeons.
Chapters
- The original Legend of Zelda used connected screens to create an explorable overworld and labyrinth-style dungeons.
- The lecture recreates core dungeon mechanics: room transitions, enemies, sword attacks, switches, and scrolling.
- Unlike a side-scrolling platformer, top-down movement uses both the X and Y axes without gravity defining vertical movement.
- The playable example includes a title screen, enemy encounters, sword attacks, and health displayed as hearts.
- Pressing M opens a map that marks the current room in red and other rooms in green.
- A switch opens doorways, and losing all health leads to a styled game-over screen.
- The first build renders a player moving in four directions with directional walking animations and a heart HUD.
- Player behavior uses idle and walk states, extending the state-machine approach from the earlier Mario lecture.
- The HUD stays fixed on screen while the player moves through the game world.
- The player sprite sheet contains distinct walking frames for up, down, left, and right, along with unused pot-carrying frames.
- Walking sprites use approximately 16-by-16 tiles, while sword animations use larger 32-by-32 frames.
- Keeping sprite categories in separate textures makes uniformly sized frames easier to load with generated quads.
- An Entity base class groups shared behavior such as rendering, updating, collision, direction, and animation handling.
- Animation definitions specify texture names, frame indices, and timing in entity definition tables rather than hard-coding every animation.
- The Player adds six health units, representing three full hearts, plus an invulnerability timer that prevents rapid repeated damage.
- LÖVE's graphics push and pop operations isolate transformations such as camera translation.
- World objects can be drawn in a translated coordinate space while hearts are drawn afterward at fixed screen coordinates.
- This separates camera-dependent rendering from user-interface rendering.
- The dungeon tiles use a 16-by-16 grid with corner pieces, wall variants, floor patterns, and multi-tile doorways.
- A Python utility using Pillow overlays tile indices on a saved image, avoiding repeated manual counting.
- The numbered sheet makes it practical to define tile IDs as constants and reference them in room-generation code.
- A Room begins as a tile container that renders top, bottom, left, and right walls around a floor.
- A two-dimensional Y-by-X traversal fills the tile map using predefined tile IDs.
- Randomly selecting among floor and wall variants reduces the repetitive look of identical tiles.
- Because rooms share fixed dimensions and tile placement, the example checks room boundaries instead of implementing collision for every tile.
- The Player walk state calls EntityWalkState.update with self to reuse inherited movement behavior after overriding update.
- Boundary collisions set a bumped flag, which later lets the player check whether the collision occurred at a doorway.
- The dungeon stores rooms in a two-dimensional table and starts the player near the center of the bottom row of a 10-by-10 grid.
- It tracks both a current room and a next room so each can be updated and rendered during a transition.
- The dungeon generator creates a connected collection of rooms, while individual Room objects manage tiles and entities.
- A hitbox is an area that can strike another object; a hurtbox is an area that can receive damage.
- In fighting games such as Street Fighter, attack hitboxes and vulnerable body regions can be active in different places and for different durations.
- Collision-box size affects game balance and perceived fairness, so developers often visualize and tune rectangles during debugging.
- Pressing Space enters a SwingSword state that chooses the sword animation based on the player's facing direction.
- The sword's rectangle changes position, width, and height for each direction, reflecting the sprite's orientation.
- The attack animation plays once, then returns the player to idle; debug rectangles make hitbox placement visible.
- Rooms generate ten enemies chosen from skeleton, slime, bat, ghost, and spider definitions.
- Enemy animation and movement settings are retrieved from entity data tables instead of being duplicated in generation code.
- Enemies use simple idle and walking behavior, choosing directions and stopping when they hit a wall.
- Room updates test player-enemy collisions with AABB rectangles and reduce player health by one unit, or half a heart.
- After damage, the player flashes for 1.5 seconds and cannot be hit again while the invulnerability flag is set.
- Sword attacks test their hitbox against room entities; enemies at zero health are removed from the room's entity table.
- A switch is a game object with an on-collision callback, following the trigger pattern used for interactive objects in earlier examples.
- Touching the switch marks it pressed, plays a sound, and sets the room's doorways to open.
- The same callback approach can connect other game objects to room or dungeon behavior.
- Each doorway is larger than one 16-by-16 tile and is assembled from four tiles, including semi-transparent arch pieces.
- Doorway direction determines its position and dimensions, while its open flag selects the appropriate tile indices.
- The tile sheet includes distinct open and closed door graphics, including gated variants that can communicate different room rules.
- A transition loads an adjacent room, shifts the camera by one virtual screen width or height, and moves the player to the opposite side of that room.
- The current and next room coexist during the animation, then their roles are swapped and the new current room is normalized to the origin.
- LÖVE's event system uses event.on handlers and event.dispatch calls to trigger directional shifts such as shift left or shift up.
- Only the player's walk state initiates room transitions; ordinary enemies cannot trigger the same behavior.
- When movement bumps into a wall, the player checks backward for an open doorway and dispatches the matching shift event.
- The player's perpendicular coordinate is aligned with the doorway before the transition to prevent visibly clipping through its edge.
- Dungeon handlers call beginShifting with a full-screen horizontal or vertical offset and load the adjacent room.
- A one-second timer tween moves the player and camera, while the adjacent room is rendered using an offset.
- When the tween finishes, the dungeon promotes nextRoom to currentRoom, resets offsets, closes doors, and resets switches.
- A stencil buffer stores per-pixel values that determine whether later drawing operations may affect the screen.
- Masking the doorway arch area prevents the player's pixels from appearing over the arch, creating the illusion of walking through a corridor.
- Stencil and depth tests can also support effects such as outlines and Portal-style views into another scene.
- LÖVE 11 uses graphics.stencil with a drawing callback and a separate stencil test; LÖVE 12 uses setStencilState.
- The LÖVE 12 implementation disables all RGBA color channels while drawing mask rectangles so the masks do not appear on screen.
- A debug key, S, displays the four mask rectangles so their placement can be checked during transitions.
- A separate dungeon test state displays generation on a 10-by-10 grid and advances the process one step at a time with Enter.
- The generator begins near the bottom center, tracks visited coordinates, and considers orthogonal neighbors for new rooms.
- A 40% chance to skip each direction, and a 60% chance to add one, produces varied layouts rather than uniform growth.
- The generator stores candidate room coordinates in a queue and advances a head index to explore them breadth-first.
- A visited table prevents two generated rooms from claiming the same coordinate, and a final pass adds doorways between connected rooms.
- Purely random expansion can produce too few rooms, so the production version enforces a minimum room count and fills remaining spaces if necessary.
- Lua coroutines preserve a function's execution state and resume it at yield points when called again.
- The dungeon test uses coroutine.wrap and coroutine.yield to expose generation phases, queue contents, and visited-room data incrementally.
- Step-by-step generation makes complex procedural algorithms easier to inspect and debug than a single synchronous run.
- Entity data can describe more than animation, including weapons, aggression, AI, sleep behavior, and flammability.
- Separating configuration from implementation lets designers adjust game content while programmers build reusable systems.
- NES games such as Super Mario Bros. were written in 6502 assembly, requiring direct manipulation of CPU instructions compared with high-level Lua in LÖVE 2D.
- Assignment 5 extends the player with liftable pots, throwable projectiles, collectible hearts, and a boomerang found once per dungeon.
- The boomerang should damage enemies, travel a set distance, return toward the player, and not be thrown again while already in flight.
- The next lecture introduces Box2D physics through an Angry Birds-style project, followed later by turn-based systems and GUI elements.
Transcript excerpt
0:20 Hello world, this is CS 52D Lecture 5. Today we're gonna be looking at the Legend of Zelda, which is a favorite franchise of mine amidst Mario. I like Mario quite a bit as well, but this was one of the first series that I have memory certainly playing, and also we styled it based on the original cartridge for the NES was actually colored gold, so was its sequel, which I thought was kind of a cool thing. This is what the original Zelda looks like, and this is sort of like a famous line that people quote online all the time. It gets referenced in various games. It's a throwback and sort of this is the very first thing you see when you go into the game. You start off, you see this cave, you go in, you grab a sword. It at its time was one of the only games that sort of had this early idea of an open world that you could go out and explore, and it accomplished this via having a bunch of sort of. separate screens that you could transition in and across.
1:11 This is a screenshot of a dungeon. You would also go and navigate sort of these labyrinth type structures, and in today's codebase we'll be primarily focused on this sort of view of what Zelda looks like looking at a dungeon that gets generated and then we can traverse it and we won't have all the bells and whistles per se, but we'll have the sort of famous scrolling and some monsters and the ability to swing your sword and so on and so forth. This was the first Zelda that I played as a kid. This is linked to the past for the Super Nintendo, which took the formula and sort of expanded on it,
This is the start of the transcript. Save this video free for the whole transcript, searchable and time-coded.
Related notes
Summary, takeaways, and chapters were generated by AI from the video's transcript and may contain errors. The video belongs to its creator, CS50.