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

Transcript

- [Instructor] So you wanna build a game, but how would you even get started? Most games we play have thousands of lines of code, some even have millions. Try and imagine a program with thousands of lines of code all in a single file. Sounds like a nightmare to navigate, and nearly impossible to debug. So how do programmers do it? We use a strategy that in programming we call modularity, or in simpler terms, we break down the problem. Say I wanna build a cozy role-playing game. What might that entail? Well, I can kind of break that down into different categories of activities like, there's farming, fishing, mining, crafting, and then within each of those categories, I can break it down further into the different actions players might take. So within farming, you might be able to plant, fertilize, water, harvest, maybe trample. Once I have that breakdown mapped out, I can focus on solving each individual sub-problem in isolation one at a time instead of trying to juggle

all the pieces of the game at once. For example, maybe I start off by thinking about what it means to harvest and then I write the code for that small piece of the game, like, maybe the plant returns a random number of vegetables based on how well the player cared for it over its lifetime. Notice how that small sub-problem was a lot easier to tackle than the bigger problem, build the farming mechanics, and way easier than the big problem of build a role-playing game. By breaking down programs into modular components like this, programmers get a lot of benefits. For one, it allows them to easily collaborate with other programmers. One team can own the farming component and another team can own the fishing component. And within farming, I can work on harvesting and my teammate can work on planting. We'll have to integrate the different components eventually, but for now, it's easy for me to focus on my task without having to worry

about conflicting with my teammate's code. Two, it makes the code much easier to test and debug. If I gave you the whole program and asked, "Does this game work?" I bet you'd have a real hard time giving me a definitive answer. But if instead I gave you a real small piece of code and asked, "Hey, does this harvesting code work?" You could probably verify that without a horrible amount of effort. If we tested all the smaller components as we built them, we can have a lot more confidence that the final product works. It's kind of like a mechanic working on a car. To check if there's any issues, they don't just take the car out and drive around for hours until something breaks down, instead, it's much easier for them to test the individual components. They can check that the brakes work, the transmission works, the HVAC works, and if all the individual components work, then there's a good chance the whole car works too. Three, it makes the code a lot more readable

and easy to work with instead of one giant mess of code, we've organized it based on task, which makes it easier to find what we're looking for when we need it. Typically, when we modularize a program, we organize it into different modules where each module or file contains the code for a related set of functionality. Then within a module, we break down that functionality into individual functions where each function contains the instructions for performing a specific task.

So in our farming module, we might have a function called harvest that contains the lines of code needed to perform the harvest action, and then we might organize the planting-related code into a plant function. Now, we've probably seen modules and functions before when we've used the ones that other people have written, like, the random module collects a bunch of functionality related to randomness and organizes that into functions like randint. As we write programs that get bigger and more complex, we need a way to organize our code too, so we're not left with a single main.py file with a giant mess of code. That means it's time to learn how to write our own functions and our own modules so we can make our code more reusable, testable, and maintainable. So let's get organized.

You are writing a program and it's starting to get pretty long, plus you are duplicating a lot of code because you need to perform the same task at several different points in the program. How can we better keep this code organized and reduce the repetition? We need functions. A function is a named block of code that performs a specific task. There's really not too much special here, it's just normal lines of code that we've packaged up and attached a name to, like a variable gives a name to a value, a function gives a name to a set of instructions. We define the function once and then that name lets us execute the task over and over again without having to rewrite all those lines of code every time. Typically, a function takes in some number of input values, it operates on them in some way, and then if it returns out an output value. The input values allow us to generalize the function's task so it can round any number to any number of decimal points

or drink a potion of any color. Each time we call the function, we can pass in different input values. The function call expression then evaluates down to whatever output value the function returns. To define a new function, we use a function definition. A function definition starts with the keyword def, which stands for define. Then we put the name of our function followed by a set of parentheses, and then like most things in Python, we end it with a colon. We call this whole line the function header. Now we're just missing the input values. We need to specify how many input values the function takes and give each of them a name. We then put those names inside the parentheses. These are called the parameters to our function. Parameters are effectively just variables, but those variables are only accessible within the function body. The function body is all the lines of code that perform the function's task.

