CS100 · Fall 2026 · Individual assignment

HW4: Two C Games

Turn pointers, arrays, and a little persistent state into two playable terminal games.

C1710 functions100 points
hw4 / assignment
Release
Deadline

Asia/Singapore (UTC+8)
Follow Gradescope and course notices for updates.

Preview of Snake in the terminal.
Problem 140 automatic points

Circular-list Snake

A circular list that moves, grows, and cleans up safely.

You edit p1/snake.c

  • snakeInit
  • snakeNextPosition
  • snakeContains
  • snakeStep
  • snakeDestroy
  • nextRandom
Preview of Flappy Bird in the terminal.
Problem 240 automatic points

Flappy Bird

A pipe array, collision boundaries, and one-time scoring.

You edit p2/flappy.c

  • advancePipes
  • birdHitsObstacle
  • scorePassedPipes
  • nextRandom

Get going

Quick start

  1. Download & unzipOpen the extracted hw4/
  2. Build with sanitizersmake debug
  3. Run one game(cd p1 && ./build/snake-debug)or (cd p2 && ./build/flappy-debug)
  4. Make it yoursEdit snake.c / flappy.c

Want to play first? Try the finished games before you start coding.

The assignment

Overview

In this assignment, you will build the core game logic for two playable terminal games in C17: P1: Circular-list Snake (40 automatic points) and P2: Flappy Bird (40 automatic points), plus 20 points for the staff check and code organization. This is individual work, and there are no separate objective questions. You will practise circular linked lists and memory ownership in P1, fixed arrays, boundary conditions, and one-time flags in P2, and a function-local static state in both problems.

At a glance#

Problem Student file Required work Points
P1: Circular-list Snake p1/snake.c Create, query, move, grow, and destroy a circular linked list, and keep random state (6 functions: snakeInit, snakeNextPosition, snakeContains, snakeStep, snakeDestroy, nextRandom) 40 automatic
P2: Flappy Bird p2/flappy.c Advance and recycle pipes, detect collisions, count new points, and keep random state (4 functions: advancePipes, birdHitsObstacle, scorePassedPipes, nextRandom) 40 automatic

What is provided and what you write#

You do not need to build a game engine from scratch. The framework already provides the main loops, keyboard input, timing, terminal drawing, colors, and result screens. In P2, the framework also handles gravity, flapping physics, random gap generation, and round retries. Read the public headers (p1/snake.h and p2/flappy.h) to see what types and constants exist and when the framework calls your functions.

Every visible action on screen comes from a small change in your data structures:

  • Snake uses a circular linked list. Normal movement reuses the old tail as the new head; growth adds one node.
  • Flappy Bird uses a fixed array of pipe pairs, collision boxes, and a flag that prevents repeated scoring.
Each frame, the game framework reads input and calls your functions to update the game state before drawing the screen.
Each frame, the game framework reads input and calls your functions to update the game state before drawing the screen.

By default, you only edit p1/snake.c and p2/flappy.c. You may add static helper functions or extra C files, as long as you keep the required file paths, public types, and function signatures intact. P1 must use the provided circular linked list (Snake and SnakeNode). P2 uses the provided fixed array (m_pipes[PIPE_COUNT]) and needs no dynamic memory allocation.

Get started#

You need macOS or Linux with a C17 compiler, Make, and a UTF-8 ANSI terminal. On macOS, run xcode-select --install to get the command-line tools. On Ubuntu or Debian, install the build-essential package. You do not need any particular editor or workspace, and both games are silent.

From the extracted hw4/ directory, build and run one game at a time:

make debug
(cd p1 && ./build/snake-debug)
(cd p2 && ./build/flappy-debug)

make debug compiles with debug symbols, AddressSanitizer (ASan), and UndefinedBehaviorSanitizer (UBSan). make release, or plain make, builds the normal optimized executables at p1/build/snake and p2/build/flappy. Debug and release modes write to separate output files.

Here is the directory structure inside hw4/:

hw4/
  README.md, Makefile, .clang-format
  docs/                       # Full handout, figures, debugging and grading
  p1/snake.c                  # Your 6 functions
  p1/snake.h                  # Public types, constants and interfaces
  p2/flappy.c                 # Your 4 functions
  p2/flappy.h                 # Public types, constants and interfaces
  p2/framework/               # Provided input, physics, drawing and game flow

Before you write your code, the two starter programs behave differently:

  • The Snake starter exits with a setup message because snakeInit returns false. Implementing initialization alone does not make it playable: the snakeStep stub ends the first movement tick with an out-of-memory result. Complete all six functions for correct play, food placement, and cleanup.
  • The Flappy Bird starter already draws the window and accepts Space to flap, but pipe movement, collision detection, and scoring do nothing until you complete your functions.

