Challenges
Captain Code: Unleash Your Coding Superpower with Python · ISBN 0137653573 · 32 challenges
Captain Code: Unleash Your Coding Superpower with Python includes challenges at the end of some lessons. Solutions to the challenges are presented here. Just keep in mind that there is rarely one solution to a challenge, so if your solutions look different but produce the desired result, that's ok.
Lesson 2: Mad Libs
So, here is your first Challenge. Hello4.py created two variables, firstName and lastName, and then combined them into a new variable, named fullName. Modify that code so that it asks the user for a first name and last name instead of using the hard-coded values.
Here’s a hint: You only need to change the first two lines of code so that each line uses an input() function. Can you figure this one out?
Make your Mad Lib interesting by prompting for at least 15 different words. And then personalize it. At the start, when you provide instructions, ask the user for their name, and then use that in the instructions to create a more personalized experience.
Lesson 3: Roll the Dice
Ok, this one is a little harder, but you can do it, promise! See that list with the five animals? Write code that creates two lists, one with animals, like this:
animals=["ant","bat","cat","dog","eel"]You can use your own list of animals, and you can have more than five (the more the better).
Then create a similar list of adjectives, things like big, green, smelly, cute, and so on. (Again, the more, the better. And it doesn’t matter whether or not your two lists have the same number of items.)
Then pick a random adjective and a random animal and save each to a variable. (You’ll need two variables: one for your animal and one for your adjective.) Then print() the choices so that the output is something like I have a cute eel. Each time you run the app, you’ll get a different combination.
Most dice we use have 6 sides, but some games use dice with more sides. And, actually, Ancient Greeks and Romans used dodecahedron shaped dice, which have 12 sides! So, just in case you ever run into an ancient Greek or Roman, write code that rolls a 12-sided die.
Lesson 4: Calculate the Day
Modify Date2.py to also display the current time. The properties you want are called hour and minute.
Lesson 5: Rock Paper Scissors
You wouldn’t want someone else with the same name getting the same advantage. How could you modify this code to make it a little more private? You could require the name to be typed a specific way (all lowercase maybe), or have a space or two at the end. Come up with an option and modify the if statement to check for it.
Lesson 6: Secret Codes
range() takes an optional third argument—a step. If you specify range(1, 11, 2), the loop counter will increase by 2 each time, so the loop will run 5 times instead of 10 (for 1, 3, 5, 7, and 9). Try to create a loop that displays the numbers 10, 20, 30, all the way to 100.
As you have seen, Encrypt.py and Decrypt.py are almost identical. In truth, they should have been the same program. We just separated them to make the code a little simpler.
action = input("Encrypt or decrypt? Enter E or D: ")Then, in your code, you can use if statements to select the encrypt or decrypt versions of the code, based on action being E or D.
Lesson 7: Guess the Number
Double challenge for you this time.
First, look at the final print() statement. It displays the sorted list, but the output doesn’t look that good. So change that output to use a for loop printing the sorted animals one per line.
Second, make sure the user doesn’t type an animal already in the list. How? Refer back to Chapter 6 if you need a reminder of how to check if an item is in a list. Then modify the if statement so that in addition to checking for the length of the input, it also checks to ensure that the item is not already in the list. Your condition will have two parts, and you’ll want to use and to join them.
This one is tricky, but you can do it. Can you provide more feedback? Instead of always displaying Too low or Too high, can you display Too low or Too high if they are close and Much too high and Much too low if they are way off? Think about it.
Lesson 9: Hangman
On second thought, we handled the user input badly in this code. Why? If the user entered too many characters, we opted to use the first of them and ignore the rest. That works. But what if the user enters no characters at all? That’s a situation we didn’t plan for! Oops!
No worries, that’s why coders write version 2 (or version 1.1, you get the idea) of their apps. So, update the code so that it catches all invalid input lengths (too long or too short). You can do this with a while loop, like this:
currGuess = ""while len(currGuess) != 1: This one is a fun one. In the current game, we display the number of lives left, like this:
# Display remaining lives
print (maxLives-livesUsed, "tries left")
Can you replace that code to actually display a Hangman picture? You can use simple characters like | and / to draw one. For example, this code would print the picture at the start of the game, with no incorrect guesses yet:
print(" |---------")
print(" | / |")
print(" |/ |")
print(" |")
print(" |")
print(" |")
print(" |")
print(" |")
print(" |")
print("---")Start with this and create the pictures needed for each wrong guess.
You’ll need an if statement to decide which picture to show.
And, here’s a tip. If you plan your print() and if statements carefully, you can do this without having to create a different picture for each number of lives. You can have one picture and change what gets shown on each line based on the number of lives left.
Oh, watch for backslash characters (the \ character). That’s a special character in Python. If you actually want to display \ as part of your hangman, you’ll want to type \\ instead (you type two backslashes, but Python will display just one).
Lesson 10: Keep Going
Want to make this a bit more interesting? Asking the user for year, month, and date (or hard coding those values) makes the math easier. But, in truth, you only need month and day, as you can figure out the year yourself: It is either this year if the birthday has not occurred yetor next year if it has.
So update the code to prompt for a month and day and do the math to figure out the year.
Want to make it more interesting? Here are some ideas:
This one is tricky, so we’ll show you 2 solutions.
Ok, heads-up, this one is tricky. But, we have faith in you.
Have you ever seen websites that give you password rules? They’ll say something like “Passwords must be at least 8 characters in length and have at least 1 digit and 1 special character.”
So, suppose the user says yep, I want uppercase, lowercase, digits, and special characters in my password. Easy, you pick random characters and build a password. Right?
Well, if you pick random characters from all the options, there is no guarantee that you’ll get a digit or a special character. Actually, you may not even get letters at all. You could end up with just digits or special characters.
Ideally, if the user says they want digits, you’ll make sure that there is at least 1 digit. Same for special characters. So, how could you modify the code to do this?
Lesson 11: Getting Func-ky
Superheroes often need to travel great distances, and depending on where they go they’ll need to measure those distances in miles or kilometers. Create two functions:
Lesson 13: Cleanup Time
Externalize all of the strings in your application. At a minimum, externalize the display text. If you’d like, you can even externalize option prompts and any other displayed text.
Lesson 14: Reduce, Reuse, Recycle, Refactor
You know what the challenge is this time: Refactor your game. Update every single location function in your game to use the new getUserChoice() function.
Back in Chapter 11, you created a wonderful inputNumber() function. That will be useful in your game, so copy it into Utils.py.
You know what else would make a great function? You are often going to need to ask the user to make a yes-or-no choice. Things like Do you want to pick up the weapon? or Do you give up? or Do you need help?
You could have a while loop in your code and use input() to get a Y or N from the user. But, nah. You could also probably use getUserChoice(). But that’s a little convoluted.
So, create a new function in Utils.py called inputYesNo(). You’d call it like this:
pickUpGun=inputYesNo("Do you want to pick up the gun?")inputYesNo() would display the passed text, prompt the user, and return a result.
You can use inputNumber() as a starting point for this one.
Lesson 15: Carrying (and Using) Stuff
You now have everything you need to define a complete inventory system. Identify places in your game where you’ll use additional inventory items. Add them to the inventory and create the appropriate wrapper functions.
Lesson 16: Staying Classy
Our player class has a name property that you can use to personalize the game. Update your doWelcome() function to ask the player for their name and save it to the player class. You can do something as simple as p.name=input(), or you can create a method in player to setName(). Either way works.
Then use p.getName() in your code to display personalized messages.
Oh, you’ll also want to personalize the text returned by get() in Strings.py, too. One simple way to do this is to pass p.getName() as a second argument to the get() method, and use that when you construct the text to be displayed.
When a player runs, they die (method doRun()). Change the code so that when they run, they lose a life. (Hint: we have a method in the class that does just this.) Then use isAlive() in an if statement. If the player is still alive, send them to doStart() to continue playing; if not, use gameOver().
Lesson 17: Color Your World
Now that you know how to color your output, go ahead and color the whole game.
Lesson 19: Crazy Driver
Try changing the window size passed to set_mode(). Make it bigger, smaller, wider … you get the idea.
We defined three colors. Try changing fill() to use RED instead of WHITE. And then create your own color variables and use them. Remember, you can use any values between 0 and 255 for each of the RGB values. You may want to use just 0 and 255 as you play with the colors. (That still gives you 8 combinations to try.)
Lesson 20: Image-ine the Possibilities
We’re only using images right now, and thus we have just an Images folder. But it’s good to plan for the future. Assume that you have Sound and Videos folders and create variables for each of those. You should be able to create each with a single line of code.
We provided three different enemy cars for you to use. We’ll actually use all three in later chapters, but for now, you can experiment with them. Change the code so that the enemy car that gets placed at the top of the screen is Enemy2 or Enemy3.
Lesson 21: We Like to Move It
Game speed is controlled by the moveSpeed variable. It specifies how many pixels the enemy should advance by and how many pixels the player sprite moves with each left or right arrow key press.
Try changing the moveSpeed value. You can try smaller numbers and larger numbers. Get a feel for how changing this value impacts game play.
We used the left and right keys to move the player sprite. You don’t have to use those keys; you can pick your own. Many games use A and S, for example. Update the code to use those keys. You’ll want to check for K_a and K_s.
Or allow both sets of keys, letting players use left arrow or A to go left and right arrow or S to go right. Here’s a hint: You can do this easily with an or in your if statement. If you do this, be careful to group your conditions correctly with parentheses because you’ll have an and and an or.
Lesson 22: Crash Bang
The game gets faster (and thus harder) the longer you play. But the scoring stays the same: 1 point per car avoided. Can you change that so that once the game doubles in speed, players get 2 points per car avoided?
Lesson 23: Finishing Touches
We created a paused variable to track whether or not the game is paused: True if it is, False if not. Was this necessary? Actually, no, it wasn’t. There is another way to know if we’re paused or not: just look at moveSpeed, which will be 0 only if the game is paused. Modify the code to remove the paused variable, and use the existing moveSpeed variable to pause (and unpause) game play.
Can you add additional vehicles to the game? You can create your own PNG files or try to find some online. Save the images to the Images folder and then add them to IMG_ENEMIES.