These can include any normal lines of code like variable assignments, conditionals, or loops. To tell the computer that these lines of code belong to the function body, we indent them one tab over from the function header. Typically at the end of the function body, we specify the output value that the function returns. To do this, we use the keyword return. Whatever value we put after it will be the output value. Our function definition is now complete, but a function definition just defines how to perform a task. To actually perform that task, we still need to call the function. Because the computer needs to learn the task before it can do the task, a function definition needs to appear in the program before any of its function calls. To call a function, we use its name and a set of parentheses. Inside the parentheses, we pass in any input values, which we call arguments. To execute a function call, the computer jumps back to the function definition.

It plugs in the input values by binding the arguments to the corresponding parameters. This is effectively the same as a variable assignment, so we're assigning the value pink to the variable color. Then the computer executes the function body. When it reaches the return statement, it'll exit out of the function body and jump back to the line of code where the function call occurred. The function returns out whatever value appeared after that return. So this function call evaluates down to the value four, and then we can call the function again and again with different arguments. Let's take another look at our original program. I can see that we're building some kind of adventure game and the player has some number of potion items in their inventory. Then within the game, the player can choose to drink a potion at any point in time. Instead of duplicating this potion conditional all over the program,

it's much easier if we refactor it into a function. We've already written this function definition, it's called drink_potion. It takes in the color of the potion as a parameter and it returns out the number of affected health points. This means we can replace all these potion conditionals with calls to the drink_potion function, and we'll pass in as an argument the potion that the user selected. The more we break down our programs into functions, the easier they are to read and maintain. For example, if I wanna add a blue potion, I only need to modify this one function definition. Before, I would've had to find every duplicated potion conditional in the entire program and update all of them to include a blue potion. But now, every time I drink a potion, I just call this function. So if I just make a quick change here, the entire game now supports blue potions. Plus, now that I've built this function, I don't ever have to think about how potions work again.

As I continue building out my game, anytime I need to deal with potions, I can just call the drink potion function without having to really understand what the code does. In this way, functions let us solve the problem once and move on, which is super convenient when solving big problems. What exactly happens when the computer executes a function call? Well, let's trace a program with a function definition to find out. When we run the program, the computer as normal reads the program line by line starting at the top of the file. When the computer sees the keyword def, it goes off to a short-term memory and defines a new function. We can think of this as the computer copying the function body into a place in memory, and then it tags that location with the function name

and the number of parameters. The computer technically makes some optimizations here, but we can think of it the same way. Effectively, the computer has just learned a new task named get_greeting. Note, however, that the computer does not yet execute any of these lines of code, it's just learning the new task right now, not doing it. When it's done learning, it skips to the next line of code after the function definition. Remember that Python's all about that indentation, so these lines of code are all part of the function body since they're indented over from the function header. To make this a bit easier to see, I'm gonna scroll the program up, but those lines of codes still exist. Here, we just have a normal variable assignment, and since the right-hand side is already a single value, we're ready to store that in short-term memory. The computer stores the value six, and then tags that location with the name last_chatted.

Next line, we have another variable assignment, but before we store, we need to simplify down the right-hand side to a single value. As with all expressions, we start simplifying with the parentheses. So we substitute in the current value of last_chatted and add one. Now that our arguments are down to single values, we're ready to call the function. To start, the computer checks its memory to see if it knows the name get_greeting with two input parameters. In this case it does, so it loads those instructions to execute. The first thing the computer does when it calls a function is create a new stack frame. A stack frame is its own isolated chunk of short-term memory. When the computer executes a function, it treats it as its own little subprogram. It doesn't want that subprogram to muck with the state of the larger program, so it ropes it off from the rest of its memory. Anything that was stored before is still there, we just don't get access to it right now.