Note: The terminal renderer uses ANSI truecolor and half-block characters. Exact visual proportions depend on your terminal font and line spacing, and these visual details are not graded. Flappy Bird only reads single keypresses; it does not need simultaneous direction keys or key-release detection.

Try the finished games#

Want to see the goal before you start? Download HW4_demos.zip from the HW4 page. It contains playable reference programs for both games (programs only, no source code):

Folder Platform
hw4-demo/linux-x86_64/ Linux on x86_64 with glibc 2.34 or newer (for example Ubuntu 22.04 or later)
hw4-demo/macos-arm64/ macOS 11 or newer on Apple Silicon; Intel Macs are not supported

From the folder that contains hw4-demo/, run one game at a time. On Linux:

(cd hw4-demo/linux-x86_64/p1 && ./snake)
(cd hw4-demo/linux-x86_64/p2 && ./flappy)

On a Mac with Apple Silicon:

(cd hw4-demo/macos-arm64/p1 && ./snake)
(cd hw4-demo/macos-arm64/p2 && ./flappy)

Tip: These demos are not notarized by Apple, so macOS may block them after download. If that happens, run xattr -dr com.apple.quarantine hw4-demo once from the same folder, then try again. If a program says permission denied, run chmod +x on it.

Keep the demo ZIP and the extracted hw4-demo/ folder outside your homework repository: the programs inside are compiled executables.

Read and develop#

Read the public headers and the P1, P2, and circular-list contracts. Design your own boundary tests and use the debug builds while developing.

Both games require nextRandom(unsigned int seed) with one function-local static unsigned int state. The problem statements give its constants, recurrence, seed rules, and examples.

A function-local static variable keeps its value between calls while remaining invisible outside nextRandom.
A function-local static variable keeps its value between calls while remaining invisible outside nextRandom.

Submit and explain your code#

Place the complete hw4/ directory at the root of your GitHub repository, and submit the whole repository to HW4_programming on Gradescope.

Grading is split into 80 automatic points (40 for P1, 40 for P2) and 20 manual points for the staff check and code organization. Each problem has an in-person staff check on your last submission where you must explain and modify your own code. Each check is 6 points; code organization is 4 points per problem.

Important: Check the formatting and repository gates before you submit:

  • Formatting gate (per problem): Your student code is checked with clang-format 18 using the Recitation 0 configuration. If a problem fails the formatting check, that problem receives 0 automatic points (the other problem is graded independently).
  • Repository cleanliness gate (whole assignment): Submitting any prohibited generated or cache files—including a nonempty build/ directory at any depth (even a build/ containing only .gitkeep), compiled binaries, or object files—gives 0 out of 80 automatic points for the entire assignment. Empty build/ directories are fine.

Extra helper functions and creative game variants are welcome as long as they do not replace or break the required core tasks. For full details, read Code style and repository rules, Debugging, and Grading.

Problem 1 · Circular lists

Circular-list Snake

40 points automatic

Complete six functions in p1/snake.c for a C17 terminal Snake game. Each food adds 1 point and 1 body node. Reach 10 points to win; hitting a wall or the body ends the game. The framework handles food placement, input, drawing, timing, pause, and restart.

Terminal Snake game showing the green snake, yellow food, wall border, and score bar
Terminal Snake game showing the green snake, yellow food, wall border, and score bar

The preview uses a sample font; colors and proportions depend on your terminal.

Build and play#

From hw4/:

(cd p1 && make)
(cd p1 && ./build/snake)

Use WASD or arrow keys to turn, P to pause, R to restart, and Q to quit. At most one turn is accepted per movement period. Enlarge the terminal if prompted.

Read snake.h for the public types, constants, and declarations. Keep those interfaces unchanged. Implement functions in snake.c, not snake.h; helpers may also go in snake.c.

Required representation#

Use a singly linked circular list of heap-allocated SnakeNode objects. Each node has Coord m_pos and struct SnakeNode *m_next. Snake stores m_head, m_length, m_direction, m_rows, and m_cols.

Four nodes A, B, C, and D form a circular list where head D points to tail A
Four nodes A, B, C, and D form a circular list where head D points to tail A
  • An empty snake has m_head == NULL and m_length == 0.
  • In a nonempty snake, m_head->m_next is the tail. Links run from tail through body to head, then back to tail.
  • A one-node ring points to itself. A length-n ring has no NULL links and returns to its starting node after exactly n links, not earlier.
  • Coordinates start at 0. The outer rows and columns are walls; BOARD_WALL_THICKNESS is 1.

