["Big Quiz","100 B I G Q U I Z How to build Each question is Big Quiz displayed here. Put your coding skills to the Pygame Zero Game test and create a quiz game to challenge your friends. You\u2019re the What is quizmaster, so you can make the capital of questions about any topic you like. What happens When the game begins, the first question is shown on the screen along with four possible answers. The player has ten seconds to click on an answer box. If they get the right answer, the game moves on to the next question. If the player chooses a wrong answer, or if the time runs out, the game ends and the final score is displayed on the screen. What is the capital London of France? Paris Berlin \u25b3 Boxes This game doesn\u2019t use images. Instead, the questions, answers, and the timer are displayed in colorful boxes that you create using code.","HOW TO BUILD BIG QUIZ 101 The game starts with ten Are you ready for seconds on the timer. If it the big quiz? reaches zero, the game ends. Bring it on! the France? 7 Paris The possible answers Tokyo are displayed in orange boxes. You can change them to a different color if you like. \u25c1 Quiz time! This program uses a Graphical User Interface (GUI, pronounced \u201cgoo-ey\u201d), which is the visible part of a program that a user interacts with. In this game, you\u2019ll build a GUI using Pygame Zero.","102 B I G Q U I Z Start \u25c1 Big Quiz flowchart How it works Draw the GUI on The main body of this program is a loop the screen that checks if the player has selected the All the questions and possible correct answer within the given time. If answers are stored in a list. The Create a list of they have, the program moves to the next program uses the pop() function questions question in the list and the timer is reset. to get the first question and If the answer is wrong, the game ends and its possible answers from the the final score is displayed. list and then displays them. The player\u2019s score is stored in a variable and increases with each correct answer. The final score is displayed at the end of the game. Are there any Reset timer questions left in N the list? Y Display the question at the top of the list Display final score NY Increase score Is the player\u2019s by one answer correct? End Umm... I have a question!","GAME PROGRESS 1 1 % 103 Thinking caps on! There may be a time limit to answer the questions, but not to build the game! Follow these steps carefully to build your own quiz show to play with your friends and family. 1 First steps Save As: quiz.py Create a new folder called big-quiz in your Tags: python-games folder. Then open IDLE and create an empty file by going to the File menu Where: big-quiz and choosing New File. Select Save As... from the same menu and save the file as quiz.py Cancel Save in the big-quiz folder. 2 Set the screen size WIDTH = 1280 These values Next you need to define the size of the HEIGHT = 720 are in pixels. playing area. Add this code to the very top of your program to set the width and def draw(): Remember, pass height of the game screen. pass is used as a placeholder for 3 Create the stubs def game_over(): functions that you You don\u2019t need any images for this game, pass don\u2019t want to so you can jump straight into writing the define right away. code. First create placeholders for the def correct_answer(): functions you\u2019ll need to build the quiz. pass Check page 144 def on_mouse_down(pos): to know more about pass placeholders. def update_time_left(): pass","104 B I G Q U I Z When planning the interface of a game, try sketching it on 4 Plan the interface paper before writing any code. When building this game, you need to think about the way it looks, or its \u201cinterface.\u201d The player needs to be able to see the question, its possible answers, and a timer that shows how long they\u2019ve got left. Here\u2019s a sketch of how you might want the interface to look. There should be Main question Timer The timer can be enough room to placed on the side, but make display the full sure it\u2019s big question. enough for the player to see The font size at a glance. will need to be big enough for the Answer 1 Answer 2 player to read the Answer 3 Answer 4 question easily. There should be enough space between The possible all the answer options so that the player answers need to be doesn\u2019t click a different answer by mistake. big enough for the player to click on them quickly. LINGO Wireframes Computer game designers can plan their game interfaces using wireframes. These are diagrams that show the different parts of an interface that the player sees on screen. They can be drawn by hand or made using a simple drawing tool on a computer. By doing this, the interface can be tested, and any changes to the design can be made before writing the code.","GAME PROGRESS 2 6 % 105 5 Create a box for the interface WIDTH = 1280 Now that you\u2019ve planned what the interface will HEIGHT = 720 look like, you can create the rectangular boxes that will make up the GUI. Type this code below main_box = Rect(0, 0, 820, 240) what you typed in Step 2 to create a box for the main question. This function takes four parameters. The This sets the box size first two numbers are the coordinates of to 820 pixels wide and 240 pixels high. the top-left corner of the box, and the last two numbers are the coordinates of the bottom-right corner of the box. 6 Make the other boxes main_box = Rect(0, 0, 820, 240) You now need to make a box for the timer timer_box = Rect(0, 0, 240, 240) and four separate boxes for each of the answer_box1 = Rect(0, 0, 495, 165) possible answers. Type this code under what answer_box2 = Rect(0, 0, 495, 165) you wrote in Step 5. answer_box3 = Rect(0, 0, 495, 165) answer_box4 = Rect(0, 0, 495, 165) The timer box is a square 240 pixels wide and 240 pixels high. All the answer boxes are the same size. 7 Move the boxes answer_box4 = Rect(0, 0, 495, 165) At the moment, all the boxes will be drawn on top of each other in the top-left corner. You main_box.move_ip(50, 40) need to add some code to move them to their timer_box.move_ip(990, 40) correct positions on the screen. Type this code answer_box1.move_ip(50, 358) immediately after the code from Step 6. answer_box2.move_ip(735, 358) Arr! Time to answer_box3.move_ip(50, 538) move all these answer_box4.move_ip(735, 538) boxes into place! move_ip() moves each The top-left corner of rectangle to the place you each box will be placed at the coordinates in want it on the screen. the brackets.","106 B I G Q U I Z 8 Create a list of answer boxes This game uses four boxes to show the possible answers to each question. You can keep track of these boxes by using a list. Add this code immediately after what you typed in Step 7. answer_box4.move_ip(735, 538) answer_boxes = [answer_box1, answer_box2, answer_box3, answer_box4] This list holds all This sets the These lines draw the answer boxes. background to a the main box and dim gray color. the timer on the 9 Draw the boxes screen and colors Now that you\u2019ve created the boxes, it\u2019s them sky blue. time to add some code to draw them on the screen. Replace pass under def draw() This draws every box from Step 3 with this code. in the answer_boxes list on the screen and def draw(): colors them all orange. screen.fill(\\\"dim gray\\\") screen.draw.filled_rect(main_box, \\\"sky blue\\\") screen.draw.filled_rect(timer_box, \\\"sky blue\\\") for box in answer_boxes: screen.draw.filled_rect(box, \\\"orange\\\") 10 Try it out Pygame Zero Game Save your file and run it from the command line in the Command Prompt or Terminal window. You should be able to see your GUI, ready to be filled with quiz questions. If your program fails to run successfully, go back to your code and try to catch those bugs! I\u2019m not sure how to run the game! Better check pages 24\u201325 for help.","GAME PROGRESS 5 2 % 107 11 Set the score Don\u2019t forget to save Now that the interface is ready, you need to start thinking about your work. how the game will work. Create a variable to hold the score and set it to zero. Type this after the code you wrote in Step 8. answer_boxes = [answer_box1, answer_box2, answer_box3, answer_box4] score = 0 12 Set the timer score = 0 This is the number of You also need to create a timer that will time_left = 10 seconds the player has hold the number of seconds the player has to answer each question. left to answer each question. You can give them ten seconds to answer by setting the This is the name of the list. This question is the variable to 10. Here it means question 1. first item in the list. 13 Add the first question time_left = 10 It\u2019s time to create the first quiz question. All the questions will be multiple choice, q1 = [\\\"What is the capital of France?\\\", which means there are several possible \\\"London\\\", \\\"Paris\\\", \\\"Berlin\\\", \\\"Tokyo\\\", 2] answers, but only one of them is correct. You can use a list to store the information These are all the This number indicates the position of about each question. Type this code next. possible answers the correct answer. Here it\u2019s 2, which to the question. means Paris is the correct answer. 14 More questions q1 = [\\\"What is the capital of France?\\\", Let\u2019s add some more questions by typing \\\"London\\\", \\\"Paris\\\", \\\"Berlin\\\", \\\"Tokyo\\\", 2] the code shown in black below the lines from Step 13. Remember, you can create your own q2 = [\\\"What is 5+7?\\\", sets of questions if you like. You could base \\\"12\\\", \\\"10\\\", \\\"14\\\", \\\"8\\\", 1] them on your favorite sports team, or show off what you know about your favorite q3 = [\\\"What is the seventh month of the year?\\\", series of books. \\\"April\\\", \\\"May\\\", \\\"June\\\", \\\"July\\\", 4] ?? Any questions? q4 = [\\\"Which planet is closest to the Sun?\\\", ? \\\"Saturn\\\", \\\"Neptune\\\", \\\"Mercury\\\", \\\"Venus\\\", 3] ? ? q5 = [\\\"Where are the pyramids?\\\", \\\"India\\\", \\\"Egypt\\\", \\\"Morocco\\\", \\\"Canada\\\", 2]","108 B I G Q U I Z 15 Create a list for the questions q5 = [\\\"Where are the pyramids?\\\", Next you need to add some code to keep \\\"India\\\", \\\"Egypt\\\", \\\"Morocco\\\", \\\"Canada\\\", 2] the questions in order. You can do this using a list, just like you did for the answer boxes questions = [q1, q2, q3, q4, q5] in Step 8. Add this line under the code from Step 14. This list holds all the questions. 16 Add a function questions = [q1, q2, q3, q4, q5] In a real-life quiz, the quizmaster begins by question = questions.pop(0) picking up the first question from the top of a list. In Python, you can do the same thing This gets the first question from by using the pop() function. This function the questions list and stores it removes the first item from the list, which in a variable called question. makes the second item move to the top of the list. So in your code, pop() will remove q1, and q2 will take its place. Type this code next. 17 Display the boxes EXPERT TIPS Now you need to update the draw() function to display the questions and the Pop the stack timer on the screen. Use a for loop to draw the possible answers inside the answer When you place items in a list, Python boxes. Add this code to the draw() function stacks them on top of each other. The first under what you typed in Step 9. item in the list appears at the top of the stack. Using the pop() function removes an item from the top of the stack. screen.draw.filled_rect(main_box, \\\"sky blue\\\") This line displays screen.draw.filled_rect(timer_box, \\\"sky blue\\\") the number of seconds remaining for box in answer_boxes: in the timer box. screen.draw.filled_rect(box, \\\"orange\\\") screen.draw.textbox(str(time_left), timer_box, color=(\\\"black\\\")) This displays screen.draw.textbox(question[0], main_box, color=(\\\"black\\\")) the question in the main box. index = 1 for box in answer_boxes: These lines draw each possible answer screen.draw.textbox(question[index], box, color=(\\\"black\\\")) in an answer box. index = index + 1","GAME PROGRESS 7 0 % 109 18 Run the code again The first question is Save your code and run it from the command line displayed on screen. again. You should see the first question and its four possible answers. At the moment, you can\u2019t click on any of the options, and the timer is also fixed at ten. You\u2019ll add the code to do these things soon. Pygame Zero Game What is the 10 capital of France? London Paris Ah! I knew this was Berlin Tokyo the right place! 19 Set up the final screen This creates a message It\u2019s time to think about how the game should end. Write that will show the player\u2019s some code that displays the final score when the game final score. ends. Replace pass under def game_over() from Step 3 with this code. def game_over(): Since there\u2019s no global question, time_left correct answer here, message = \\\"Game over. You got %s questions correct\\\" % str(score) it\u2019s set to 5, which question = [message, \\\"-\\\", \\\"-\\\", \\\"-\\\", \\\"-\\\", 5] isn\u2019t on the list. time_left = 0 This sets the time to zero The final message is displayed instead of another when the game ends. question. This will set all possible answers to a dash because you don\u2019t want the player to be able to answer.","110 B I G Q U I Z def correct_answer(): This increases global question, score, time_left the score by one. 20 Correct answers Now you need to tell Python score = score + 1 This gets the what you want the program if questions: next question to do if the player gets an if there are any- answer correct. You need to question = questions.pop(0) more questions increase the current score, time_left = 10 left in the list. and then get the next else: question. If there aren\u2019t any print(\\\"End of questions\\\") This resets the questions left, the game game_over() timer back to should end. Replace pass ten seconds. under def correct_answer() This displays a message from Step 3 with this code. in the Command Prompt or Terminal window. This block runs if there are no more questions in the list. This line checks The variable index holds a number which box has that represents the position of the been clicked on. answer box in the list. 21 Answering questions def on_mouse_down(pos): Next add some code that index = 1 will run when the player clicks for box in answer_boxes: on an answer box. This code if box.collidepoint(pos): will check to see which box print(\\\"Clicked on answer \\\" + str(index)) has been clicked on, and index = index + 1 then print the result in the Command Prompt or Terminal The variable index increases This displays a message window. Replace pass under by one and moves to the in the Command Prompt the on_mouse_down(pos) next answer box in the list. or Terminal window. function from Step 3 with this code. 22 Click the boxes Rabiahma \u2013 bash \u2013 80x24 Run your code again and click on each answer box Clicked on answer 1 that appears on the screen. Clicked on answer 2 You should see messages in Clicked on answer 3 the Command Prompt or Clicked on answer 4 Terminal window telling you which box you clicked on.","GAME PROGRESS 89% 111 23 Check the answer Wow! Tina has gotten all Now you need to update the body of the answers correct! the on_mouse_down(pos) function from Step 21. Add the following code that will run if the player clicks on a box with the correct answer. def on_mouse_down(pos): The item at position five index = 1 in each question list is the for box in answer_boxes: number that corresponds if box.collidepoint(pos): to the correct answer. print(\\\"Clicked on answer \\\" + str(index)) if index == question[5]: print(\\\"You got it correct!\\\") correct_answer() index = index + 1 This checks if the player One more point and has clicked on the correct the game is over! answer box. 24 End the game If the player clicks on a wrong answer, the game should end. Update the code under def on_mouse_down(pos) one last time and use an else statement to run the game_over() function if the player selects a wrong answer. Add the code shown in black below. def on_mouse_down(pos): index = 1 for box in answer_boxes: if box.collidepoint(pos): print(\\\"Clicked on answer \\\" + str(index)) if index == question[5]: print(\\\"You got it correct!\\\") correct_answer() else: game_over() index = index + 1 This block runs if the box clicked on doesn\u2019t hold the correct answer.","112 B I G Q U I Z 25 Update the timer Now you need to update the code under def update_time_left() from Step 3. This will decrease the number of seconds by one every time the function is run. Type the following code. If there\u2019s still time def update_time_left(): left on the timer, global time_left this decreases if time_left: it by one. time_left = time_left - 1 This ends the else: game when the game_over() time runs out. 26 Schedule the timer global time_left Finally, you need to update the update_time_left() function so if time_left: that it runs automatically once time_left = time_left - 1 every second. You can use Pygame Zero\u2019s clock tool to do this. Add this else: line of code to the very bottom of game_over() your program. clock.schedule_interval(update_time_left, 1.0) This calls the update_time_left() function once every second. 27 Get quizzing! Pygame Zero Game 7 The player That\u2019s it! Run your game and try it needs to click out. Hopefully, you\u2019ll be able to What is the on the correct answer all the questions correctly. capital of France? answer before Remember, if your screen doesn\u2019t the time look right, you\u2019ll have to go back to runs out. your code and debug it. Read every line carefully and make sure your London Paris code matches the steps exactly. Have fun quizzing your friends! Berlin Tokyo","GAME PROGRESS 1 0 0 % 113 Hacks and tweaks Got it! You\u2019ve built a great game, but don\u2019t limit yourself to just five questions. Take Big Quiz to the next level by tweaking some of its rules. Here are some suggestions to get you started. \u25b7 Take the hint def on_key_up(key): if key == keys.H: You can give the player print(\\\"The correct answer is box number %s \\\" % question[5]) a hint by displaying the correct answer box in the Command Prompt or Terminal window if they press the H key. Here is some code you could use to do this. def on_key_up(key): \u25c1 Skip a question global score if key == keys.H: You could add some print(\\\"The correct answer is box number %s \\\" % question[5]) more code to the if key == keys.SPACE: on_key_up(key) score = score - 1 function that allows correct_answer() the player to skip a question by pressing This block first decreases the player\u2019s score by one the Space bar. Skipping and then runs the correct_answer() function, which a question means they increases it by one, keeping the score the same. move on to the next question, but without scoring a point. Here\u2019s one way of doing it. \u25b7 More questions q6 = [\\\"What is a quarter of 200?\\\", \\\"50\\\", \\\"100\\\", \\\"25\\\", \\\"150\\\", 1] You can play this game over and over again, but to keep it interesting, you q7 = [\\\"Which is the largest state in the USA?\\\", can change the questions or even add \\\"Wyoming\\\", \\\"Alaska\\\", \\\"Florida\\\", \\\"Texas\\\", 2] some more. Here are a few examples of questions that you might want to use. q8 = [\\\"How many wives did Henry VIII have?\\\", You can always add some of your own! \\\"Eight\\\", \\\"Four\\\", \\\"Six\\\", \\\"One\\\", 3] If you add extra questions, what else in the code will you need to update?","114 B I G Q U I Z papaya whip plum slate blue (R 255, G 239, B 213) (R 221, G 160, B 221) (R 106, G 90, B 205) \u25b7 Dash of color You can make your interface more attractive moccasin orchid dark slate blue by changing the color of the background, the (R 255, G 228, B 181) (R 218, G 112, B 214) (R 72, G 61, B 139) boxes, or the text that appears on screen. Here are some colors along with their RGB values that you can play with. Take a look at page 75 to find out how RGB values work. light salmon hot pink peach puff fuchsia pale green (R 255, G 160, B 122) (R 255, G 105, B 180) (R 255, G 218, B 185) (R 255, G 0, B 255) (R 152, G 251, B 152) salmon deep pink pale goldenrod medium orchid light green (R 250, G 128, B 114) (R 255, G 20, B 147) (R 238, G 232, B 170) (R 186, G 85, B 211) (R 144, G 238, B 144) light coral medium violet red yellow blue violet dark sea green (R 240, G 128, B 128) (R 199, G 21, B 133) (R 255, G 255, B 0) (R 138, G 43, B 226) (R 143, G 188, B 143) crimson coral gold dark violet green yellow (R 220, G 20, B 60) (R 255, G 127, B 80) (R 255, G 215, B 0) (R 148, G 0, B 211) (R 173, G 255, B 47) red tomato khaki dark orchid chartreuse (R 255, G 0, B 0) (R 255, G 99, B 71) (R 240, G 230, B 140) (R 153, G 50, B 204) (R 127, G 255, B 0) fire brick orange red dark khaki dark magenta lawn green (R 178, G 34, B 34) (R 255, G 69, B 0) (R 189, G 183, B 107) (R 139, G 0, B 139) (R 124, G 252, B 0) dark red dark orange lavender purple lime (R 139, G 0, B 0) (R 255, G 140, B 0) (R 230, G 230, B 250) (R 128, G 0, B 128) (R 0, G 255, B 0) pale violet red orange thistle indigo lime green (R 219, G 112, B 147) (R 255, G 165, B 0) (R 216, G 191, B 216) (R 75, G 0, B 130) (R 50, G 205, B 50) pink light yellow violet medium slate blue sea green (R 255, G 192, B 203) (R 255, G 255, B 224) (R 238, G 130, B 238) (R 123, G 104, B 238) (R 46, G 139, B 87)","HACKS AND TWEAKS 115 green pale turquoise royal blue rosy brown maroon (R 0, G 128, B 0) (R 175, G 238, B 238) (R 65, G 105, B 225) (R 188, G 143, B 143) (R 128, G 0, B 0) dark green sky blue medium blue burly wood azure (R 0, G 100, B 0) (R 135, G 206, B 235) (R 0, G 0, B 205) (R 222, G 184, B 135) (R 240, G 255, B 255) olive drab light sky blue dark blue tan gainsboro (R 107, G 142, B 35) (R 135, G 206, B 250) (R 0, G 0, B 139) (R 210, G 180, B 140) (R 220, G 220, B 220) olive cyan navy sandy brown light gray (R 128, G 128, B 0) (R 0, G 255, B 255) (R 0, G 0, B 128) (R 244, G 164, B 96) (R 211, G 211, B 211) dark olive green medium turquoise midnight blue goldenrod silver (R 85, G 107, B 47) (R 72, G 209, B 204) (R 25, G 25, B 112) (R 218, G 165, B 32) (R 192, G 192, B 192) spring green turquoise corn silk peru dark gray (R 0, G 255, B 127) (R 64, G 224, B 208) (R 255, G 248, B 220) (R 205, G 133, B 63) (R 169, G 169, B 169) dark cyan cadet blue beige dark goldenrod gray (R 0, G 139, B 139) (R 95, G 158, B 160) (R 245, G 245, B 220) (R 184, G 134, B 11) (R 128, G 128, B 128) teal deep sky blue linen chocolate dim gray (R 0, G 128, B 128) (R 0, G 191, B 255) (R 250, G 240, B 230) (R 210, G 105, B 30) (R 105, G 105, B 105) medium aquamarine dodger blue antique white saddle brown slate gray (R 102, G 205, B 170) (R 30, G 144, B 255) (R 250, G 235, B 215) (R 139, G 69, B 19) (R 112, G 128, B 144) light sea green steel blue wheat sienna light slate gray (R 32, G 178, B 170) (R 70, G 130, B 180) (R 245, G 222, B 179) (R 160, G 82, B 45) (R 119, G 136, B 153) light cyan medium slate blue misty rose brown black (R 224, G 255, B 255) (R 123, G 104, B 238) (R 255, G 228, B 225) (R 165, G 42, B 42) (R 0, G 0, B 0)","","Balloon Flight","118 BALLOON FLIGHT How to build A cloudy backdrop Balloon Flight sets the scene. Take control of your own hot-air Pygame Zero Game balloon and try to avoid the obstacles that come your way as you fly. What happens When the game starts, a hot-air balloon appears in the middle of the screen. You need to use the mouse button to make the balloon rise or fall. The challenge is to keep the balloon in the air without hitting any birds, houses, or trees. For every obstacle you avoid, you\u2019ll score one point. But as soon as you hit one, the game is over. \u25c1 Balloon The balloon begins to drop as soon as the game starts. You can make it rise again by clicking the mouse. \u25c1 Obstacles The obstacles keep appearing at random positions. The player needs to avoid all the obstacles to stay in the game.","HOW TO BUILD BALLOON FLIGHT 119 Watch out for the bird as it flies across the screen. Score: 0 The clouds are part of the background, so you don\u2019t need to avoid them. The balloon moves up when you\u2019re pressing the mouse button and down when you\u2019re not pressing it. \u25c1 Up in the air The program creates the illusion of motion by making the obstacles appear at random intervals and moving them along the x-axis.","120 B A L L O O N F L I G H T How it works First you\u2019ll add the balloon and all the obstacles to the code. The program will check if the player has pressed the mouse button to move the balloon up, or hasn\u2019t to let it fall. Once an obstacle has disappeared off the left edge of the screen, the program will place a new one up to 800 pixels off the right edge of the screen at a random position to make the obstacles appear at random intervals. If the balloon hits any of the obstacles, the game will end and the top scores will be displayed. Start Add balloon N Add obstacles Has an obstacle Has the balloon N disappeared off the collided with an left side of the screen? Add one point to the score obstacle? Y Y Place obstacle at a random position Show high scores End off the right side of the screen Has the player Make balloon fall clicked the mouse? N Y \u25b3 Balloon Flight flowchart This flowchart maps the progress of the Move balloon up game, which constantly checks for obstacles disappearing off the screen, mouse clicks, and collisions between the balloon and the obstacles.","GAME PROGRESS 1 4 % 121 Up, up, and away! Before you take to the skies, it\u2019s important to understand the key elements used to build this game. The code is a bit long and tricky, so be extra careful when you\u2019re typing it out. 1 First steps 2 Set up an images folder Go to the python-games folder you made This game uses six images. Create a earlier and create a folder called balloon-flight new folder called images within your inside it. Now open IDLE and create an empty balloon-flight folder. Find the Balloon Flight file by going to the File menu and choosing images in the Python Games Resource Pack New File. Save this file as balloon.py in the (dk.com\/computercoding) and copy them balloon-flight folder. into the images folder as shown here. Save As: balloon.py balloon-flight Tags: balloon.py Where: balloon-flight images Cancel Save background.png balloon.png bird-down.png bird-up.png house.png tree.png 3 Create a file to store the high scores balloon-flight Next open a new file in IDLE and type the following code in it. From the File menu, select Save As... and balloon.py save the file as high-scores.txt in the balloon-flight high-scores.txt folder. Make sure you delete the .py extension. images 000 Make sure you put a space IDLE automatically adds .py to a file name. between each 0. So remember to change the extension to .txt when saving the file. 4 Import a module Now that your folders are ready, it\u2019s time to from random import randint start writing the code. First you need to import a module that\u2019s used in the program. Type this This function will be used to line at the top of your balloon.py IDLE file. generate random positions for the obstacles on the screen.","122 B A L L O O N F L I G H T 5 Set the screen size 6 Get the balloon ready Next you need to set the size of the screen Now you need to set up the Actors. First for your game. Type this code under the add the hot-air balloon, which the player line from Step 4. controls to play the game. WIDTH = 800 balloon = Actor(\\\"balloon\\\") This line creates HEIGHT = 600 balloon.pos = 400, 300 a new Actor using the This sets the screen This line places the balloon balloon image. size in pixels. in the center of the screen. 7 Prepare the obstacles This line makes the bird Next you need to set up the Actors for all the appear at a random position obstacles in the game. Create one for the bird, on the x-axis between 800 one for the house, and one for the tree. and 1600 pixels, and at a random position on the y-axis bird = Actor(\\\"bird-up\\\") between 10 and 200 pixels. bird.pos = randint(800, 1600), randint(10, 200) This value makes the This line creates a house = Actor(\\\"house\\\") tree appear on the new Actor using the house.pos = randint(800, 1600), 460 grass at the bottom image of the house. of the screen. tree = Actor(\\\"tree\\\") tree.pos = randint(800, 1600), 450 Pygame Zero Game EXPERT TIPS Functions The balloon A function is made up of two has to avoid parts\u2014a header and a body. birds, houses, The header is the first line of the and trees. function that includes the name and any parameters it has. The body is the code that the function runs when it\u2019s called. Name of the The function\u2019s function parameters def add(a, b): return a + b Body of the function","GAME PROGRESS 3 1 % 123 8 Create global variables EXPERT TIPS You can now set up the global variables. Add these lines after the Obstacles on screen code from Step 7. In Balloon Flight, the balloon stays in the This keeps track of the image used for the middle of the screen and the obstacles bird Actor. The image will be changed later move past it. This makes it look like it\u2019s in the game to make the bird look like it\u2019s the balloon that\u2019s moving. To make the flapping its wings. obstacles appear at random intervals, the game chooses a random position for each tree.pos = randint(800, 1600), 450 one to appear between 800 and 1600 pixels. Because the width of the screen is bird_up = True This line 800 pixels, the obstacles will first \u201cappear\u201d up = False keeps track of off screen, so you won\u2019t see them right game_over = False the player\u2019s away. Later on, you\u2019ll add code to make score = 0 score. these obstacles move from right to left, number_of_updates = 0 so the farther off screen an obstacle is placed, the longer it will take to appear scores = [] on screen. The upper limit is set to 1600 because otherwise the obstacles would This list stores the This variable keeps track of take too long to appear. top three high how many times the game scores for the game. has been updated to change The position of the image of the bird. the house on the y-axis is fixed at 460. house.pos = randint(800, 1600), 460 9 Manage the high scores The house can appear Next add placeholders for the functions that anywhere along the x-axis will manage the high scores. You will need a between 800 and 1600 pixels. function to update the scores and another to display them. The bodies of these functions I must steer clear of will be added later on. all these obstacles! scores = [] def update_high_scores(): pass def display_high_scores(): pass Use pass to create a function placeholder. You can define it later.","124 B A L L O O N F L I G H T 10 Create the draw() function This adds a background Just like in the other games you\u2019ve created, you now image of the sky, grass, need to add a draw() function to your code. You will also and clouds. add an image for the game background instead of just a solid color. Add these lines after the code from Step 9. def draw(): This line displays screen.blit(\\\"background\\\", (0, 0)) the score on screen. if not game_over: balloon.draw() bird.draw() house.draw() tree.draw() screen.draw.text(\\\"Score: \\\" + str(score), (700, 5), color=\\\"black\\\") If the game isn\u2019t over, this code will draw the Actors on screen. 11 Show high scores else: In the draw() function, you need to add display_high_scores() a call to display_high_scores() when the game is over. Type this immediately after Remember to add four This won\u2019t do anything yet the last line of code from Step 10. spaces before else. because you haven\u2019t written the body of this function. 12 Test your code Pygame Zero Game Now try running your code. You should see the balloon in the middle of the screen and a current Score: 0 score of zero. There won\u2019t be any obstacles on the screen yet\u2014these will only appear once you\u2019ve added some code to make them move onto the screen. You can see the background used in the game.","GAME PROGRESS 4 5 % 125 EXPERT TIPS 13 Reacting to mouse clicks Now you need to define two event handler Coordinates functions\u2014on_mouse_down() to make the balloon rise if the player pushes down In most programming languages, the coordinates on the mouse button, and on_mouse_up() (0, 0) refer to the top-left corner of the screen. to let the balloon fall if they release the Subtracting 50 pixels from the y-coordinate in button. Add this code under what you on_mouse_down() makes the balloon go 50 typed in Step 11. pixels closer to 0 on the y-axis, which is the top of the screen. Therefore, the balloon goes up. else: display_high_scores() I can\u2019t believe this def on_mouse_down(): is actually working! global up up = True balloon.y -= 50 These functions def on_mouse_up(): handle the mouse global up up = False button presses. EXPERT TIPS ? Quick! What\u2019s 4 + 4? Shorthand calculations With Python, you can perform a calculation using a variable and then store the result in the same variable. For example, to add 1 to a variable called a, you would usually write: a = a + 1. A shorter way to write this calculation and still get the same result is a += 1. You can also do this with subtraction, multiplication, and division. For example: a = a - 1 is the same as a -= 1 a = a \/ 1 is the same as a \/= 1 a = a * 1 is the same as a *= 1","126 B A L L O O N F L I G H T EXPERT TIPS 14 Make the bird flap Actor animations To make the bird more realistic, add a function to make it look like it\u2019s flapping You can make your Actors look like they\u2019re moving its wings. You don\u2019t need to do this for by using two or more different images of the same the other obstacles. Actor. For example, in this game, there are two images of a bird\u2014one with its wings up and one with its wings def flap(): down. By alternating between the two images, it looks global bird_up as if the bird is flapping its wings. The same function if bird_up: could make a person look like they\u2019re dancing, or a frog bird.image = \\\"bird-down\\\" look like it\u2019s jumping! bird_up = False else: bird.image = \\\"bird-up\\\" bird_up = True If the bird\u2019s wings are up, this code will change its image to the one where the bird\u2019s wings are down. 15 Create the update() function def update(): Now you need to create a function to update the game. Remember, update() global game_over, score, number_of_updates is a built-in function that automatically runs 60 times a second, so you don\u2019t This line declares the need to call it. Add this code right after variables the function the lines from Step 14. must change. 16 Add in gravity global game_over, score, number_of_updates Next add some code to make the balloon if not game_over: move down when the player isn\u2019t pressing the mouse button. Add this code to the if not up: update() function from Step 15. balloon.y += 1 17 Test your code If the mouse button Let\u2019s run the code again. This time is not being pressed, you\u2019ll see the same screen as in this moves the balloon Step 12, but the balloon should down by one pixel. react to mouse clicks.","GAME PROGRESS 65% 127 18 Move the bird Get out of the way! Next you need to add some code to make it look like the bird is flying across the screen If the bird is on the while flapping its wings. This code will move screen, this will move the bird to the left by four pixels to make it it to the left. seem like it\u2019s flying across the screen. balloon.y += 1 if bird.x > 0: This block of code will bird.x -= 4 make the bird flap its if number_of_updates == 9: wings every tenth time the flap() update() function is called. number_of_updates = 0 else: number_of_updates += 1 19 Handle the bird flying off the screen EXPERT TIPS When the bird disappears off the left edge of the screen, you need to move it back to a random Smooth animations position off the right side of the screen, just like you did at the beginning of the game. The In Python, the update() function is height at which the bird appears also needs to automatically called 60 times every be randomly chosen. Type the following code second. If you change the image of the immediately after the last line of code in Step 18. bird each time this function is called, it would just be a blur on the screen. To Remember to add This code places the bird at make the animation smoother, add a block eight spaces before a random position off the of code that will change the image every typing this line. right side of the screen. tenth time the function is called. You can change this interval if you want. But if the else: gap between the updates is too big, the number_of_updates += 1 bird will appear to move very slowly. else: Dude, you\u2019re so bird.x = randint(800, 1600) wrong! The actors aren\u2019t bird.y = randint(10, 200) score += 1 blurry at all! number_of_updates = 0 This adds one to the player\u2019s score for every obstacle that disappears off the screen.","128 B A L L O O N F L I G H T MOVING VAN 20 Move the house Just like you made the bird move across the screen, you now need to make the house move, too. Add this code under the lines from Step 19. else: bird.x = randint(800, 1600) bird.y = randint(10, 200) score += 1 number_of_updates = 0 if house.right > 0: If the house disappears off the house.x -= 2 left edge of the screen, this line places it at a random position else: off the right edge. house.x = randint(800, 1600) score += 1 EXPERT TIPS This line will update the Scrolling across the screen score by one if the house moves off the screen. Once the obstacles disappear off the screen, you need to move them back to the right-hand side 21 Move the tree of the screen. This is to create the illusion of motion Using the same logic as before, add these and make it look like lots of obstacles are appearing lines under the code from Step 20 to make on the screen when, in reality, you only use one the tree move across the screen. Actor for each type of obstacle in your code. Don\u2019t forget to count the Scrolling the same Actor across the screen means number of spaces before you don\u2019t have to create new Actors every time one each line of code. disappears off the screen. else: house.x = randint(400, 800) score += 1 if tree.right > 0: tree.x -= 2 else: tree.x = randint(800, 1600) score += 1","GAME PROGRESS 8 3 % 129 22 Keep it steady score += 1 Your game needs to end if the balloon hits the top or the bottom if balloon.top < 0 or balloon.bottom > 560: of the screen. Type this code under game_over = True the lines from Step 21. update_high_scores() 23 Handle collisions with obstacles This line checks if the Finally, you need to add some code to balloon has touched the end the game if the balloon hits any of top or bottom of the screen. the three obstacles. Add the code below. This checks if the balloon has hit any of the three obstacles. update_high_scores() This sets game_over if balloon.collidepoint(bird.x, bird.y) or \\\\ Use a backslash to True, which tells balloon.collidepoint(house.x, house.y) or \\\\ character if you balloon.collidepoint(tree.x, tree.y): need to split a long the program that the game_over = True line of code over game is over. update_high_scores() more than one line. This updates the high scores, if necessary. 24 Test your code Pygame Zero Game Save your program and run it from the command line. You Score: 0 should now be able to play the game, but it\u2019s not quite finished yet! Next you\u2019ll find out how to add high scores to your game. All the obstacles will now seem to move across the screen.","130 B A L L O O N F L I G H T 25 Update the high scores Now go back to the update_high_scores() function from Step 9 and write the body. This function gets the top three high scores and updates them if the player\u2019s current score has beaten one of them. Replace pass with the code in black below, then carefully follow the extra instructions to get the path for your high-score.txt file. def update_high_scores(): global score, scores filename = r\\\"\/Users\/bharti\/Desktop\/python-games\/balloon-flight\/high-scores.txt\\\" scores = [] This resets the list You will need to change this gray bit of code to the high-scores.txt of high scores. file's location on your own computer. Drag the high-scores.txt file into the Command Prompt or Terminal window, then copy and paste the path here and put quotation marks around it. Replace any backslashes \\\\ that look out of place with a space. 26 Get the current high scores To know if the player\u2019s score has beaten any of the This opens the high-scores.txt previous scores, you\u2019ll need to read the scores saved file for reading. in the high-scores.txt file you created in Step 3. Add this code under the lines from Step 25. Remember, the high scores = [] This function splits scores file only has one with open(filename, \\\"r\\\") as file: the high scores stored line. This reads the single in one line into three line = file.readline() different strings. line stored in the file. high_scores = line.split() EXPERT TIPS name = \\\"Martin,Craig,Daniel,Claire\\\" name.split(\\\",\\\") Splitting strings This parameter splits the string at each In this game, all the high scores are comma. If you don\u2019t provide a parameter, saved in a text file on a single line as a the function will split the string at the space string. To check if the player has beaten character, like in Step 26 of your program. any of these high scores, you need to split this string into three separate The list is returned with four separate strings. parts. Python\u2019s split() function can be used to split a string at a character and [\\\"Martin\\\", \\\"Craig\\\", \\\"Daniel\\\", \\\"Claire\\\"] then store the separate strings in a list. You can pass a parameter to the split() function telling it which character you want to split the string by.","GAME PROGRESS 9 7 % 131 EXPERT TIPS 12 10 8 This is an example 12 11 8 of an existing list Keeping score 12 11 10 of scores. Imagine the current high scores are 12, 10, 8, and a Once 11 has replaced player scores 11. If your code just replaced each score 10, you need to you\u2019ve beaten with the new score, you\u2019d end up with check 10, rather 12, 11, 11, which wouldn\u2019t be right. To avoid this, your than 11, against 8. code needs to compare the player\u2019s score with the top These are the new score first. 11 is less than 12, so it doesn\u2019t replace it. It three high scores. then needs to move on to the second-highest score. The next one, 11 is greater than 10, so it replaces it. Now that 11 is on the scoreboard, the code needs to check if 10, the score that was just replaced, is greater than the score currently in third place. Because 10 is greater than 8, it replaces it, and 8 is removed altogether. 27 Find the highest scores This loops Now write some code that will check if the current through the list score has beaten any of the three high scores. of high scores. Add this code under the lines from Step 26. This checks if the player\u2019s high_scores = line.split() score is higher than the for high_score in high_scores: existing high scores. if(score > int(high_score)): This sets score to scores.append(str(score) + \\\" \\\") the high score that score = int(high_score) was just beaten. else: scores.append(str(high_score) + \\\" \\\") If the player hasn\u2019t beaten the high If the player\u2019s score is higher score in question, that current than an existing high score, high score is added to the list. this adds it to the list. 28 Write the high scores in the file scores.append(str(high_score) + \\\" \\\") Use write() to write the new high score with open(filename, \\\"w\\\") as file: to the high-scores.txt file. Add this code under the code from Step 27. for high_score in scores: file.write(high_score) This block writes the new This opens the high-scores.txt high scores to the .txt file. file to be written to.","132 BALLOON FLIGHT EXPERT TIPS File handling In Balloon Flight, you\u2019ve used a .txt file to store the high scores. A file like this can be opened and assigned to a variable. The main functions that you need to handle the file are open(), read(), and write(). \u25b7 open() takes two parameters, the file name file = open(\\\"names.txt\\\", \\\"r\\\") and the \u201cmode,\u201d, which tells Python what you want to do with the file. There are four modes in Name of Mode Python: r for reading, w for writing, a for adding the file to the end of a file, and r+ for reading and writing. \u25bd Use the read() function to read an entire file. \u25bd You can also just read a single line, rather than the whole file. names = file.read() name = file.readline() \u25bd You can even add all the lines to a list. \u25bd Now use the write() function to write to a file. lines = [] for line in file: file = open(\\\"names.txt\\\", \\\"w\\\") file.write(\\\"Martin\\\") lines.append(line) \u25bd When you\u2019re finished with a file, you should \u25bd If you forget to close a file after using it, close it to tell the program you are done with it. some of the data may not get written to it. Use the with statement to stop this from file.close() happening. This statement opens the file and automatically closes it when it has finished It\u2019s time to close. Are running the body of the with statement. you sure you\u2019re done? with open(\\\"names.txt\\\", \\\"r\\\") as file: name = file.readline() Body of the function.","GAME PROGRESS 1 0 0 % 133 29 Display high scores Now that you\u2019ve written a function to collect the high scores, you need to write one to display them on the screen. Replace the word pass under def display_high_scores() from Step 9 with this code. def display_high_scores(): screen.draw.text(\\\"HIGH SCORES\\\", (350, 150), color=\\\"black\\\") y = 175 This sets the first This line writes position = 1 high score\u2019s position HIGH SCORES on the y-axis. on the screen. for high_score in scores: screen.draw.text(str(position) + \\\". \\\" + high_score, (350, y), color=\\\"black\\\") y += 25 position += 1 This adds to the y position, so This line displays the high that each high score is displayed scores on the screen. 25 pixels below the previous one. Hacks and tweaks Phew! I still have two lives left. There are lots of ways you can adapt this game to make it more complex. Here are some ideas you can try out. Pygame Zero Game HIGH SCORES lives = 3 1. 12 2. 9 \u25b3 Lives 3. 8 Why don\u2019t you give the player some more 4. 6 chances to complete the game? Introduce a 5. 3 new variable to keep track of a player\u2019s lives. Reduce the number by one every time the \u25b3 More high scores player hits an obstacle. When there are no Right now the game only stores the top three high scores. more lives left, the game ends. Can you change it to store the top five or ten? Remember the text file you created in Step 3 with three zeroes? How can you edit this file to store more high scores?","134 B A L L O O N F L I G H T I think I read about file handling on page 132 as well. bird.x -= 4 Make this number higher new_high_score = False to increase the speed. \u25b3 File handling \u25b3 Speed it up In the game, you write to the high-scores.txt file every time the program exits. It would be more efficient to write Do you want to make the game more to the file only if the high scores have changed. To code challenging? Why don\u2019t you make the obstacles this, you can use a Boolean variable to track whether go faster? You can do this by changing the the high scores have changed. In programming, this is number of pixels the obstacles move by. If you sometimes referred to as a \u201cflag.\u201d In the game, if the flag make the bird faster, remember to also update is set to True, then the high scores have changed and the flap() function to match the new speed. you have to write them back to the file. But if there is no change, there is no need to write anything to the file. I didn\u2019t know I could score points like this! \u25b3 Different way to score Name of the second bird obstacle. In the current game, the player scores a point every time an obstacle disappears off the left bird2 = Actor(\\\"bird-up\\\") edge of the screen. You can change the code so that the player scores every time they pass bird2.pos = randint(800, 1600), randint(10, 200) an obstacle on the screen. Can you figure out how to do this? Remember the position of the \u25b3 Add in multiples of each obstacle balloon always remains at 400 pixels along Do you find avoiding just one of each obstacle on the the x-axis. screen too easy? You could change the code so that more than one of each obstacle appears on the screen at the same time.","HACKS AND TWEAKS 135 \u25bd Level up EXPERT TIPS Make the game more fun by adding levels and increasing the speed with each level. To do this, you could set the Modulo operator number of obstacles in each level to ten. To complete the level, the player must clear all the obstacles and score ten When Python performs division, it ignores the points. Every time the score reaches a multiple of ten, remainder. But sometimes it\u2019s useful to know if make the obstacles move faster. In the original game, the there is a remainder and what it is. For example, birds move by four pixels at a time, and the houses and if you want to test if the number is even, you can trees move by two. If you want to increase it with every do so by dividing it by 2 and checking if there is level, you need to store the speed in a variable. Just a remainder. To do this, you can use the modulo remember that the bird should always be traveling twice operator %. as fast as the trees and houses. >>> print(2 % 2) speed = 2 0 bird.x -= speed * 2 This is 0 because there is no \u25bd Space out the obstacles remainder when 2 is divided by 2. Sometimes all the obstacles\u2014the tree, the house, and the bird\u2014might appear at the same >>> print(3 % 2) position on the x-axis. This works fine, but you 1 may want to avoid it. Try to change the update() function so that the obstacles pick a new random This is the remainder x coordinate if there is a clash. This code will when 3 is divided by 2. help you get started. In Balloon Flight, you can use the modulo if bird.x == house.x operator to know if the score is a multiple of 10, and therefore whether the player should move to the next level. score % 10 This would return the remainder when the score is divided by 10.","","Dance Challenge","138 DANCE CHALLENGE How to build Dance Challenge Get your groove on with this fast-paced Pygame Zero Game game. Watch the dancer move to the music and then put your memory skills Score: 0 to the test by repeating those moves. How long can you keep going without making a mistake? What happens In this game, the dancer performs a sequence of moves. You need to remember this sequence and make him repeat it using the four arrow keys on the keyboard. Each correct move will earn you a point. \u25c1 Dancer The dancer loves showing off his moves! Follow him carefully to keep on playing. \u25c1 Colored squares One of the squares is highlighted with a yellow outline each time the dancer switches from one move to another.","HOW TO BUILD DANCE CHALLENGE 139 You can use a different image for the background of the game. The dancer appears to dance by switching between different poses. Press the arrow keys in the right order to score points. This stage image sets the scene for your game. \u25c1 Ready to rock! This program uses different functions to make the dancer move and to highlight the colored squares. You can also create a countdown to give the player time to get ready to memorize the routine.","140 DANCE CHALLENGE How it works Start Are you up to Start music the challenge? You start this program by Generate moves setting up functions that will generate a sequence of dance moves, create a countdown, and then display the moves on the screen. The game will keep checking if you have pressed an arrow key and if it was the correct one. If you make a mistake, the game will end. EXPERT TIPS Show countdown \u25c1 Dance Challenge flowchart Display moves Adding music This simple flowchart shows how Display \u201cDance!\u201d the game fits together and how your In this game, you will need to add actions affect what happens next. If some music for your dancer to you manage to copy all the moves move to. Pygame Zero has some in the sequence in the right order, the special commands that make it game will loop around to create a new quite easy to do this. Each time sequence. This will continue to happen you add music to a game, set until you make a mistake. up a folder called music within your game\u2019s main folder, so that Y All moves in N Check the key pressed Pygame Zero knows where to by the player find the audio files. the sequence checked? See which move Y to check next Did it match the move? N End","GAME PROGRESS 13% 141 Hit the dance floor 1 Create a file in IDLE Open IDLE and create an empty Now that you\u2019ve worked out how the file by going to the File menu and game will work, it\u2019s time to put your dancing choosing New File. shoes on and get started! Begin by setting up and saving a new file, and then import File the Python modules you will need in this game. You will then use different Python New File functions to create the game. Open... 2 Save your game Save As: dance.py Go to the python-games folder you made Tags: earlier. Inside this folder, create another folder called dance-challenge and save your IDLE file Where: dance-challenge in it as dance.py. Cancel Save Nice save! Create this folder inside the python-games folder. 3 Set up an image folder 4 Put the images into the folder This game uses images of a dancer, a stage, Find the Dance Challenge files in the Python and eight colored squares with an arrow inside Games Resource Pack (dk.com\/computercoding), each. You\u2019ll need to create a new folder, called and copy them into the images folder. Leave the images, inside your dance-challenge folder. This .ogg audio file for the moment. folder has to be inside the same folder as your dance.py IDLE file. dance-challenge dance-challenge dance.py images dance.py images dancer-down.png dancer-left.png Within your dance-challenge There should be a dancer-right.png folder, right-click and choose total of 14 files in dancer-start.png New Folder to create the the images folder. dancer-up.png images folder. down-lit.png down.png left-lit.png left.png right-lit.png right.png stage.png up-lit.png up.png","142 DANCE CHALLENGE 5 Set up a music folder 6 Put the music file into the folder This game uses an audio file so that the dancer Go back to the Python Games Resource Pack, has something to dance to. The file needs its find the file called \u201cvanishing-horizon.ogg\u201d own folder, so create a new folder called music and copy it into the music folder. Your folders inside your dance-challenge folder. should look like this now. New Folder dance-challenge Get Info Clean up dance.py Clean up by images Sort by music vanishing-horizon.ogg \u25b6 \u25b6 7 Import a module from random import randint Now that you\u2019re all set up, it\u2019s time to get started on the code. Open the dance.py file in IDLE and This imports the randint() type this line of code at the top of the program. function from Python\u2019s You\u2019ll use randint() to generate random numbers Random module. that will represent different dance moves. 8 Set the stage WIDTH = 800 These variables Next you need to define the global HEIGHT = 600 define the size of variables. These are variables that can CENTER_X = WIDTH \/ 2 the game window. be used in any part of the program. CENTER_Y = HEIGHT \/ 2 Add this code next. These will move_list = [] contain lists of The stage is almost display_list = [] the dance moves. set. I can\u2019t wait to score = 0 These variables are get started! current_move = 0 assigned integer count = 4 values needed in dance_length = 4 the game. say_dance = False These are flag show_countdown = True variables that moves_complete = False keep track of game_over = False what\u2019s happening in the game.","GAME PROGRESS 3 5 % 143 9 Add the Actors dancer = Actor(\\\"dancer-start\\\") When the game Now it\u2019s time to define the dancer.pos = CENTER_X + 5, CENTER_Y - 40 starts, the Actors and set their starting dancer appears positions. Add this code under up = Actor(\\\"up\\\") in the starting what you typed in Step 8. up.pos = CENTER_X, CENTER_Y + 110 position in the right = Actor(\\\"right\\\") center of the This code will arrange the right.pos = CENTER_X + 60, CENTER_Y + 170 game window. colored squares in a cross down = Actor(\\\"down\\\") shape below the dancer. down.pos = CENTER_X, CENTER_Y + 230 left = Actor(\\\"left\\\") left.pos = CENTER_X - 60, CENTER_Y + 170 These lines tell Python which global variables you want to use in this function. 10 Draw the Actors def draw(): It\u2019s time to see what your game is going to look like. You can display global game_over, score, say_dance your Actors on the screen using Pygame Zero\u2019s built-in draw() global count, show_countdown function. Type this in next. if not game_over: This command is only run This line clears screen.clear() if the game isn\u2019t over. previous items drawn. screen.blit(\\\"stage\\\", (0, 0)) These lines draw all the Actors in their dancer.draw() current positions. up.draw() Use this function to This prints the down.draw() add a background in score in the top-left right.draw() the game window. corner of the screen. left.draw() screen.draw.text(\\\"Score: \\\" + str(score), color=\\\"black\\\", topleft=(10, 10)) return 11 Run the code Check pages 24\u201325 if you Save all the changes you\u2019ve made, and then go need to remind yourself how to the command line in the Command Prompt or Terminal window. Type in pgzrun and drag the to run your games. dance.py file into the window. Then press Enter.","144 D A N C E C H A L L E N G E Pygame Zero Game 12 First screen Score: 0 If your code is working properly, your game screen should look something like this. If not, there\u2019s no need to worry. Just go back to your code and use your debugging skills to check every line for possible errors, such as spellings and number of spaces. Take that! 13 Musical statues def reset_dancer(): This function will set You\u2019ve probably spotted a problem with your pass the Actors back to their dancer... he\u2019s not moving! Set up placeholders original positions. for the functions you\u2019re going to use to def update_dancer(move): change that. Add this code under what you pass This function updates typed in Step 10. the Actors to show a def display_moves(): dance move. REMEMBER pass This function will display Placeholders def generate_moves(): the latest sequence of pass moves generated by Using pass is a good way to list all the program. the functions you\u2019ll need so you don\u2019t def countdown(): forget anything. pass This function will generate a list of def next_move(): dance moves. pass This function will display def on_key_up(key): a countdown before each pass sequence of moves. def update(): This function will pass go to the next move in the list. This function will make the program react when you press a key. This is a built-in Pygame Zero function.","GAME PROGRESS 4 8 % 145 14 Random numbers 3 = Left 3 0 0 = Up Your program needs to generate dance sequences for you 1 1 = Right to memorize and repeat. The four possible moves are Up, Down, Left, and Right. You don\u2019t have a function that will 2 2 = Down generate random directions, but the randint() function will let you generate random numbers. If you assign each of the four moves a number, starting from 0, you will then be able to create random dance sequences. Step 15 will show you how to do this. 15 Let\u2019s move! This function will tell Don\u2019t forget to save The first function you need to define properly is update_dancer(). the dancer which your work. This changes the image of the dancer to match the dance move move to perform. he should perform. The colored square that corresponds to that dance move also changes to become outlined in yellow. Replace pass under the update_dancer(move) function from Step 13 with the code shown below. There\u2019s quite a lot to add, so be extra careful. This line tells def update_dancer(move): The value in move tells Python which global game_over the dancer which dance global variable if not game_over: move to do. Here, it\u2019s set if move == 0: to 0, which will mean Up. to use. up.image = \\\"up-lit\\\" dancer.image = \\\"dancer-up\\\" This line changes the This line highlights clock.schedule(reset_dancer, 0.5) image of the dancer. the colored square elif move == 1: right.image = \\\"right-lit\\\" The dancer will hold the for Up with a dancer.image = \\\"dancer-right\\\" move for half a second yellow outline. clock.schedule(reset_dancer, 0.5) before reset_dancer() elif move == 2: is called, returning him down.image = \\\"down-lit\\\" to the starting pose. dancer.image = \\\"dancer-down\\\" clock.schedule(reset_dancer, 0.5) else: left.image = \\\"left-lit\\\" dancer.image = \\\"dancer-left\\\" clock.schedule(reset_dancer, 0.5) return","146 D A N C E C H A L L E N G E def reset_dancer(): global game_over 16 Reset the Actors if not game_over: The dancer needs to return to the start position after dancer.image = \\\"dancer-start\\\" each move. The yellow-outlined arrow square that up.image = \\\"up\\\" corresponds to his dance move will also need to go right.image = \\\"right\\\" back to normal. To make a function to handle this, down.image = \\\"down\\\" replace the word pass under def reset_dancer() left.image = \\\"left\\\" from Step 13 with this code. return 17 Make a move def on_key_up(key): Next you need to write a function global score, game_over, move_list, current_move that makes the dancer perform a if key == keys.UP: move when you press one of the update_dancer(0) arrow keys on the keyboard. You elif key == keys.RIGHT: can use Pygame Zero\u2019s built-in tool update_dancer(1) on_key_up() to write an event- elif key == keys.DOWN: handler function to do this. Replace update_dancer(2) pass under the on_key_up(key) elif key == keys.LEFT: function from Step 13 with this code. update_dancer(3) return Each time an arrow key is pressed, the update_dancer() function is called with a parameter to make the dancer perform the relevant move. 18 Move those feet Pygame Zero Game It\u2019s time to see your dancer\u2019s moves! Save your file and run it from the Score: 0 command line. You will see the same screen as in Step 12, but this time A square is if you hit the Right key, the dancer highlighted to will perform the dance move match the arrow key assigned to that key. The square that you pressed. for the Right arrow will also get highlighted. The dancer and square will return to their starting images after half a second. Press the other arrow keys to test their moves, too.","GAME PROGRESS 6 1 % 147 19 Show me the steps Care to teach Now that you can make the dancer move with the arrow me flamenco? keys, he needs to display some computer-generated moves for the player to copy. Begin by writing the function that displays a sequence of moves to memorize. Replace pass under the display_moves() function from Step 13 with the code shown below. This line def display_moves(): This line stores the first checks if the global move_list, display_list, dance_length move in display_list in list of dance global say_dance, show_countdown, current_move the variable this_move. if display_list: moves has this_move = display_list[0] This removes the first item something in it. display_list = display_list[1:] from display_list so that if this_move == 0: the second item will now If the value of update_dancer(0) be at position 0. this_move is 0, clock.schedule(display_moves, 1) elif this_move == 1: If display_list is empty, it is passed on update_dancer(1) this line tells the draw() to this function. clock.schedule(display_moves, 1) function to display \u201cDance!\u201d elif this_move == 2: This line sets the This line update_dancer(2) global variable schedules a call clock.schedule(display_moves, 1) show_countdown to the function else: to False. display_moves() update_dancer(3) in one second. clock.schedule(display_moves, 1) else: say_dance = True show_countdown = False return","148 D A N C E C H A L L E N G E 20 Counting down EXPERT TIPS You don\u2019t want your players to be looking away when the next set of moves to memorize is displayed. Add a function that displays 3, 2, and Recursive functions then 1 with a one-second pause between each number. You\u2019ll actually count down from 4, but because the countdown() function begins by Both display_moves() and subtracting one from count, the number 4 doesn\u2019t appear on the countdown() are functions screen long enough to be seen. Replace pass under def countdown() that call themselves. These are from Step 13 with this code. known as recursive functions. Because Pygame Zero redraws def countdown(): This updates the the screen thousands of times global count, game_over, show_countdown value in count by every second, you need your if count > 1: subtracting one. recursive functions to schedule count = count - 1 a call to themselves one whole clock.schedule(countdown, 1) This line second later. Otherwise, the else: schedules moves and the countdown show_countdown = False another call to would be displayed too fast display_moves() the countdown() for even the most eagle-eyed return function in player to see! one second. This removes the Can you call me back countdown from the in a second? screen if count is less than or equal to one. 21 Show the countdown This line draws the Now that you\u2019ve defined a function for the countdown, you need word \u201cDance!\u201d on to add some code to the draw() function to display it. You will the screen in black. also need to display \u201cDance!\u201d when a new set of moves has been shown, so the player knows when to start entering the moves This line displays the using the arrow keys. Add this code to the draw() function that current value of count you started in Step 10. on the screen in black. screen.draw.text(\\\"Score: \\\" + str(score), color=\\\"black\\\", topleft=(10, 10)) if say_dance: screen.draw.text(\\\"Dance!\\\", color=\\\"black\\\", topleft=(CENTER_X - 65, 150), fontsize=60) if show_countdown: screen.draw.text(str(count), color=\\\"black\\\", topleft=(CENTER_X - 8, 150), fontsize=60) return"]
Search
Read the Text Version
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
- 62
- 63
- 64
- 65
- 66
- 67
- 68
- 69
- 70
- 71
- 72
- 73
- 74
- 75
- 76
- 77
- 78
- 79
- 80
- 81
- 82
- 83
- 84
- 85
- 86
- 87
- 88
- 89
- 90
- 91
- 92
- 93
- 94
- 95
- 96
- 97
- 98
- 99
- 100
- 101
- 102
- 103
- 104
- 105
- 106
- 107
- 108
- 109
- 110
- 111
- 112
- 113
- 114
- 115
- 116
- 117
- 118
- 119
- 120
- 121
- 122
- 123
- 124
- 125
- 126
- 127
- 128
- 129
- 130
- 131
- 132
- 133
- 134
- 135
- 136
- 137
- 138
- 139
- 140
- 141
- 142
- 143
- 144
- 145
- 146
- 147
- 148
- 149
- 150
- 151
- 152
- 153
- 154
- 155
- 156
- 157
- 158
- 159
- 160
- 161
- 162
- 163
- 164
- 165
- 166
- 167
- 168
- 169
- 170
- 171
- 172
- 173
- 174
- 175
- 176
- 177
- 178
- 179
- 180
- 181
- 182
- 183
- 184
- 185
- 186
- 187
- 188
- 189
- 190
- 191
- 192
- 193
- 194
- 195
- 196
- 197
- 198
- 199
- 200
- 201
- 202
- 203
- 204
- 205
- 206
- 207
- 208
- 209
- 210
- 211
- 212
- 213
- 214
- 215
- 216
- 217
- 218
- 219
- 220
- 221
- 222
- 223
- 224
- 225
- 226