First, we need to store the arguments that were passed in. To do this, the computer copies the argument values into new locations in its stack frame. Then it tags each location with the corresponding parameter name. This is order-dependent, so the first argument in the function call gets assigned to the first parameter in the function header. Then we're just executing these lines of code per normal. Seven is not less than one, so this evaluates to false, and we jump to the else branch, and we assign the string "Always good to see you" to a new variable greeting in our own stack frame. Then we're at the return statement. The return keyword tells the computer to exit the function and return execution back to wherever the function was called, but first, it needs to calculate the return value, so we need to simplify down this expression. We plug in the current values of greeting and catchphrase and then we concatenate everything together.

Now, the computer jumps execution back to the call site, taking that return value with it. However, this stack frame does not get to come back. We've effectively terminated this sub-program, so its short-term memory gets cleared. We take that return value to go as we pop off that stack frame. What that means in practice is that this function called expression evaluates down to the return value. So now we have the statement response is assigned the value, "Always good to see you, kerPOW." We have a single value now so we can go off and create that variable. Because we cleared that stack frame, we're back in our global memory space, so we store response there. Now, finally, we get to move to the next line. This just reassigns the variable last_chatted to the value zero, easy. Here we've got another function called to get_greeting. So we just do the same thing. Our two arguments are already simplified down to single values, so we can just go ahead and call the function.

The computer loads the instructions associated with get_greeting from memory and, like before, it also creates a new stack frame. It copies the arguments into the corresponding parameters and then continues on to execute the function body. Days_since_spoken contains zero this time, so we execute the if branch and then we're back at the return statement. This string expression evaluates down to, "Oh, it's you again, ma beans." And once we have that single value, we return back to the call site popping off that stack frame. Now this is a bit of a weird one. This function called expression evaluates down to that string we returned. However, this line of code doesn't do anything with that string. I wouldn't recommend writing programs like this because we're wasting the computer's time calculating a result that we don't need. But I took the creative liberty here so I could show what happens. This instruction is complete, so we moved to the next line and, unfortunately,

since we didn't store it, that function called return_value gets lost to time. We are back in our global memory space and we have a print statement. We load in the value of response and then we concatenate it to the first string. Once we have that single value, we go ahead and display it in the console and then we hit the last line so the computer clears out his global memory and terminates the program. Notice that that function definition gets cleared out from memory too. The computer doesn't remember user-defined functions across program executions so we need that function definition to teach it how to get_greeting every time.

What do you think happens when I run this program? Does it print zero, four, or raise some kind of error? To find out, let's explore variable scope. The scope of a variable describes the region of the program where we can access it. When we run this program, the computer will store the instructions for the get_fall_damage function in short-term memory. Then it'll store the variables max_damage, damage, and height. These all exist in what we call global scope. Because we define them at the top level of the program, the computer stores them in that base level in its short-term memory, so they can be accessed anywhere in the program. They're global. Then we execute this function call. So the computer starts off by creating a new stack frame, which, remember, is just a separate region of short-term memory, the parameter height, and then this damage gets stored in that new stack frame. Notice that these don't get stored in that base global level,

so we don't overwrite the value of this existing global damage. Instead, we're creating new damage and height variables in a different scope. We call this local scope because it's local to this region of memory. As soon as the function call returns, that stack frame gets popped off, so all those local variables disappear. By the time we get to this last print statement, we only have the global damage available. So this prints zero. What does this tell us? Anytime we assign a variable as a part of a function call, that variable gets stored on that local stack frame. That means we can't use functions to update global state. The only reliable way we can communicate information out of a function is through the return value. So instead of trying to update the global variable damage, we can just return out the result of our damage calculation. When we exit out of that function call, we're back in global scope so we can store that return value.

Okay, but why is Python like this? Technically, we can force Python to access the variable in global scope instead. We put the keyword global and the name of the variable, but we should almost never do this. Python defaults to local scope for a reason. By the time we're finished, our program may have tons and tons of function definitions. If every variable in every function was in global scope, then every variable and every function parameter would have to have a global unique name, we couldn't reuse anything. That becomes incredibly difficult to enforce if I have thousands of lines of code spread across tons of different files. Anytime I wanna create a new variable, I'd have to first check if that name is used anywhere else in the program, otherwise my function, and that other function will start conflicting where we're overriding each other's values, which is not what we wanted here. Local scope let's us avoid this problem because we don't need to worry