See Circular Lists for the ring invariants. The letters in these figures identify nodes, not cells:

On a normal move, old tail node A updates its position and becomes the new head On a growing move, old tail A stays in place and new node E is inserted as the new head

Functions to write#

1.snakeInit6 automatic points#

bool snakeInit(Snake *snake, int rows, int cols, size_t length);

Precondition: *snake is a zero-initialized empty Snake. Create length nodes on a rows by cols board and return true on success.

  • Require rows >= MIN_BOARD_SIZE, cols >= MIN_BOARD_SIZE (MIN_BOARD_SIZE is 6), and 1 <= length <= cols - 2 * BOARD_WALL_THICKNESS.
  • Face DIR_RIGHT. Put the head at row rows / 2, column max(cols / 2, length), with the remaining body extending left one column per node.
  • Set every Snake field and satisfy the ring invariants.
  • On invalid arguments or any allocation failure, release all allocations from this call, reset *snake to all zero, and return false.

2.snakeNextPosition4 automatic points#

Coord snakeNextPosition(const Snake *snake, Direction requested);

Precondition: the snake was successfully initialized. Return the next head cell without modifying any state.

Ignore a direct reverse request when m_length > 1; allow it at length 1. Ignore invalid direction values. In either ignored case, keep the current direction. Up/down change the row by -1/+1; left/right change the column by -1/+1.

3.snakeContains4 automatic points#

bool snakeContains(const Snake *snake, Coord pos);

Return whether any body node has both coordinates equal to pos. Return false if m_head == NULL or m_length == 0. Do not modify the snake.

4.snakeStep16 automatic points#

StepResult snakeStep(Snake *snake, Direction requested, bool grow);

Advance an initialized snake one cell using the same direction rules as snakeNextPosition. The framework supplies grow according to whether the next cell contains food.

Condition Result
Next cell is on or beyond a wall: row < BOARD_WALL_THICKNESS, row >= m_rows - BOARD_WALL_THICKNESS, or the analogous column bounds STEP_WALL
Next cell is occupied by a body node, subject to the tail exception below STEP_SELF
Growth allocation fails STEP_NO_MEMORY
Move succeeds STEP_OK

A normal move (grow == false) reuses the old tail as the new head, with no allocation, freeing, or shifting coordinates across body nodes. Length stays unchanged. Growth keeps all existing nodes in place and adds one newly allocated head between the old head and tail; length increases by 1. On success, store the effective direction.

Important: A normal move may enter the old tail cell. Growth may not: that is STEP_SELF. On any failure, every original link, coordinate, and Snake field must remain unchanged.

5.snakeDestroy6 automatic points#

void snakeDestroy(Snake *snake);

Free every node and reset every field of *snake to zero. Empty snakes and repeated calls on the same snake must be safe.

6.nextRandom4 automatic points#

unsigned int nextRandom(unsigned int seed);

Implement this separately in p1/snake.c and p2/flappy.c. Keep state in one function-local static unsigned int, initially RANDOM_INITIAL_SEED. Use unsigned arithmetic and the named constants, not raw numbers. Do not use globals, struct members, rand, or srand; do not allocate memory or modify game structs.

Constant Value
RANDOM_INITIAL_SEED 100
RANDOM_MULTIPLIER 109
RANDOM_INCREMENT 1021
RANDOM_MODULUS 32768

A positive seed replaces the previous state with seed % RANDOM_MODULUS; zero retains the previous state. Then advance and return the state:

state = (RANDOM_MULTIPLIER * state + RANDOM_INCREMENT) % RANDOM_MODULUS

Normalization must precede the recurrence. Every result is in [0, RANDOM_MODULUS).

Calls, in order Results
nextRandom(1), nextRandom(0), nextRandom(0) 1130, 25887, 4656
nextRandom(1) again 1130 again
nextRandom(32768) 1021

Without a prior positive seed, the first two nextRandom(0) calls return 11921 and 22458. The framework seeds once at startup and uses zero for later food placement. Round restarts continue the sequence; a new process starts fresh.

Debug and calibrate#

Design your own boundary tests in addition to playing. From p1/:

make debug
./build/snake-debug

See Debugging for sanitizer reports and test-driver placement. If cells look stretched, run ./build/snake --calibrate, adjust with + or -, and press Enter. Calibration is not graded.

Important: Delete the generated .snake-ui.conf and clean build/ before submitting. Follow the repository and formatting rules.

P1 has an in-person staff check on your last submission where you must explain and modify your own code (6 points), plus code organization (4 points). See Grading.

