PyGame Lesson 3 Learner resource.pdf
Document Details
Uploaded by CapableTsavorite
Curro Rivonia
Tags
Full Transcript
Python Game Coding Level 1 | Learner resource | Lesson 3 Making decisions, Branching and Loops Making decisions When we play a game, we often have to make decisions about what we should do next. Computers can also m...
Python Game Coding Level 1 | Learner resource | Lesson 3 Making decisions, Branching and Loops Making decisions When we play a game, we often have to make decisions about what we should do next. Computers can also make decisions in games by asking questions! They do this by comparing different values. Boolean values In Python, Boolean values help us answer questions with either a "yes" or a "no". It's like playing a game of "true or false" with the computer! Boolean values can only have two possible states: True or False. We use these values to represent whether something is true or false in our code. They MUST START WITH A CAPITAL LETTER. You can store Boolean values in a variable. Logical operators You can also use Logical Operators to make comparisons, such as equal to or if something has a bigger or smaller value. See the image below: 1 Python Game Coding Level 1 | Learner resource | Lesson 3 The following list provides a simplified explanation of all Python keywords. and: A way to combine two conditions and check if both are true. as: Used to give a nickname to a module or object, making it easier to use. assert: A way to make sure something is true. If it's not, it'll create a fuss by raising an AssertionError break: Press this button to make a loop stop early and move on to the next thing. class: Imagine it as a blueprint for creating your own custom objects. continue: Skip the rest of the current round of a loop and go straight to the next round. def: Create your own superpower by defining a custom function. del: Make a variable or item disappear! elif: When there are more conditions to check after "if," this is where you go. else: If none of the other conditions are true, do this instead. except: Catch specific mistakes that might happen and handle them gracefully. finally: No matter what happens, this code will always run. for: Loop through a list of things and do something for each item. from: Import items you need from a library. global: Declare a superpower that can be used anywhere, inside or outside functions. if: Make decisions in your code by checking if something is true. import: Bring in modules or objects from other files or libraries. in: Check if something is a part of a group or collection. is: Compare two things and see if they are exactly the same. lambda: Create quick, anonymous functions when you want it. not: Flip a condition to its opposite, like turning "True" to "False." or: Combine conditions and see if at least one of them is true. pass: When you want to skip a step for now, just leave a placeholder. raise: Throw your own custom error or problem into the mix. return: Exit a function and give back a value to the code that called it. try: Put code here that might cause trouble, and handle those troubles wisely. while: Keep doing something as long as a certain condition stays true. with: Make sure something important happens before and after some code. yield: Special move to temporarily pause a function and share a value. 2 Python Game Coding Level 1 | Learner resource | Lesson 3 Complete the guided activities for Activity 1-11 on the Inspire Campus. Follow the prompts on the Inspire Campus. Operators = and == The = operator In Python, the = operator is used to assign a value to a variable. It's like giving a name to something. For example: score=10 In this code, we're assigning the value 10 to the variable named score. It means that we're saying "score is equal to 10." We use the = operator to make this assignment. The == Operator: The == operator is used to compare two values to see if they are equal or not. It helps us check if two things are the same. For example: 3 Python Game Coding Level 1 | Learner resource | Lesson 3 Comparing values You can use the > < and == operators to compare values which will result in a True or False output. In the example below we used the = operator to assign the value 2 to tigers and 4 to bones. By using the other operators, we can compare the results. Multiple comparisons You can also use and or or, to compare multiple comparisons. For and - BOTH comparisons need to be correct for it to be TRUE. For or - only ONE comparison needs to be correct for it to be TRUE otherwise the result will be FALSE. Branching In a computer game, you often need to make decisions based on what's happening. Sometimes, the computer itself can make those decisions for us! This is called branching. We commonly use if, else and elif in branching. Branching is like having different paths or choices in a game. The computer can run specific code only in certain situations. It's like the computer making the decision on what to do next. 4 Python Game Coding Level 1 | Learner resource | Lesson 3 One branch –if: The simplest type of branching command is an if statement. It only has one branch that the computer takes. After the if statement you must add a colon: Two branches – if…else In coding, we have a special command called an if else statement. It's like a way to make our game do different things based on whether a condition is true or false. With the if else statement, we can code our game to do one thing if the condition is true and another thing if the condition is false. It's like having a backup plan if the first condition isn't true. 5 Python Game Coding Level 1 | Learner resource | Lesson 3 Three branches – if else, elif Sometimes in our games, we have more than two options or conditions to consider. That's where the elif statement comes in handy! The word "elif" stands for "else- if" and allows us to check multiple conditions one by one. An elif statement must ALWAYS come after and if and before an else. The elif statement allows us to consider different possibilities and make our game respond accordingly. It's like having multiple choices or paths to follow, depending on the conditions we encounter. Loops When we're creating a game with code, there are moments when we want to do something again and again. It would be tedious if we had to type the same code over and over again. Luckily, we have a clever solution called loops! For loop The for loop counts for us and performs a task a certain number of times. In this code, the for loop starts with the keyword "for" and the variable name "number." It tells Python to count from 1 to 11. The "in range" (1, 11) part means we want the numbers from 1 up to (but not including) 11. Then, the loop runs the indented code block, which prints each number on the screen. 6 Python Game Coding Level 1 | Learner resource | Lesson 3 For loop – count in range Count is a Python built-in function that returns the number of times an object appears in a list. In this range, we are commanding the computer to repeat the phrase High five! 10 times. Looping over a list In this example, you can create a list and then move along the list. Looping over two lists In this example you can loop through two lists at once by using the index. List for the villains List for their super_power The variable introduced here is the index. The index will print the name of the villain and state its super_power. Take note of the [index]square bracket. 7 Python Game Coding Level 1 | Learner resource | Lesson 3 While loop (and input) Sometimes in a game, we're not sure how many times we need to repeat a certain action. That's when we can use a while loop. A while not loop has a question, called the "loop condition," and the answer to this question can be either True or False. The while loop will only start if the answer to the loop condition is True. Let's consider an example: Imagine you're coding a game where you need to find a sword before you can attack a powerful villain. The loop condition would be "Do you have a sword?" and the actions to attack the villain would be inside the loop body. Make sure the loop condition can eventually become False; otherwise, the loop could go on forever, like an endless game loop! In the code below we are using an input. This requires to user to answer questions. Infinite loop While true is an infinite loop that will continue to run unless you close it..lower() The purpose of using.lower() in the above context is to perform a case- insensitive comparison. By converting the strings to lowercase, any variations in capitalization (e.g., "Yes", "YES", "yes") will be considered equivalent when compared to the lowercase string "yes". 8 Python Game Coding Level 1 | Learner resource | Lesson 3 Python Purpose Code Booleans Boolean values help us answer True questions with either a "yes" or False a "no". Booleans can only have two possible states – True and False. True and False are always start with a capital letter. The = The = operator is used to assign score=10 operator a value to a variable. It's like giving a name to something. The == The == operator is used to age=13 operator compare two values to see if if age ==13: they are equal print(“You are 13 years or not. old”) Comparing You can use the > < and == tigers=2 values operators to compare values bones=4 which will tigers>bones result in a True or False output. False Multiple You can also use and or or, tigers=2 comparisons to compare multiple bones=4 comparisons. (tigers==2) and (bones==4) For and - BOTH True (tigers==6) or (bones==4) comparisons need to be correct True for it to be TRUE. (tigers==6) or (bones==6) For or - only ONE False comparison needs to be correct (tigers==6) and (bones ==6) for it to be TRUE False if It only has one branch that the door=”red” computer takes. if door==”red”: After the if statement you print(“Congratulations, you must add a colon: won a sheep!”) 9 Python Game Coding Level 1 | Learner resource | Lesson 3 if…else With the if else statement, treasure_found=True we can code our game to do one if treasure_found: thing if the condition is true and print(“You found a another thing if the condition is treasure!”) false. else: print(Nothing here…”) If else elif allows you to create more treasure_found=”diamond” if treasure_found==”gold”: elif than two branches. An elif statement must print(“Nice one, you found gold”) ALWAYS come after if and elif treasure_found==”silver”: before an else. print(“Awesome, silver is great”) else: print(“You’re not so lucky, keep searching”) for The for loop counts for us and for number in range(1,11): print(number) number performs a task a certain number of times. The "in range" (1, 11) part 1 2 means we want it to count the 3 numbers from 1 up to (but not 4… including) 11. count in count is a Python built-in for count in range(1,11): print(“High five!”) range function that returns the number High Five! of times an object appears in a list. High Five! in this range, we are High Five! High Five!.... commanding the computer to repeat the phrase High five! ten times. index The index helps you find the treasure_found="diamond" index position of an element or villains=["Shadowstrike", an item in a string of characters "Venomfang", "Drakomatrix"] or a list of items. super_power=["steal your shadow", "poison my victims", "can breathe fire"] index = 0 for each in villains: print("Beware! I am " + villains[index] + ". I can " + super_power[index]) index=index + 1 10 Python Game Coding Level 1 | Learner resource | Lesson 3 while A while not loop has a have_sword=False question, called the "loop while not have_sword: condition," and the answer to answer=input(“Do you have a this question can be either True sword? (yes/no): ”) or False. The while loop will only if answer.lower()==”yes” start if the answer to the loop have_sword=True condition is True. print(“You can now attack”) else: print(“Keep searching for a sword!”) Infinite loop while true is an infinite while True: loop that will continue to run print(“This will go on while forevvver”) unless you close it. true input When using input, the user is wake_up = input("Did you wake required to write a response. up on time? (yes/no): ") Write the response in (brackets) with a : and space before closing the string. 11 Python Game Coding Level 1 | Learner resource | Lesson 3 Lesson 3: Independent Activity Complete this activity in the Editor Window so that you can save it. Open a New Folder in IDLE and save this code as Python Game Coding Lesson 3. Create a “Ready for school” input code. Create a list of five items that you need to do before going to school. Create an input for each of the items: You may use the example below or create a different scene. wake_up = input("Did you wake up on time? (yes/no): ") brush_teeth = input("Did you brush your teeth? (yes/no): ") eat_breakfast = input("Did you eat breakfast? (yes/no): ") get_dressed = input("Are you dressed for school? (yes/no): ") if wake_up.lower() == "yes" and brush_teeth.lower() == "yes" and eat_breakfast.lower() == "yes" and get_dressed.lower() == "yes": print("Great job! You're ready for school!") else: print("Make sure to complete all the necessary tasks before going to school.") 12