1. Home
  2. Explore
  3. Computer Science
  4. Modularity in Game Development

Study methods

Flashcards
Quiz
Fill in the blanks
Written test
Lesson
Notes
Podcast
Content

Modularity in Game Development

Speaker 1Speaker 2

Modularity in Game Development

21:45
0:00-21:45
  1. Anna

    You want to build a game, but where do you start when a finished game might contain thousands—or even millions—of lines of code? Putting all of that into one file would make it hard to navigate and even harder to debug. The key idea is modularity: break a large problem into smaller, related pieces.

  2. Corey

    So rather than thinking, “Build an entire role-playing game,” we can divide it into activities like farming, fishing, mining, and crafting. Then divide each activity again. Farming might include planting, fertilizing, watering, harvesting, and even trampling.

  3. Anna

    Exactly. Once the problem is mapped out that way, we can solve one sub-problem at a time. For instance, we might work out what harvesting means and write a small piece of code that returns a random number of vegetables based on how well the player cared for a plant. That’s much more manageable than solving all the farming mechanics—or the whole game—at once.

  4. Corey

    And modularity helps in several ways. It supports collaboration: one team can work on farming while another works on fishing, and within farming, one person can handle harvesting while someone else handles planting. The components will need to be integrated eventually, but people can focus on their tasks without constantly conflicting with each other’s code.

  5. Anna

    It also makes testing and debugging easier. Asking whether an entire game works is a huge question. Asking whether one small harvesting function works is much easier to answer. It’s like a mechanic checking a car’s brakes, transmission, and heating and cooling system individually instead of just driving around and waiting for something to break.

  6. Corey

    And if the smaller components have each been tested as they’re built, we can be more confident in the complete product. Organization also improves readability: code arranged by task is easier to find than one giant tangle of instructions.

  7. Anna

    In Python, a common structure is to group related functionality in a module—a file containing code for a related set of tasks—and then organize the individual tasks inside that module into functions. A farming module, for example, might have a harvest function and a plant function.

  8. Corey

    We’ve already used modules and functions written by other people. The random module gathers functionality related to randomness, and it offers functions such as randint. As our own programs grow, we need to create functions and modules too, so our code can be more reusable, testable, and maintainable.

  9. Anna

    Let’s begin with functions. A function is a named block of code that performs a specific task. You define the instructions once, give them a name, and then call that name whenever you want to perform the task again. That prevents you from rewriting the same code at multiple points in a program.

  10. Corey

    A function often takes input values, does something with them, and returns an output value. Inputs let the function handle different cases: a rounding function could round different numbers to different numbers of decimal places, for example. Each call can use different inputs, and the call expression evaluates to the value the function returns.

  11. Anna

    In Python, a function definition starts with def, then the function’s name, parentheses, and a colon. That first line is the function header. We put the names of the function’s inputs inside the parentheses; those names are called parameters. They work like variables, but they’re available within the function body.

  12. Corey

    The function body contains the instructions for the task—ordinary code such as assignments, conditionals, or loops. We indent those instructions under the header so Python recognizes them as belonging to the function. When the function needs to produce an output, it uses return followed by the value to send back.

  13. Anna

    Defining a function teaches the computer what the task is, but it doesn’t perform the task yet. To do that, we call the function by writing its name and parentheses, with the input values inside. Those values are called arguments. A function definition must appear before the program reaches a call to that function, so the computer has learned the task before being asked to do it.

  14. Corey

    When a call runs, the arguments are matched to the parameters in order. You can think of that as assigning each argument’s value to its corresponding parameter. Then Python executes the function body. At return, it leaves the function and goes back to the line where the call happened, with the returned value.

  15. Anna

    That’s useful in an adventure game with potions. If potion-handling conditionals have been copied all over the program, we can put the behavior in one drink_potion function. It can take the potion color as a parameter and return the number of health points affected.

  16. Corey

    Then, wherever the player drinks a potion, we call that function with the selected potion as its argument. If we later add a blue potion, we update the one function definition rather than searching through every duplicated conditional. The function lets us solve the potion problem once and reuse the solution.

  17. Anna

    There’s another way to picture execution. When Python reads a def statement, it stores the function’s instructions and associates them with the function’s name and its parameter count. It has learned a task, but it does not execute the function body at that moment. After the definition, Python continues with the next top-level instruction.

  18. Corey

    When a function is called, Python creates a new stack frame: a separate area of short-term memory for that particular call. It copies the argument values into that frame, names them after the corresponding parameters, and executes the body there. The frame keeps that function’s temporary information separate from the larger program.

  19. Anna

    At return, Python evaluates the return expression, sends that value back to the call site, and clears the function’s stack frame. The call expression is replaced, so to speak, by the returned value. The surrounding program can then store that value in a variable or use it in another expression.

  20. Corey

    If a function returns a value and the program doesn’t use it, the calculation still happens, but the value is discarded. That’s generally wasted work. Also, user-defined functions are stored for that program execution; the computer doesn’t remember them after the program ends, so the definition must be run again next time.

  21. Anna

    That stack-frame idea leads to scope. Scope means the region of a program where a name can be accessed. Names defined at the top level of a program are in global scope. Names assigned inside a function—including its parameters—are local to that function call.

  22. Corey

    A local variable with the same name as a global one doesn’t overwrite the global variable. They live in separate regions of memory. When the function returns, its local stack frame is popped away, so those local variables disappear. That’s why assigning to a variable inside a function won’t, by itself, update a same-named global variable.

  23. Anna

    The dependable way for a function to communicate a result back to its caller is to return it. The caller can then store the result in its own scope. Python does provide a global keyword to refer to a global variable from inside a function, but good practice is to avoid relying on that in most cases.

  24. Corey

    Why? Imagine if every function’s variables and parameters were global. Every name would have to be unique across the whole program, even across thousands of lines and many files. Local scope lets different functions reuse names safely without accidentally overwriting one another’s values.

  25. Anna

    A function can read a name from an enclosing scope if the name isn’t defined in its local scope. Python searches the closest scope first, then moves outward; if it finds the name globally, it can use that value. But relying on an unannounced global variable makes a function harder to trust, because a caller may not know the function requires that variable to exist.

  26. Corey

    It’s safer to make required information explicit. If a damage calculation needs a maximum-damage threshold, pass that threshold as a parameter instead of silently reading a global. A useful mental model is that a function is an input-output machine: arguments bring information in, return values carry information out, and what happens in between is local.

  27. Anna

    Functions can call other functions, too. When an outer function calls an inner one, the computer pauses the outer function, creates another stack frame on top of the first, and executes the inner function. The outer frame stays in place because the outer function hasn’t finished yet.

  28. Corey

    When the inner call returns, its frame is removed and execution resumes in the outer function. This can happen several levels deep: each call adds a frame to the top, and each return removes the top frame. If information needs to move through several calls, one function can pass it along as an argument to the next.

  29. Anna

    Why break work into several functions instead of making one enormous function? Consider a sneaking mechanic in a game. Detection depends on the volume of the player’s footsteps, which depends on movement—crouching or running—and on the environment, such as grass or metal.

  30. Corey

    One giant function could calculate movement volume, adjust it for the environment, and compare it with a random detection threshold. But the function would be doing several different jobs. Its name might not make all those jobs clear, it would be harder to test each part, and it would be harder to reuse the pieces.

  31. Anna

    So we can create a function that adjusts a base volume for the player’s movement, and another that adjusts volume for the environment. Each does one specific job and returns the adjusted volume. We can test them independently: crouching should produce a lower volume than running, for example.

  32. Corey

    Then we can use a wrapper function, perhaps get_footstep_volume, to combine those calculations. We can keep the detection check separate in an is_detected function that takes a volume and returns a Boolean. Descriptive function names can explain the code, reducing the need for comments.

  33. Anna

    That separation also makes reuse easier. If the player’s voice can give them away, we can reuse the environment adjustment and the detection check with a voice-volume calculation. The code already has useful pieces, so adding the feature takes less work.

  34. Corey

    Here’s a second design example: a program for several card games. We can make a draw_card function, then a draw_hand function that takes the desired hand size, repeatedly draws cards in a loop, and gathers them into a hand. A newline character, written as backslash-n, can put each card on its own line for readability.

  35. Anna

    To make draw_card return a random card, we can break that task down again. A card has a suit and a rank, so we can use a get_suit function and a get_rank function. The random module can help choose among four suits—hearts, diamonds, spades, and clubs—and get_rank can choose among thirteen possible ranks.

  36. Corey

    For ranks, one can represent ace as one, jack as eleven, queen as twelve, and king as thirteen, while the other numbers are represented by their numbers. But be consistent about return types. If the face-card cases return strings but an ordinary rank returns an integer, concatenating the card pieces can cause a TypeError. Convert the number to a string before returning it.

  37. Anna

    Some games may not use face cards. We can represent that option with a Boolean parameter. If face cards are disabled, choose a number from two through ten. The caller decides whether the option is enabled, and that choice can be passed through draw_hand to draw_card and then to get_rank.

  38. Corey

    One limitation of this simple design is that the deck has no state. It can generate the same card more than once, so a hand might contain two ace of spades. That could be fine for games using multiple decks or where repeated cards are acceptable, but it would be wrong for a game that requires one of each card. Whether the simplification is appropriate depends on the use case.

  39. Anna

    As programs grow, even a well-organized collection of function definitions can crowd the main logic in one file. We can move related functions into another Python file, which is called a module. A module is simply a file with a .py extension; for instance, we might put arcade-game functions in arcade.py.

  40. Corey

    After moving the functions, the main program won’t automatically know their names. We need to import the module. Then we refer to one of its functions with the module name, such as arcade dot get_score. That module prefix tells Python where to find the function.

  41. Anna

    A program may have many files, but only one file is specified to run directly. That’s the entry point, or main logic; by convention, Python programs commonly call it main.py. Code in other modules runs when it is reached through the chain of imports and function calls that begins at that entry point.

  42. Corey

    An import makes Python execute the imported module’s top-level code, then return to the importing file. It can feel like copying the module’s contents into the program, but names are kept in the module’s own scope. So arcade.get_score is a two-step lookup: first find the arcade namespace, then find get_score inside it.

  43. Anna

    That module scope avoids name conflicts. You and another programmer can both define a function called get_score in different modules, because each name belongs to its own module. It’s also wise to keep module-level code mostly to definitions: a top-level print statement runs whenever the module is imported, which can make output confusing when modules import other modules.

  44. Corey

    Modules are a convenience for programmers. They group related functions, make a program easier to navigate, and let us reuse a package of functionality in multiple places. They also help us focus: in main.py, we can work on how the big pieces fit together; in inventory.py, we can concentrate on inventory details.

  45. Anna

    Let’s see modules and functions together in a small Nim game. Players take turns removing one or two stones, and whoever removes the last stone loses. We can put game-related functions in stones.py and keep the main loop in main.py.

  46. Corey

    In stones.py, we might define pick_for_user and pick_for_computer. The user function prompts for a choice and uses a loop to keep asking until the user enters one or two. The computer function can begin with a simple choice, such as always picking one, while we build the rest of the game.

  47. Anna

    In main.py, initialize the pile and use a while loop that continues while stones remain. On a user turn, call stones.pick_for_user and subtract the chosen number. But the computer should not take a turn after the user removes the last stone, so the players need to alternate rather than both acting unconditionally on each loop iteration.

  48. Corey

    A Boolean can track whose turn it is: true for the user, false for the computer. At the bottom of each iteration, switch it to the other player. When the loop ends, that turn variable has already been switched, so it indicates the player who did not take the final turn; the other player removed the last stone and therefore lost.

  49. Anna

    We can make the game easier to play by printing the rules, displaying the pile, and reporting the winner. A show function can take the number of stones and return a picture of the pile, perhaps with a circle for each stone and a number so the pile is easier to count. Keeping display work in its own function means we can adjust the picture without changing the main game logic.

  50. Corey

    Randomizing the starting pile makes repeated games less predictable. We can also improve the computer’s move using the number of stones left. With one stone, it has to pick one; with two, picking one leaves the opponent the last stone; with three, picking two does the same.

  51. Anna

    Four stones are a losing position for the player whose turn it is, because either choice lets the opponent leave them with the last stone. So, if the computer can leave its opponent four stones, it has a winning position. With five stones it can pick one, and with six it can pick two, leaving four.

  52. Corey

    That gives us some cases for the computer’s algorithm: pick one when there are one, two, or five stones; pick two when there are three or six; and choose randomly otherwise in this version. The larger numbers can be analyzed further—eight and nine, for example, are left as an exercise. The important design lesson is that the strategy can be improved inside its own function.

  53. Anna

    Now, how do programmers keep large programs from breaking as many people make changes? Testing. Tests can take forms such as performance tests and end-to-end tests, but a common kind is the unit test, which checks one unit of functionality—often a single function.

  54. Corey

    A unit test encodes a requirement. It calls a function with particular arguments and checks whether the result matches an expected value. If it does, the test passes; if it doesn’t, the test fails. Teams can automate tests to run when code changes and prevent a change from being submitted until the relevant tests pass.

  55. Anna

    That makes tests a living contract for a function’s expected behavior. If a function is wrong, we can fix it to meet the existing requirement. Or, if the intended behavior has genuinely changed, we can update the test along with the code so the new expectation is explicit.

  56. Corey

    Choosing good tests matters. One test isn’t enough: a broken function that always returns four might pass a test expecting four for one input. Testing every possible input may be impractical too. Instead, aim for code coverage: choose representative inputs that exercise every meaningful path through the function.

  57. Anna

    For a function with branches based on train counts, for instance, we’d want test inputs for each branch: two or fewer trains, three, four, and five or more. That helps us check different classes of input, not just one convenient example. Testing isn’t perfect, and time may limit coverage, but when a bug is found, add a test for that exact failure so it’s less likely to recur.

  58. Corey

    Python programmers commonly use the unittest or pytest modules, and the precise syntax depends on the framework. A test suite may contain several similar cases that differ mainly in their names, inputs, and expected results. The framework can report which test failed and what result it got instead of what was expected.

  59. Anna

    A lot of test code is repeated boilerplate, so programmers may copy and adapt it. The more valuable skill is identifying meaningful cases. If you’re learning independently, writing automated tests for every little program may take as long as writing the program itself; still, it’s a good habit to try functions with several inputs and check the results.

  60. Corey

    That basic checking builds confidence in individual pieces. Then, if an error appears later as you assemble the whole program, you can rule out functions you’ve already checked and focus your debugging effort.

  61. Anna

    Let’s apply that to a racing game. Two cars move forward by random amounts each round on a straight track, and the first car past the end wins. The game loop moves the cars, prints the race status, and displays the track. A bug seems to make cars disappear near the end, so instead of guessing, we test the display function by itself.

  62. Corey

    We try cases where the first car is ahead, the second car is ahead, both cars are in the same position, and one car has moved beyond the track’s length. Isolating the function makes the issue easier to see: the car disappears when its position is beyond the track, and the shared-position case displays only one car.

  63. Anna

    For the first bug, the drawing loop stops at the track length. If a car goes farther, we need to keep drawing far enough to show it. So the end of the range should be based on the greatest of the track’s end and both cars’ positions—not just the track length.

  64. Corey

    Then we can check both cases where either car is furthest. For the cars sharing a position, we need to decide what the display should mean. One option is a distinct symbol, such as X, for a space occupied by both cars.

  65. Anna

    The symbol-selection function needs to check that the cars have the same position and that the position currently being drawn is that shared position. If we only check that car one and car two match, we’d draw an X on every segment. Checking that the current position also equals their position fixes that mistake.

  66. Corey

    Once all four test cases pass, we have stronger evidence that the display function handles those situations. We can put the game back together and continue testing. The broader debugging method is to narrow a symptom down to one function, test representative inputs, identify what the function should do, and then fix and retest it.

  67. Anna

    So the thread connecting all of this is decomposition. Break a large program into modules, modules into functions, and functions into clear, specific tasks. Pass information in through arguments, return results instead of depending on hidden global state, and test the pieces as you build them.

  68. Corey

    That structure makes code easier to read, reuse, collaborate on, and debug. And when the pieces work independently, combining them into a larger game becomes much less overwhelming.

Ask anything

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

FlashcardsQuizFill in the blanksWritten testLessonNotesPodcastContent