Problem 2 · Arrays & collision

Flappy Bird

40 points automatic

Complete four functions in p2/flappy.c for a C17 terminal Flappy Bird game. Tap Space to flap. The bird stays at BIRD_X while pipe pairs scroll left; each passed pair earns one point. No linked list or dynamic allocation is needed.

Flappy Bird running in a terminal with scrolling pipes and a score counter.
Flappy Bird running in a terminal with scrolling pipes and a score counter.

Note: The preview uses a sample font. Colors and proportions depend on your terminal.

Build and play#

From hw4/, on macOS or Linux with a UTF-8 ANSI terminal:

make debug
(cd p2 && ./build/flappy-debug)

Space starts, flaps, or retries after a collision. P pauses, R returns to the ready screen, and Q quits. Results remain visible until retry. The game is silent and reads individual keypresses, not key releases. The framework keeps the best score for the current process.

Read flappy.h for public types, constants, and helpers; do not modify it. The starter draws and accepts input, but its four student functions are incomplete. make release or plain make builds p2/build/flappy.

Framework and data#

The framework handles input, bird physics, gap generation, drawing, pause, and retries. Each physics update applies bird motion, calls advancePipes(game, STEP), checks birdHitsObstacle(game), and calls scorePassedPipes(game) only if the bird survives. It manages READY, PLAYING, DEAD, and m_best.

Game contains Pipe m_pipes[PIPE_COUNT], bird position m_bird_y, velocity m_vy, elapsed time m_elapsed, score m_score, best score m_best, and status m_status.

