Modularity in Game Development
Organizing Programs with Functions, Modules, and Tests
Modularity: breaking a large problem into smaller parts
A large program can contain thousands or even millions of lines of code. Keeping all of that code in one file makes it difficult to navigate, understand, test, and debug. Modularity addresses this problem by dividing a large program into smaller components, each responsible for a related part of the overall task.
For example, a role-playing game might be divided into activity areas such as farming, fishing, mining, and crafting. Farming could then be divided into specific actions such as planting, watering, fertilizing, and harvesting. Instead of attempting to build the whole game at once, a programmer can work on one action or component at a time.
A useful hierarchy is:
Large program: the complete game.
Component: a major area, such as farming.
Sub-problem: a particular action, such as harvesting.
Implementation: the code that performs that action.
A harvesting feature, for instance, might return a random number of vegetables based on how well a plant was cared for. Designing that one behavior is more manageable than designing all farming mechanics at once.
Benefits of modularity
Collaboration: Different programmers or teams can work on separate components. One person might develop farming while another develops fishing; within farming, separate people might work on planting and harvesting. The pieces can be integrated later.
Testing and debugging: A small component is easier to test than an entire application. Testing harvesting in isolation makes it easier to identify whether that specific behavior works.
Readability: Code organized by purpose is easier to navigate than one large, undifferentiated block. A programmer can look in the relevant area when searching for a feature.
Maintainability: Changes to one component are less likely to require edits throughout the entire program.
Reuse: A well-designed component can be called from multiple parts of the program rather than recreated each time.
Testing components separately is similar to checking a car’s brakes, transmission, and heating system individually rather than driving for hours and waiting for something to fail. When the components work correctly, there is greater confidence in the assembled system, although the integrated system still needs testing.
Programs are commonly organized using modules and functions. A module groups related functionality, often in a file. A function groups the instructions for one specific task. For example, a farming module might contain separate functions for planting and harvesting.
Functions: named, reusable tasks
A function is a named block of code that performs a specific task. It gives a name to a set of instructions in much the same way that a variable gives a name to a value. A function can be defined once and called repeatedly, avoiding duplicated code.
Functions often follow an input-process-output pattern:
Receive input values.
Perform an operation using those values.
Return an output value, if one is needed.
Inputs allow a function to handle different cases. A rounding function, for example, can work with different numbers and different numbers of decimal places. A potion function can handle potions of different colors.
Defining a function
In Python, a function definition begins with the keyword def, followed by the function name, parentheses, and a colon. The function’s parameters go inside the parentheses. The indented statements below the header form its body.
def get_greeting(days_since_spoken, catchphrase):
if days_since_spoken < 1:
greeting = "Oh, it's you again"
else:
greeting = "Always good to see you"
return greeting + ", " + catchphraseThe components of a definition are:
Function header: The line beginning with
def. It specifies the function’s name and parameters.Parameters: Names listed in the header that receive input values. They behave like variables inside the function.
Function body: The indented instructions that perform the task. The body can contain assignments, conditionals, loops, and other ordinary code.
Return statement: The
returnkeyword sends a result out of the function and ends that function call.
A function may also finish without an explicit return; in Python, such a call returns None. When a function is intended to produce a useful result, its return behavior should be clear and consistent.
Calling a function
A function call executes a function. It uses the function’s name and parentheses, with input values supplied inside the parentheses.
The values supplied in a call are called arguments. The parameters are the corresponding names in the definition. When a function is called, each argument is bound to its matching parameter. In ordinary positional calls, the first argument is assigned to the first parameter, the second to the second, and so on.
For example, get_greeting(7, "kerPOW") passes 7 and "kerPOW" as arguments. The function uses those values as days_since_spoken and catchphrase. Its return expression evaluates to a string, and the call expression evaluates to that returned value.
A function definition must be executed before a call can use that function. Defining a function teaches the running program what the function does; it does not immediately execute the function body.
Refactoring duplicated code into a function
Suppose an adventure game contains the same potion-related conditional in several places. Repeating the conditional makes the program harder to change: adding a new potion would require finding and updating every copy.
Instead, the potion logic can be placed in a function such as drink_potion. The function can accept the potion’s color and return the number of health points affected. Each place where the player drinks a potion can then call the same function with the selected color.
This approach means that:
Potion behavior is implemented in one place.
A new potion type can be added by changing that function rather than many separate blocks.
Other parts of the game can use the function without needing to know its internal implementation.
Functions therefore let a program solve a small problem once and reuse the solution wherever it is needed.
What happens during a function call
A running program executes instructions in order. When it encounters a function definition, it records the function’s instructions, name, and parameter information so that the function can be called later. It does not execute the body just because the definition has been encountered. After recording the definition, execution continues after it.
When a function call occurs, the computer:
Finds the function definition.
Creates a new stack frame, a separate region of short-term memory for that particular call.
Copies the argument values into that frame and associates them with the corresponding parameters.
Executes the function body.
Evaluates the return expression, if there is one.
Ends the call, removes its stack frame, and resumes execution at the line that made the call.
A stack frame keeps a function call’s local variables separate from the surrounding program. When the function returns, its local frame is discarded. A returned value can still be used by the caller because that value is passed back as the call expression’s result.
For example, a returned string can be assigned to a variable in the calling scope. If a function’s result is not assigned, printed, or otherwise used, the computation still occurs, but the result is discarded. Calling a function whose result is unnecessary may therefore waste work.
Repeated calls and program lifetime
Each function call gets its own execution context. Calling the same function again creates another frame for the new call; values from an earlier call do not remain as local variables in the new one.
User-defined functions also do not persist after a program ends. Each new program execution must run the relevant definitions again so that the program knows those functions.
Variable scope: where names can be used
A variable’s scope is the region of a program in which its name can be accessed. Scope determines which values a function can see and where assignments take effect.
Global scope
Names defined at the top level of a program are in global scope. They belong to the surrounding program rather than to one function and can generally be accessed from different parts of that program.
Local scope
Names created inside a function, including its parameters and variables assigned in its body, are in that call’s local scope. They exist in the function’s stack frame and disappear when the function returns.
If a function assigns to a name, the function normally creates or updates a local variable of that name. It does not automatically change a global variable with the same name. Thus, a local variable named damage can coexist with a global variable also named damage.
This separation prevents functions from accidentally changing unrelated parts of a program. It also allows different functions to reuse simple, descriptive names without requiring every variable and parameter across an entire codebase to have a unique name.
A function’s local variables are private to its call. The clearest routine way to communicate results outward is to return a value.
Looking up names in enclosing scopes
When Python looks up a name inside a function, it searches the local scope first. If the name is not found there, it can search an enclosing scope, such as the global scope. If no matching name is found, Python raises a NameError.
A function may therefore be able to read a global value without defining it locally. However, relying on hidden global dependencies is risky: the function’s behavior depends on a value that is not visible in its parameter list, and a caller may not know that the global value must exist or be initialized correctly.
A safer design passes required information through parameters. For example, if a damage calculation needs a maximum damage threshold, that threshold can be an explicit parameter rather than an assumed global variable.
Python also provides the global declaration for situations where a function must assign to a global name. This is rarely recommended for ordinary program design because it makes state changes less visible and increases the chance of conflicts.
Functions as input-output machines
A reliable mental model is to treat each function as an input-output machine:
Inputs arrive through arguments and are bound to parameters.
Processing takes place using local variables.
Outputs leave through the return value.
This design makes dependencies clear and reduces accidental interference with the rest of the program.
Nested function calls and function composition
A function can call another function from inside its body. In that case, the outer function pauses while the inner function runs.
The computer creates a new stack frame for the inner call on top of the outer function’s frame. The outer frame remains available because its work is unfinished. When the inner function returns, its frame is removed and execution resumes inside the outer function at the point where the inner call was made.
This process can repeat across several levels:
A main program calls function A.
Function A calls function B.
Function B returns to A.
Function A finishes and returns to the main program.
Each frame preserves the local state of one active function call. Values can be passed through several levels by accepting them as parameters and forwarding them as arguments.
Why divide a large function into smaller functions?
Consider a game in which guards detect a player based on the volume of their footsteps. Footstep volume depends on both the player’s movement and the environment: crouching on grass is quiet, while running on metal is loud. A single large function might calculate movement volume, adjust for the environment, compare against a random detection threshold, and return whether the player was detected.
Although that function has a name, it performs several distinct tasks. This creates three problems:
Readability: The function name may not reveal all the work hidden inside its body.
Testing: A final detection result can be hard to diagnose without seeing the intermediate volume.
Reuse: Other features may need only one of the operations, such as adjusting sound for an environment.
A more modular design separates those responsibilities:
A movement function adjusts a base volume according to movement type.
An environment function adjusts a volume according to the surface or surroundings.
A footstep-volume function combines the movement and environment calculations.
A detection function compares a volume with a threshold and returns a Boolean.
The larger behavior can be assembled through calls to these smaller functions. Their names can also serve as documentation: a clearly named function often makes an explanatory comment unnecessary.
This design supports reuse. For example, a player’s voice might also be affected by the environment. The same environment-adjustment function can be reused for voice volume, and the independent detection function can evaluate the resulting volume without tying detection specifically to footsteps.
Designing a card-drawing program with functions
A card-game program can be divided into functions for drawing a card, drawing a hand, choosing a suit, and choosing a rank.
Drawing a hand
A hand-drawing function can accept the number of cards as a parameter and repeatedly call a card-drawing function. It can collect the resulting card strings and return them as one formatted string.
A loop is suitable because the number of draws depends on the requested hand size. Adding a newline character between card strings places each card on a separate line, improving readability when the hand is displayed.
Testing the hand function with several different hand sizes checks whether it handles different parameter values rather than only one case.
Choosing suits and ranks
A card has a suit and a rank. The suit function can choose among hearts, diamonds, spades, and clubs with equal likelihood. A rank function can select among thirteen possibilities: ace, numerical ranks two through ten, jack, queen, and king.
A rank-selection strategy can use a random number from one through thirteen:
One represents ace.
Eleven, twelve, and thirteen represent jack, queen, and king.
Other values represent their numerical ranks.
If the function returns face-card names as strings but returns ordinary ranks as integers, callers may encounter a type error when trying to combine the result with a string. A function should have a consistent return type whenever practical. In this case, numerical ranks should also be converted to strings before being returned.
Optional behavior through parameters
Some games exclude face cards. A Boolean parameter can express whether face cards are enabled. When they are disabled, the rank function can choose only from two through ten.
If the rank function needs this setting, the card-drawing function must receive it and pass it along. If the hand-drawing function calls the card-drawing function, it must also receive and forward the setting. This illustrates how parameters communicate options through a chain of nested calls.
Modeling choices and limitations
A simple drawing function that chooses a card independently each time does not model the changing state of a physical deck. It may produce the same card more than once in a hand.
That may be acceptable for games that use multiple decks or allow repeated draws under the chosen rules. It is incorrect for games that require exactly one of each card. Whether this simplification is useful depends on the requirements of the program.
Modules: organizing related code into files
A module is a Python file used to group related code. A file with the .py extension can contain function definitions and other Python statements. For example, game-related functions could be placed in arcade.py rather than kept in the file containing the main program logic.
Moving function definitions into a separate file does not automatically make them available in another file. The program must import the module.
Importing and using a module
An import statement tells Python to load a module. A function in that module is generally called using the module name followed by the function name, such as arcade.get_score.
The module name acts as a namespace. This means that two different modules can each define a function called get_score without those names colliding. The caller specifies which one is intended by identifying the module.
At a high level, importing makes the module’s definitions available to the importing program. More precisely, Python creates a module namespace and executes the module’s top-level statements when the module is first loaded. The importing file then refers to the names stored in that namespace.
Entry point and execution flow
A program can include many files, but a run normally begins from one designated file called the entry point. In many Python projects, this file is conventionally named main.py.
Execution can then move through a chain of calls and imports:
The entry point imports a module.
A function in that module may call another function.
That function may depend on another module.
For code to run, execution must reach it through the entry point and the resulting chain of imports and calls. Merely having a file in the project does not mean its functions will be invoked.
When a module is imported, its top-level statements are executed. Therefore, modules are generally best used to define functions and other reusable components, rather than to contain unrelated top-level actions. A top-level print statement, for example, runs when the module is imported and can produce confusing output if many modules do this.
Why modules are useful
Navigation: Related functionality is grouped in a predictable place, such as an inventory module for inventory management.
Reuse: A module’s functionality can be imported by multiple parts of a program.
Reduced naming conflicts: The module namespace distinguishes names defined in different files.
Separation of concerns: The main file can focus on how components work together, while a specialized module can focus on the details of one area.
Functions divide a program by task; modules group related functions into larger areas of responsibility.
Applying functions and modules to the game Nim
Nim can be implemented as a program in which a user and a computer take turns removing one or two stones from a pile. The player who removes the last stone loses.
Separating game behavior into a module
A stones module can contain functions for the user’s move and the computer’s move.
The user-move function can prompt for a number of stones and validate the response in a loop, repeating the prompt until the input is either one or two. In a complete implementation, the input should also be converted to a numeric type before it is used to update the pile.
The computer-move function can be developed in stages: first with a simple fixed choice, then with a strategy that considers how many stones remain.
Main game loop
The main file can initialize the pile and repeatedly play turns while stones remain. On each turn, it calls the appropriate move function and subtracts the number of stones taken from the pile.
A Boolean variable can track whose turn is next:
One Boolean state represents the user’s turn.
The other represents the computer’s turn.
At the end of an iteration, the state changes to the other player.
The check for whether stones remain should control the loop so that a player does not receive a turn after the pile has run out. The order of updating the pile and switching turns also matters when determining who took the final stone and, consequently, who lost.
Displaying the pile
A separate display function can accept the number of stones and return a visual representation, such as a row of circles. A number included in the display can make the pile easier to count. Keeping this rendering logic in a function lets the appearance change without altering the main game loop.
Developing the computer’s strategy
The computer’s move can depend on the number of remaining stones. The strategy begins by reasoning about positions near the end of the game:
With one stone remaining, the computer has to take one and loses.
With two stones remaining, taking one leaves one for the opponent.
With three stones remaining, taking two leaves one for the opponent.
With four stones remaining, either legal move gives the opponent a position from which the opponent can leave the computer with one stone.
With five stones remaining, taking one leaves four for the opponent.
With six stones remaining, taking two also leaves four for the opponent.
The key idea is to try to leave the opponent a position from which every available move leads back to a disadvantage. A first version of the algorithm can handle selected cases explicitly and choose randomly otherwise. Testing several pile sizes can verify that the specified cases return the expected move.
The example strategy is a starting point rather than a complete analysis of every possible pile size. Further reasoning can reveal a repeating pattern and improve the computer’s choices.
Testing functions and programs
A program with many components can remain reliable when its behavior is tested regularly. Unit testing checks one small unit of functionality at a time, most often a single function.
A unit test supplies an input and checks whether the output matches an expected result. For example, a test might assert that a function called with a particular set of resource values returns False. If the actual result matches the expected result, the test passes; otherwise, it fails.
Tests as executable requirements
Tests specify expected behavior in code. A development team can run them automatically whenever a change is made. If a change breaks a requirement, the failing test signals the problem and can prevent the change from being accepted until the issue is resolved.
When a requirement intentionally changes, the test may need to change as well. In this way, tests act as a living contract: they record the behavior the function is expected to provide.
Choosing useful test cases
One test case is rarely enough. A function that always returns the same value might pass one test by coincidence. Testing every possible input may be impractical, so programmers identify meaningful classes of inputs and choose representative examples.
Code coverage describes how much of a program’s code or execution behavior is reached by tests. For function logic with conditional branches, test cases should exercise each important branch. For example, if a route-scoring function handles at most two trains, three trains, four trains, and at least five trains differently, a useful test set includes cases from each of those categories.
Tests should aim to cover the reasonable paths through a function, while recognizing that complete coverage may be limited by time or the complexity of possible inputs. If a bug is discovered later, a strong practice is to add a test that reproduces that exact failure. The test then helps prevent the same bug from returning.
Testing frameworks and manual checks
Python programmers commonly use testing frameworks such as unittest and pytest. Frameworks provide conventions for defining and running tests and reporting failures. The test cases often share repeated setup and assertion syntax, so the central skill is usually not memorizing boilerplate but identifying meaningful cases.
For a beginner working independently, writing automated tests for every small program may take as much time as writing the program itself. Even so, manually calling a function with several different arguments is valuable. It can reveal errors early and establish confidence in a component before it is used elsewhere.
Debugging by isolating a function
A racing game illustrates how function-level tests can narrow down a bug. The game has two cars that move along a straight track. Each round, the cars move forward a random number of spaces, the program displays the race, and the race continues until a car reaches or passes the end.
If a car sometimes disappears from the display, the cause may be in the function that draws the track. Rather than immediately investigating the entire game loop, the display function can be tested independently with representative inputs:
The first car is ahead.
The second car is ahead.
Both cars occupy the same position.
A car has moved beyond the track’s stated length.
These tests help identify which situations produce the faulty output.
Cars beyond the nominal track length
If a car’s position is greater than the track length, a drawing loop that stops at the track boundary will omit that car. The display range should extend far enough to include both the track’s end and the furthest car position. The endpoint can be based on the maximum of the track length and the two car positions.
Cars sharing a space
If both cars occupy the same position, the display function should represent both rather than drawing only one car. A special symbol, such as an X, can indicate the overlap.
The condition for drawing that symbol must check not only that the cars occupy the same position, but also that the currently drawn position is that shared position. Otherwise, the overlap condition would incorrectly draw the special symbol at every position.
Once the isolated display tests pass, the display function can be returned to the full game. This method localizes the fault, makes each expected behavior explicit, and reduces the number of possible causes under investigation.
A reliable debugging process reduces a broad failure to a small, testable unit, checks representative cases, and then reintegrates the corrected component into the larger program.

Ask anything
We've read this whole study set, so questions about it get the best answers.