about the larger program state. We can reuse whatever names we want inside our local function scope. Let's say I change the value of height to 100. We still have the same four names in global scope and the same two names in local scope. So what happens when we access max_damage inside the function? Well, it turns out, while we can't modify the value of a global variable from local scope, we can view the value. When the computer looks up a name, it starts its search in the closest scope. Here, it searches the local stack frame first for the name max_damage. If it doesn't find it in memory there,

it moves its search to the next closest enclosing scope. So now it'll try to look up max_damage in global scope, and once it finds it, it uses that value. If it hadn't found it, it would raise a name error when it ran out of scopes to search. Now, this can be convenient, but it's still not recommended. This function can't guarantee that there exists a global variable named max_damage, and callers of this function may not realize that's a requirement. So we are just asking for future bugs.

It's much safer if I only rely on information passed in through the function parameters. Instead of accessing the global max_damage, I can add a second parameter that takes in that max_damage threshold. That way I can enforce that callers of my function think about what value max_damage should have instead of just hoping that some global variable has been set correctly. Our key takeaways, names defined at the top level of a program are in global scope, and names defined inside a function are local scope. There are ways to cross these boundaries, but in good programming practice we should avoid it as much as possible. Instead, think of your functions like input-output machines. We can communicate information in from an enclosing scope at the beginning through the function arguments, and we can communicate information out to the enclosing scope at the end through the return value. Anything that happens in the middle is a local secret.

Can I call a function from inside another function? Let's trace what happens and explore why we might wanna organize our code this way. When we call a function from the top level of a program, we create a new stack frame and store all our local variables there. When we later return from that function call, we pop off our stack frame and pass our return value back to the caller. If a function calls another function within its function body, we just do the same thing, but we're going one level deeper. When execution reaches that inner function call, the computer pauses what it's doing, loads that function's instructions, and then goes off to execute them. This creates a new stack frame on top of our existing stack frame. Our existing stack frame stays where it is because we're not done executing that function yet, it hasn't returned. The computer needs to preserve that state so we can go back and finish executing the function later.

Any parameters or variables that are a part of this function get stored on that new top stack frame. When we reach this function's return statement, we exit out, pop off that top stack frame and return back to where that function was called, which in this case was inside another function. Notice that the top stack frame now, which is the one that's accessible, is the one that has the state for this function call, and then the computer picks up execution of this function where it left off. We can, in theory, go as many levels deep as we want. Every time the computer calls a function, it creates a new stack frame on the very top, and every time the computer returns from a function call, it pops off the top stack frame. That way, each stack frame is keeping track of the variables local to a specific function call. If we need to pass information through that pipeline of function calls, we can just use the function parameters. We can pass it as an argument to the first function call,

which can then pass it as an argument to the inner function call. Okay, but why might we nest a function call in the first place? Let's set the scene. Imagine a video game where a player tries to sneak into a building without being detected by the guards. Your chance of detection depends on the volume of your footsteps and the volume of your footsteps depends on how fast you're moving and the environment you're in, you can be super quiet crouching in the grass, or you can be super loud running on metal. Now here's one way to solve that problem. I have one giant function that takes in as parameters the player's movement type and environment, and then it returns out a Boolean that tells us whether the player has been detected. I can now call this function across my game anytime a player is sneaking around. So what's the problem then? Well, it's true that I technically have a function, but this function body is huge. Within one function, I'm performing several different tasks.

First, I calculate the player's footstep volume based on their movement. Then I adjust that volume based on the environment they're in, and then I compare that volume against a random detection threshold. When a function does a lot of different things, it makes the program harder to read because it's not always obvious from the function name all of the things that that giant function does. Two, it makes it harder to test. If I pass in as arguments walk and metal,