Each Pipe has float m_x (left edge), float m_gap_y (gap's top edge), and bool m_scored (whether this pair has earned a point). One slot represents both pipes. Their width is PIPE_WIDTH; the lower pipe begins at m_gap_y + PIPE_GAP_HEIGHT.

A fixed array of four pipe pairs moves left and recycles off-screen slots behind the rightmost pipe.
A fixed array of four pipe pairs moves left and recycles off-screen slots behind the rightmost pipe.

Functions to write#

1.advancePipes10 automatic points#

void advancePipes(Game *game, float dt);

Precondition: dt is finite and nonnegative. Decrease every pipe's m_x by PIPE_SPEED * dt. Recycle each slot satisfying m_x + PIPE_WIDTH <= 0 by calling recyclePipe(game, index), in ascending index order.

Important: Every pipe must have its updated position before the first recycling call. The helper uses the current positions to find the rightmost pipe. A zero dt still requires recycling eligible slots, including exact equality at the boundary.

The helper places the recycled slot after the current rightmost pipe, outside the view, generates its gap using nextRandom(0), and resets m_scored to false. Use this helper rather than a custom gap generator. Do not resize the array. Unrecycled slots retain their m_gap_y and m_scored values.

2.birdHitsObstacle14 automatic points#

bool birdHitsObstacle(const Game *game);

Return whether the bird crosses the playable vertical bounds or overlaps any pipe. Do not modify *game. Use gameBirdBox(game) for the bird's Box (m_x, m_y, m_width, m_height).

The playable area is [0, FLOOR_Y]. A collision occurs when bird.m_y < 0 or bird.m_y + bird.m_height > FLOOR_Y; exact ceiling or floor contact is safe.

Use boxesOverlap with the bird and both rectangles of every pipe:

Rectangle Top-left (m_x, m_y) Width Height
Upper pipe {pipe.m_x, 0} PIPE_WIDTH pipe.m_gap_y
Lower pipe {pipe.m_x, pipe.m_gap_y + PIPE_GAP_HEIGHT} PIPE_WIDTH FLOOR_Y - pipe.m_gap_y - PIPE_GAP_HEIGHT

Overlap requires positive intersection on both axes. Shared edges or corners alone are safe, as is fitting completely inside the gap. Use the named constants, not hardcoded dimensions.

The bird box is checked against the ceiling, the floor, and the upper and lower rectangles of each pipe.
The bird box is checked against the ceiling, the floor, and the upper and lower rectangles of each pipe.

3.scorePassedPipes12 automatic points#

int scorePassedPipes(Game *game);

For every unscored pipe whose right edge is strictly left of the bird's left edge (pipe.m_x + PIPE_WIDTH < BIRD_X), award one point and set m_scored = true. Equality does not count as passed. Add all new points to game->m_score and return their count, not the total score.

A pass scores only once until recycling resets its flag; multiple pipes may score in one call. Leave all other state unchanged, including positions, gaps, m_best, and m_status.

A pipe awards one point when its right edge moves strictly left of BIRD_X and cannot score again until recycled.
A pipe awards one point when its right edge moves strictly left of BIRD_X and cannot score again until recycled.

4.nextRandom4 automatic points#

unsigned int nextRandom(unsigned int seed);

Implement this separately in p2/flappy.c and p1/snake.c, with the same contract. Keep state in one function-local static unsigned int, initially RANDOM_INITIAL_SEED. Use unsigned arithmetic and named constants. Do not use globals, struct members, rand, or srand; do not allocate memory or modify game structs.

Constant Value
RANDOM_INITIAL_SEED 100
RANDOM_MULTIPLIER 109
RANDOM_INCREMENT 1021
RANDOM_MODULUS 32768

A positive seed replaces the previous state with seed % RANDOM_MODULUS; zero retains the previous state. Then advance and return the state:

state = (RANDOM_MULTIPLIER * state + RANDOM_INCREMENT) % RANDOM_MODULUS

Normalization must precede the recurrence. Every result is in [0, RANDOM_MODULUS).

Calls, in order Results
nextRandom(1), nextRandom(0), nextRandom(0) 1130, 25887, 4656
nextRandom(1) again 1130 again
nextRandom(32768) 1021

Without a prior positive seed, the first two nextRandom(0) calls return 11921 and 22458. The framework seeds once at startup and uses zero for new gaps. Round retries and replacing a Game do not reset the sequence; a new process starts fresh.

Debug and submit#

Design your own boundary tests in addition to playing. Use make debug and ./build/flappy-debug for ASan and UBSan checks. See Debugging for reports and test-driver placement, and follow the repository and formatting rules.

P2 has an in-person staff check on your last submission where you must explain and modify your own code (6 points), plus code organization (4 points). See Grading.

A closer look

Circular Lists for P1

P1 uses a singly linked circular list. Nodes are separately allocated, unlike array elements. The last link returns to the first node instead of ending at NULL.

The Snake ring#

Tail node A links through body nodes B and C to head node D, and head D links back to tail A
Tail node A links through body nodes B and C to head node D, and head D links back to tail A

Snake stores one entry pointer, m_head, and a node count, m_length. m_head->m_next is the tail. Links run from tail through body to head, then back to tail.

Every valid snake satisfies these invariants:

  • Empty: m_head == NULL and m_length == 0.
  • One node: m_length == 1 and m_head->m_next == m_head.
  • Length n: following exactly n links from any node returns to that node, with no NULL links or earlier return.

Movement and ownership#

A normal move reuses the old tail as the new head. It does not allocate, free, or shift coordinates across the body. Growth keeps the old tail in place and adds one new head node. Both operations must preserve the ring.

The head may enter the old tail cell during a normal move because the tail leaves it. During growth, that cell remains occupied and causes STEP_SELF.

Important: A failed snakeStep leaves the original snake unchanged. A failed snakeInit releases its partial allocations and leaves a zeroed snake.

snakeDestroy must release every node exactly once and zero all fields. It must be safe on empty snakes and when called repeatedly. See P1 for the full function contracts.

Testing#

Design your own boundary tests and run them with sanitizers. A playable game alone does not establish that the ring and memory ownership are correct.

Build confidence

Debugging with Sanitizers

C code can look correct on screen while accessing invalid memory. AddressSanitizer (ASan) catches memory errors; UndefinedBehaviorSanitizer (UBSan) catches detectable undefined behavior.

Workflow for debugging with sanitizers: build with detection enabled, run boundary cases, read the first report, fix the cause, and retest.
Workflow for debugging with sanitizers: build with detection enabled, run boundary cases, read the first report, fix the cause, and retest.

Build and run#

From hw4/, run one game at a time:

make debug
(cd p1 && ./build/snake-debug)
(cd p2 && ./build/flappy-debug)

You can also build inside either problem directory. The starter functions are incomplete; see each problem's handout. Press Q to quit normally so exit cleanup can run.

Mode Build command P1 executable P2 executable
Debug make debug p1/build/snake-debug p2/build/flappy-debug
Release make release or make p1/build/snake p2/build/flappy

Debug and release outputs are separate. Release uses -O2; debug uses:

-O1 -g -fno-omit-frame-pointer
-fsanitize=address,undefined -fno-sanitize-recover=all

These options retain source locations and useful call stacks and stop at the first detected error. If sanitizer runtimes are missing, install the matching compiler runtime or use a compiler that includes it.

What the tools detect#

Tool Examples
ASan Out-of-bounds access, use after free, double free, invalid free
UBSan Signed overflow, misaligned access, detectable null-pointer-related operations
LeakSanitizer (LSan) Unreleased allocations at exit, on supported platforms

Sanitizers only inspect paths that execute. A quiet run is not proof of correctness. Design your own boundary tests in addition to playing.

On Linux with LSan support, run from hw4/:

(cd p1 && ASAN_OPTIONS=detect_leaks=1 ./build/snake-debug)
(cd p2 && ASAN_OPTIONS=detect_leaks=1 ./build/flappy-debug)

Note: LSan availability varies by OS, architecture, and compiler. Regardless of local support, every allocation your code owns must be released.

Reading reports#

Fix the first report's root cause before chasing later symptoms. Read its error type, source location, and relevant allocation/free call stacks. Rebuild and rerun after fixing it; do not suppress reports by disabling sanitizers.

The terminal UI may obscure a report. Save standard error outside your repository:

(cd p1 && ./build/snake-debug 2>/tmp/hw4-p1-sanitizer.log)
cat /tmp/hw4-p1-sanitizer.log

If an abnormal exit leaves the terminal unusable, run stty sane and, if needed, reset. Do not commit logs or executables.

Important: Put custom drivers with their own main in that problem's extras/ or extensions/ directory, not directly in p1/ or p2/. Otherwise they conflict with the grader's test entry point, causing a link failure and zero automatic points for that problem.

Online grading#

Online functional tests use ASan and UBSan. A detected memory error or undefined behavior fails the affected test item, without a separate sanitizer penalty. Both harnesses directly check unreleased allocations rather than relying on LSan's exit scan; P1 also checks node allocation and release behavior.

Sanitizer checks do not replace the per-problem clang-format 18 gate or the repository rules. Run make clean before submission; nonempty build/ directories are prohibited.

Before you submit

Code Style and Repository Rules

Your code must follow the Recitation 0 clang-format configuration, just as the starter and teacher code do.

Naming#

Use descriptive names that explain what each value or function does. Short coordinate names (x, y) and loop indices (i) are fine. Keep system and third-party API names unchanged.

Kind Rule Examples
Struct/enum types and type aliases UpperCamelCase SnakeNode, Game, StepResult
Struct members m_ plus lowercase words separated by underscores m_head, m_next, m_gap_y
Functions lowerCamelCase snakeInit, advancePipes, scorePassedPipes
Local/file variables and parameters lowerCamelCase headCol, game, nextPos
Constants and macros UPPER_SNAKE_CASE PIPE_WIDTH, RANDOM_MODULUS, MIN_BOARD_SIZE
typedef struct SnakeNode {
    Coord m_pos;
    struct SnakeNode *m_next;
} SnakeNode;

int scorePassedPipes(Game *game);

No magic numbers#

Use meaningful constants or enums for speeds, gravity, sizes, tolerances, intervals, capacities, and protocol states. Check snake.h and flappy.h first; do not repeat a parameter as a raw number or give it a meaningless name like NUMBER_8.

In P2, use BIRD_WIDTH, BIRD_HEIGHT, PIPE_WIDTH, PIPE_GAP_HEIGHT, PIPE_COUNT, and PIPE_SPEED. Write pipe movement as PIPE_SPEED * dt instead of repeating a numeric speed. Two numbers that happen to have the same value for different reasons should not share one constant.

You may write 0, 1, or 0.5 (or / 2) directly when they express a mathematical relationship: zero initialization, comparing with zero, adding or subtracting one, or taking a half. Keep colors, pixel art, file-format data, and test inputs grouped together with clear meanings or units rather than scattering game parameters through your logic.

Structure and memory ownership#

  • Write standard C17 code with 4-space indentation and a 100-column line limit.
  • Put braces around if, else, for, and while bodies, and write one statement per line.
  • Leave a blank line between functions. Split long conditions into named boolean variables when that makes them easier to read.
  • Use static helper functions for distinct subtasks, but do not split every single line into its own function.
  • Write comments that explain ring-link rules, boundary cases, units, and failure handling. Remove or update finished TODO comments.
  • Keep the provided types, struct members, function names, and signatures unchanged. Do not modify the course framework to work around a requirement.

Memory ownership in Problem 1#

  • Release every allocation you own exactly once. Do not access freed memory.
  • Follow the initialization, failure rollback, and destruction contracts in P1.

Required online format gate#

The online grader checks your source files with clang-format 18 using the teacher's Recitation 0 configuration. It checks each problem independently, including any C helper .c and .h files you add. The grader ignores any .clang-format changes or overrides in your repository.

Important: A formatting failure acts like a compilation failure for that problem: that problem receives zero automatic points, while the other problem is graded independently. The grader shows the offending file and diff, does not modify your code for you, and skips that problem's functional tests until you fix the formatting and resubmit. Do not change .clang-format or use clang-format off/on comments to bypass the check.

The supplied .clang-format in hw4/ is:

Language:        Cpp
BasedOnStyle:    LLVM
IndentWidth:     4
AccessModifierOffset: -4
ColumnLimit:     100

Language: Cpp is intentional and applies to both C and C++ files in clang-format. Do not change it to C. Both p1/ and p2/ share this root configuration.

To format your files from the command line, run from hw4/:

clang-format-18 -i p1/snake.c p2/flappy.c

Remember to include any extra student .c and .h files you created.

Tip: Using VS Code is optional. If you use VS Code, open hw4/ as the workspace folder and install the Microsoft C/C++ extension. The supplied .vscode/settings.json enables format-on-save automatically, or you can run Format Document manually. If your editor's built-in formatter disagrees with the online grader, run clang-format-18 directly.

Passing the format gate is a prerequisite, not a separate point item. Teaching staff still review naming, constants, code organization, and resource ownership during manual grading.

Compile and check with sanitizers#

Build with the provided Makefiles and fix all compiler warnings. Then build the sanitizer-checked executables from hw4/ and test both games:

The online grader adds -Werror, so compiler warnings become build errors there. Fix every warning locally before submitting.

make debug
(cd p1 && ./build/snake-debug)
(cd p2 && ./build/flappy-debug)

Design your own boundary tests and check memory ownership as well as gameplay. See Debugging for sanitizer commands, reports, and platform limits.

Repository contents and extensions#

You are welcome to add helper source files, headers, notes, normal assets, and creative game variants. Adding extra files or directories does not lose points on its own; large structural changes or edits to course framework files simply trigger a staff review notice.

You must keep the required file paths and public interfaces intact and stay compatible with the teacher's C17 framework. Missing required source files, incompatible signatures, or compilation errors give the affected problem zero automatic points. Extra features must not break the required core behavior.

Where to place extra files#

  • Graded helpers: Put helper .c and .h files used by your solution inside p1/ or p2/ (or a subdirectory such as p1/helpers/). The grader format-checks and compiles added C logic files with your solution. Remember to add them to your local Makefile and verify that the full game still builds.
  • Standalone drivers and extensions: Put independent test programs or extra entry points (files with their own main) in p1/extras/, p1/extensions/, p2/extras/, or p2/extensions/. The grader does not link those directories with the teacher's test runner, but any student C code inside them must still pass clang-format-18. The provided terminal UI and physics files are not treated as added student logic.

Important: A custom driver with its own main must go in the problem's extras/ or extensions/ directory, not directly in p1/ or p2/. Otherwise the grader links it with its own test entry point, causing a link failure and zero automatic points for that problem.

Prohibited files#

Important: Submitting a nonempty build/ directory at any depth, compiled artifacts, or any prohibited generated/cache file listed below gives zero for the entire automatic 80 points. Fix the repository and resubmit. An empty build/ directory is allowed, but a build/ containing even .gitkeep counts as nonempty.

Do not commit or submit any of the following:

  • Compiled artifacts and binaries: object files, static/dynamic libraries, or executables (including executables with no file extension, such as a.out), and any file matching *.o, *.obj, *.a, *.so, *.dylib, *.dll, *.exe, *.class, *.pyc, or *.pyo.
  • Caches, build trees, and tool directories: __pycache__/, .pytest_cache/, .mypy_cache/, .ruff_cache/, .cache/, .idea/, node_modules/, .venv/, venv/, ipch/, CMakeFiles/, cmake-build-*/, CMakeCache.txt, cmake_install.cmake, and compile_commands.json.
  • Editor, OS, and local temporary files: *.swp, *.swo, *.swx, .snake-ui.conf, .DS_Store, __MACOSX/, ._*, Thumbs.db, desktop.ini, a.out, and *~.
  • Downloaded archives: HW4_student_starter.zip and HW4_gradescope.zip. Also keep the demo download HW4_demos.zip and its extracted hw4-demo/ folder out of your repository: the programs inside are compiled executables.

The supplied .vscode/settings.json, .clang-format, and PNG/SVG figures are allowed, as are normal new assets such as images. Binary asset formats such as images are not treated as compiled executables just because they are binary files.

The two zero-score gates have different effects:

  • Formatting failure zeroes only the affected problem (P1 or P2).
  • Prohibited repository contents zero the entire automatic 80 points across both problems.

Manual grading items are explained in Grading.

Before you submit#

.gitignore ignores common generated files, but it does not untrack files that you already committed with git add. An untracked local build on your disk is not sent to GitHub, whereas a tracked generated file stays in your submission even if it matches .gitignore.

Run these commands from hw4/ before every submission:

make clean
clang-format-18 -i p1/snake.c p2/flappy.c
git status --short
git ls-files
  • Confirm clang-format-18 has formatted p1/snake.c, p2/flappy.c, and any extra student .c or .h files.
  • Check git status --short and git ls-files to make sure Git is not tracking any nonempty build/ directory, compiled binary, prohibited cache, or downloaded archive listed above. Keep local debug logs outside the repository too.

How it is assessed

Grading

Homework 4 is worth 100 points: 40 automatic points for Problem 1, 40 automatic points for Problem 2, and a separate 20 points for the staff check and code organization. There are no separate objective questions. Submit your GitHub repository to HW4_programming.

  • Automatic tests: 80 points total (40 in P1, 40 in P2).
  • Manual assessment (staff check and code organization): a separate 20-point block.

Problem 1: Circular-list Snake (40 automatic points)#

Item Points What is checked
Initialization 6 Positions, direction, length, valid ring, partial-allocation cleanup
Next position 4 Four directions, reverse/invalid requests, no mutation
Cell query 4 Empty/one-node/full ring, occupied and absent cells, traversal ends
Movement and growth 16 Tail reuse, one-node growth, wall/body collisions, tail-cell rules, failure rollback
Destroy 6 Full release, empty and repeated cleanup, no double free or use after free
Random state 4 Default state/consecutive calls (2), reseeding/range/full period (2)

Problem 2: Flappy Bird (40 automatic points)#

Item Points What is checked
Advance pipes 10 Movement/zero time (3), recycling after all movement (3.5), several slots/exact off-screen edge (3.5)
Collision 14 Top/floor bounds (4), both pipe rectangles (5), safe gaps and touching edges (5)
Score new passes 12 One pass/no double count (3), multiple passes/strict edge (4.5), reused slot scores again (4.5)
Random state 4 Default state/consecutive calls (1.5), reseeding/large seeds (1.5), range/full period (1)

Gates and memory checks#

Important: Two online gates run before functional grading:

  • Per-problem format gate: Each problem must pass the teacher's clang-format 18 check before its functional tests run. A formatting failure gives that problem 0 automatic points and prints a file and diff report, while the other problem is graded independently. Fix the formatting and resubmit. Grading-environment errors are reported separately from student formatting errors.
  • Repository-wide cleanliness gate: A nonempty build/ directory (at any depth; even .gitkeep alone counts as nonempty), compiled artifacts, or explicitly prohibited generated/cache files give 0 for the entire automatic 80 points. An empty build/ directory is fine.

Adding extra source files, normal assets, or creative game variants does not lose points for file count or directory layout alone; large structural changes simply trigger a staff review notice. You must still preserve all required file paths and public interfaces. See Code style and repository rules for the full list of prohibited files.

The online grader compiles with -Werror: compiler warnings are build errors and give the affected problem zero automatic points. Fix all warnings locally; the starter Makefiles do not enable -Werror.

Online functional tests run with ASan and UBSan enabled. Memory errors and undefined behavior fail the functional test items where they occur; the same bug is not deducted a second time under a separate sanitizer category. Build with make debug and test boundary states locally. Memory leak checks also matter; see Debugging.

Staff check and code organization (20 points)#

Manual item Points
P1 staff check 6
P1 code organization 4
P2 staff check 6
P2 code organization 4

Teaching staff review the last version you submitted. Manual items stay pending on Gradescope until staff complete their review.

  • P1 staff check (6 points): An in-person check on your last submission where you must explain and modify your own code.
  • P2 staff check (6 points): An in-person check on your last submission where you must explain and modify your own code.
  • Code organization (4 points per problem): Staff review your naming, named constants, comments, helper functions, function responsibilities, and resource ownership. Because clang-format is already enforced by the online gate, formatting is not deducted again here.

General notes#

  • Core data structures and responsibilities: P1 must use a genuine circular linked list with valid node connections. P2 is graded on advancePipes, birdHitsObstacle, scorePassedPipes, and nextRandom; the provided framework handles input and bird physics.
  • Independent random tests: The online nextRandom tests run separately for P1 and P2.
  • No unlimited error stacking: Memory errors count under the functional test items they affect; deductions are not stacked without limit for the same underlying issue.
  • Local environment choices: Terminal, editor, font, and color differences do not lose points. You do not need any specific workspace file. Always test against the provided framework, because online grading calls the required logic functions directly.
  • Extensions: Extra features and visual decoration are welcome, provided they do not replace the required public interfaces or break core behavior when linked with the teacher's framework.