and the function returns true, "Well, did it work?" I don't know what that final value of volume was that it compared against the threshold. So it's hard to say whether that return value true makes sense, or there's some bug hiding in my function body. And three, it makes the code harder to reuse. If every function performs only one task, then I can mix and match the functionality as I need. So how do we fix this? We just break it down into several smaller functions. So first, let's separate out this movement task. We wanna take in a base volume and movement type, and return out the adjusted volume. So we'll copy this conditional into our function body and return the volume. Then inside this wrapper is_detected function, we can delete this conditional and replace it with a function call.

Notice that this smaller function is very easy to test now. Because my function is doing one specific task, it's easier for me to gut check that my return values make sense. If I call it with the argument crouch, I should get a smaller volume and if I call it with the argument run, I should get a bigger volume. Then I can just do that same thing with the environment conditional. I separate it out into a smaller function that takes in a volume and an environment type and then returns out the adjusted volume. Then I can come back here and nest that function call. Notice that these function names describe the task that they perform, so we don't really need these comments anymore. Our function names are self-documenting. Now for the detection check, I could nest a third function call here, but in this case, I think it might actually be better to separate out this functionality entirely. There's really no reason why this volume calculation needs to be tied to this threshold check,

so I can instead have a wrapper get_footstep_volume function that takes in the movement and environment and returns out the volume. That now lets me have a nice reusable independent is_detected function that takes in a volume and returns out a Boolean. Okay, we've seen how this makes our program easier to test and easier to read, but how about this reusability benefit? If I wanna now add a feature where say the player's voice can also give them away, I have these functions in place to make that really easy. A voice would also be modified by the environment, so I can reuse my environment function without having to think twice about it.

And then since I decoupled that detection threshold check, I can calculate my voice volume and then conveniently just plug it into the is_detected function. To build that whole feature, I had to do very little work because I solved most of those problems already. So the next time you're writing a program, think about breaking it down into small functions that each perform a specific task. Then when you need to combine functionality to perform a bigger task, you can always nest those function calls in a wrapper function.

Let's design a program with functions and nested function calls. We wanna build a program that lets the user play several different card games. That means every game is going to need to share functionality for dealing a deck of playing cards. The first thing that comes to mind is that I'll probably want a function that can draw a random card from the deck. I'm thinking I probably wanna represent a card as a string, so this might return something like queen of hearts. For now, I'm gonna go ahead and stick that in as a placeholder return value.

The other task I can see wanting to perform over and over again is drawing a hand of cards. Different games use different hand sizes, so I'll want this to be generalizable. So the function should take as a parameter the number of cards in the hand. Okay, so how should this function work? I guess really what I want is to draw a number of cards equal to that parameter. Maybe I accumulate all of those card strings into one giant string, and then return that at the end.

That sounds like a good use case for a loop. On each iteration, I draw a card, and then I concatenate that card to our hand. Before we get ahead of ourselves, let's test out what we did so far by calling draw_hand, and to be safe, let's test it out with a few different arguments. Oh, okay, that's a little hard to read. What if instead I put each card on a separate line? In Python, we can achieve this with a new line character, which is just a backslash followed by n. Instead of displaying this as it appears, Python interprets this essentially as us hitting the Enter key. So now with my hand nicely formatted, I feel confident that my draw_hand function works, but I don't want my hand to be full of queens every time. So it's time to go back in

and fill in our draw_card function. A playing card consists of two pieces, the suit and the rank. To draw a random card then, I wanna pick a random suit and random rank, which sounds like two different tasks, which means two different functions. Let's start out with the suit, since that only has four options, and we'll import the random module at the top of the file. Okay, well, we want this function to return either hearts, diamonds, spades, or clubs with equal likelihood. So we'll generate a random number between one and four, and based on that number, choose which suit to return.

Then we can go back to the draw_card function and replace that hard-coded hearts with a call to get_suit. When I run those draw_hand function calls now, I get all different kinds of queens. The last thing we need to add is a get_rank function. A playing card can have a rank of ace, two through 10, or jack, queen, king. That means in total there are 13 possible ranks, so we'll generate a number between one and 13. If we get one, we'll return the rank ace, 11, we'll return jack, 12, queen, and 13, king. Any other rank, like eight, is just represented by its number, so we can return num. Now, just like before, let's go back to draw_card and call get_rank.

Hmm, what does this stack trace mean? When we read stack traces that involve function calls, we generally wanna focus on the bottom because that is where it'll tell us what the actual error is and what line it came from. The rest of the stack trace just tells us the path of execution the computer took to reach that line. So it started by executing draw_hand, which then called draw_card, which then had the error. This TypeError tells us that we're adding an integer and a string, so get_rank must be returning an integer somehow. These cases are definitely returning a string. Mm, but down here when we return num, num is an integer. As a general rule, a function should be consistent about which data type it returns always. That way callers can know what to expect. So since get_rank needs to return a string in the ace, jack, queen, king case, we also wanna cast num to a string before we return it.

There's one last feature we wanna add. Some of our card games, don't use face cards, that is ace, jack, queen, king. Because face cards can either be enabled or disabled, we can support this option with a Boolean parameter, and if we don't want face cards, we can just generate a random number between two and 10 instead. That way we're excluding the options 1, 11, 12, and 13. Now, when I call get_rank inside draw_card, I'll need to pass that parameter, but how do I know if it should be true or false? Well, I don't know. I wanna let the caller decide. So draw_card will also take that parameter and pass it through to get_rank, and then that extends to draw_hand as well.

Oops. And now I need to update my calls to draw_hand to take in that extra argument. Now that it's all working, what are the limitations of this approach? Well, the deck I modeled here isn't actually stateful. It's possible my hand has two ace of spades. Depending on our use case, this might actually be a feature because some games use multiple decks or don't want players to count cards. But in other games where the rules strictly assume exactly one of each card, this might be a bug. For this collection of games, I actually think this simplification is pretty nice, but it might not be for someone else's use case.

We've been writing our code all in a single file, but as our programs get longer, our main logic tends to get buried underneath all of our function definitions, which can make the program hard to read. So easy solution, what if we just took all those function definitions and moved them somewhere else? That means organizing our code into modules. To create a module, we just make a new file with a .py file extension. File extensions tell the computer how to interpret the files contents, like MP4 is a video, and .py is Python code. We'll name this file arcade.py because it's meant to contain functionality for an arcade game, and then we'll just move all those function definitions in here. If I run the program now, I get a NameError because the computer doesn't know where to find those functions anymore. It may seem obvious to us that there's another file over here, but the computer doesn't put two and two together,

it only does exactly what we tell it to do. So if we want the computer to be aware of the arcade module when it runs the program, we need to import it. Anytime we call one of its functions here then, we need to prefix it with the module name. All right, that concept is pretty straightforward, we just have our code in multiple files now. But let's unpack how exactly this all works. Even though our program logic may be spread across multiple files, when we run a program, we can only ever specify a single file to execute. We call this the entry point or main logic. By convention, in Python, we name this file main.py. You may have noticed that in the Khan Academy IDE, the default file is always named main.py. When we press the Run button, this is the file that executes. We can build up a program by having a function in one module call a function in another module, which imports another module, and so on and so on. But for any code to be executed,

it needs to be triggered somewhere along the chain from that entry point file. Okay, what about this import statement? How exactly does that work? When the computer executes an import statement, it jumps execution to the specified module. When it's done there, it'll jump execution back to the importing module and pick up from where it left off. From the computer's perspective, importing a module is effectively the same as copying and pasting all the contents of that file where the import statement appears. But there's one key difference: the scope. Function and variable names are scope to the module that they're defined in. This just basically adds another layer. So in the computer's memory, all those function names are filed under the module name. That's why if we call get_score in main.py without the arcade in front of it, we get a NameError because the computer can't find that name in main's global scope. By putting the arcade in front of it,

we make it a two-step lookup. First, the computer looks in its memory for the arcade namespace, and then, in that scope, it looks up get_score. Module scope means that, as a programmer, I don't have to worry about what other programmers or myself yesterday are naming their functions in other files, we can both name our functions get_score because they'll exist in different scopes. Note that we typically only put function definitions inside a module because the net effect of executing that is just that the computer has learned some new tasks. If I add a print statement indented at the top level of this file, it executes anytime I import this module. If that module imports another module, imports another module, and all of them have these top level print statements, it becomes very difficult to trace where that output is coming from.

So why use modules? Well, they're really just a convenience for the programmer. We break down our tasks into functions and then we group those functions into modules. Well-written modules make programs easy to navigate because if I want a piece of functionality related to inventory management, I would know to look in the inventory module. They also make code more reusable because I can package a bunch of related functionality into a module and then import it in multiple places, and they let us focus on one thing at a time as we're building. When I'm working in main.py, I can think about my program at a high level and just work on how all the pieces fit together. And when I'm working in inventory.py, I can forget about all that and just focus on the details of how inventory management works.

Let's design a program with multiple files. We wanna build a basic version of the strategy game Nim. In Nim, players take turns removing either one or two stones from a pile. Whoever removes the last stone loses. In the version we're building, we want the user to play against a computer player. That means we'll probably want a function that decides how many stones the user picks up and a function that decides how many stones the computer picks up. Let's start by creating a new module for our game components to live in. I think I'm gonna name this stones.py because at the very least I know I'm gonna have some functions for picking stones. I'll name one pick_for_user and the other pick_for_computer. I don't wanna get too stuck on this detail right now, so I'm gonna have the computer always pick one stone and I'll figure out a better algorithm later. The user, on the other hand, needs to pick their number of stones via input prompt. So in pick_for_user,

I'll call the input function, and then I'll return out the number of stones that the user entered. However, we wanna make sure that this function can only ever return one or two, so we can use a loop to validate the user's input. If they don't enter one or two, we repeat the prompt. Now that we have a couple functions sketched out, let's switch over to thinking about the main game logic, so I'll jump to the main.py file. The game continues with players picking stones until the pile runs out, which kind of sounds like a while loop. While there are still stones, play a turn. So like with all while loops, we'll initialize our pile before the loop, in the loop condition, we'll check if the pile is greater than zero, and then inside the loop body we need to update pile.

So we'll call pick_for_user and subtract that number of stones. We defined pick_for_user in the stones module, so in order to call the function we'll need to import stones and then prefix the function name. Okay, let's pause and test that our loop works. Because there are 10 stones, if I pick up two every time, the loop should terminate after five iterations. Now let's add in the computer player's turn. Just like the user, the computer will pick a number of stones and remove those from the pile, but we can't just put this in the loop body after the user's turn because what if the user has already picked the last stone? A computer shouldn't get another turn 'cause the game's already over. Instead, we wanna alternate players on each iteration of the loop. So we'll add a new variable to keep track of whose turn it is.

Since there are only two possible states, we can make this a Boolean. If it's true, we play the user's turn, and if it's false, we play the computer's turn. Then at the bottom of the loop we just swap it to the other player. If it's true, we change it to false, and if it's false, we change it to true. Okay, let's try this out. It seems like we have a pretty good working prototype here, so now it's time to jazz up the user interface. First, I think it would be nice if the program told us who won. We know the game is over after the loop has terminated, so we'll print out the result here. Whoever went last must have picked the last stone, but we already swapped over the turn at the bottom of the loop. So if it says it's the user's turn, then the computer picked the last stone, and to make it clear that you don't wanna pick the last stone, I'll print out the rules at the top of the program.

It might also be nice to draw the pile of stones. I'll define a new function for that so I can change up how the pile looks without having to touch my main logic. The function will take in a number of stones as a parameter and return out a picture. Let's maybe draw a little circle for every stone. Then, back in main.py I can just call show and print out its result. These circles look cool, but they're a little annoying to count. So I'll go back to the show function and include a number in the picture.

Ask anything

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

FlashcardsQuizFill in the blanksWritten testLessonNotesPodcastContent