Using While Loop to Play a Game Again
Program Arcade GamesWith Python And Pygame
Chapter four: Guessing Games with Random Numbers and Loops
The concluding step before nosotros offset with graphics is learning how to loop a department of code. Most games "loop." They echo the aforementioned lawmaking over and over. For instance the number guessing game below loops for each estimate that the user makes:
Hello! I'thou thinking of a random number between 1 and 100. --- Attempt ane Guess what number I am thinking of: 50 Too high. --- Endeavor 2 Guess what number I am thinking of: 25 Too high. --- Attempt iii Guess what number I am thinking of: 17 Besides loftier. --- Attempt 4 Guess what number I am thinking of: 9 Too low. --- Effort 5 Guess what number I am thinking of: xiv Too high. --- Try half-dozen Estimate what number I am thinking of: 12 Besides loftier. --- Try 7 Guess what number I am thinking of: 10 Also low. Aw, you ran out of tries. The number was 11.
Wait, what does this have to do with graphics and video games? A lot. Each frame the game displays is 1 fourth dimension through a loop. You may be familiar with the frames-per-2d (FPS) statistic that games evidence. The FPS represents the number of times the calculator updates the screen each second. The college the charge per unit, the smoother the game. (Although an FPS rate by 60 is faster than most screens can update, then there isn't much point to push it past that.) Effigy 4.ane shows the game Eve Online and a graph showing how many frames per second the computer is able to display.
The loop in these games works similar the flowchart in Figure 4.2. Despite the complexities of mod games, the inside of this loop is similar to the calculator plan we did in Chapter 1. Become user input. Perform calculations. Output the result. In a video game, we try to repeat this upwardly to 60 times per 2nd.
At that place tin fifty-fifty be loops within of other loops. A real "loop the loop." Take a expect at the "Draw Everything" box in Figure 4.2. This set of code loops through and draws each object in the game. That loop is inside of the larger loop that draws each frame of the game, which looks like Figure iv.3.
In that location are two major types of loops in Python, for loops and while loops. If you desire to repeat a certain number of times, utilise a for loop. If you want to repeat until something happens (like the user hits the quit push button) so use a while loop.
For example, a for loop can be used to print all student records since the computer knows how many students there are. A while loop would demand to exist used to check for when a user hits the mouse button since the calculator has no idea how long it will have to wait.
iv.1 For Loops
The for loop instance below runs the impress statement five times. It could just as hands run 100 or 1,000,000 times but past irresolute the v to the desired number of times to loop. Note the similarities of how the for loop is written to the if statement. Both end in a colon, and both apply indentation to specify which lines are afflicted by the argument.
for i in range(5): print("I will not chew gum in class.") | Output: I volition not chew mucilage in form. I will not chew glue in course. I volition not chew gum in class. I will non chew gum in class. I will not chew gum in course. |
The i on line 1 is a variable that keeps rails of how many times the program has looped. It is a new variable and can be named any legal variable name. Programmers often use i as for the variable proper name, because the i is brusk for increment. This variable helps track when the loop should finish.
The range function controls how many times the code in the loop is run. In this case, v times.
The adjacent example code will print "Delight," five times and "Can I become to the mall?" merely once. "Tin can I go to the mall?" is non indented and so information technology is non part of the for loop and volition non impress until the for loop completes.
for i in range(5): print("Please,") print("Can I go to the mall?") | Output: Please, Please, Please, Please, Delight, Can I go to the mall? |
This next lawmaking example takes the prior example and indents line three. This modify will cause the program to impress "Please," and "Can I become to the mall?" five times. Since the statement has been indented "Can I go to the mall?" is now office of the for loop and will repeat five times simply like the word "Please,".
for i in range(v): impress("Please,") print("Tin I get to the mall?") | Output: Please, Can I get to the mall? Please, Can I go to the mall? Please, Can I go to the mall? Please, Can I get to the mall? Please, Can I go to the mall? |
The code beneath will print the numbers 0 to 9. Notice that the loop starts at 0 and does not include the number 10. It is natural to assume that range(10) would include 10, but information technology stops just brusk of it.
for i in range(x): print(i) | Output: 0 1 2 3 4 5 6 vii viii nine |
A plan does not need to name the variable i, it could be named something else. For instance a programmer might employ lineNumber if she was processing a text file.
If a programmer wants to go from one to ten instead of 0 to 9, there are a couple ways to do it. The start way is to send the range function two numbers instead of ane. The first number is the starting value, the 2d is just across the ending value.
Information technology does accept some practise to go used to the idea that the for loop volition include the beginning number, but not the second number listed. The example below specifies a range of (ane,11), and the numbers 1 to 10 are printed. The starting number 1 is included, just not the ending number of 11.
for i in range(one, 11): print(i) | Output: 1 2 iii four 5 6 seven viii ix 10 |
Another way to impress the numbers ane to 10 is to nonetheless use range(ten) and have the variable i go from 0 to 9. Just just before printing out the variable the programmer adds one to information technology. This besides works to impress the numbers one to 10. Either method works only fine.
# Print the numbers 1 to 10. for i in range(10): print(i + 1)
4.1.1 Counting By Numbers Other Than One
If the program needs to count past 2's or use some other increment, that is like shooting fish in a barrel. But like before at that place are two means to practice it. The easiest is to supply a third number to the range function that tells it to count by two'southward. The second way to practice information technology is to go ahead and count by one'southward, just multiply the variable by 2. The code example below shows both methods.
# 2 means to print the even numbers 2 to 10 for i in range(2,12,2): impress(i) for i in range(5): print((i + 1) * 2) | Output: 2 iv six viii 10 two 4 half-dozen 8 ten |
It is likewise possible to count backwards down towards nil by giving the range part a negative step. In the example beneath, start at 10, go down to but not including 0, and do information technology by -1 increments. The hardest part of creating these loops is to accidentally switch the start and stop numbers. The plan starts at the larger value, and then it goes commencement. Normal for loops that count up showtime with the smallest value listed first in the range part.
for i in range(10, 0, -1): print(i) | Output: 10 9 8 7 six 5 iv 3 2 i |
If the numbers that a program needs to iterate through don't form an piece of cake blueprint, information technology is possible to pull numbers out of a list. (A full discussion of lists is covered in Chapter 7. This is merely a preview of what you tin do.)
for i in [2,6,4,2,four,half-dozen,7,4]: impress(i)
This prints:
two 6 4 ii 4 6 7 4
4.ane.2 Nesting Loops
Endeavor to predict what the code below will print. Then enter the code and see if you lot are correct.
# What does this impress? Why? for i in range(3): print("a") for j in range(3): print("b") This next block of code is most identical to the one above. The second for loop has been indented i tab cease then that it is at present nested inside of the start for loop. This changes how the code runs significantly. Attempt it and see.
# What does this print? Why? for i in range(3): print("a") for j in range(3): print("b") print("Done") I'g not going to tell y'all what the code does, go to a computer and come across.
4.1.three Keeping a Running Full
A common operation in working with loops is to keep a running total. This "running total" code design is used a lot in this book. Go on a running total of a score, total a person's business relationship transactions, employ a total to find an boilerplate, etc. You might desire to bookmark this code list because we'll refer back to it several times. In the code below, the user enters five numbers and the code totals up their values.
total = 0 for i in range(five): new_number = int(input("Enter a number: " )) full += new_number print("The total is: ", total) Notation that line 1 creates the variable total, and sets it to an initial amount of zero. Information technology is easy to forget the need to create and initialize the variable to zero. Without it the computer will mutter when it hits line 4. It doesn't know how to add new_number to total because total hasn't been given a value yet.
A common fault is to use i to total instead of new_number. Recall, we are keeping a running total of the values entered by the user, not a running total of the current loop count.
Speaking of the current loop count, we can apply the loop count value to solve some mathematical operations. For example:
$southward=\sum\limits_{n=1}^{100}n$
If you lot aren't familiar with this type of formula, information technology is just a fancy way of stating:
$s=1+2+3+4+v \ldots 98+99+100$
The lawmaking beneath adds all the numbers from 1 to 100. It demonstrates a common pattern where a running total is kept within of a loop. This as well uses a dissever variable sum to track the running total.
# What is the value of sum? sum = 0 for i in range(1, 101): sum = sum + i print(sum)
Here's a dissimilar variation. This takes five numbers from the user and counts the number of times the user enters a zero:
total = 0 for i in range(5): new_number = int(input( "Enter a number: ")) if new_number == 0: total += 1 print("You entered a total of", total, "zeros") A programmer that understands the nested for loops and running totals should be able to predict the output of the code below.
# What is the value of a? a = 0 for i in range(ten): a = a + ane print(a) # What is the value of a? a = 0 for i in range(10): a = a + 1 for j in range(10): a = a + 1 print(a) # What is the value of a? a = 0 for i in range(x): a = a + one for j in range(x): a = a + 1 print(a)
Don't go over this section likewise fast. Requite it a try and predict the output of the code above. So copy it into a Python program and run information technology to see if you are correct. If you lot aren't, effigy out why.
four.2 Example for Loops
This example lawmaking covers mutual for loops and shows how they work.
# Sample Python/Pygame Programs # Simpson College Estimator Science # http://programarcadegames.com/ # http://simpson.edu/computer-science/ # Print 'Hi' 10 times for i in range(ten): impress("Hello") # Print 'Hello' five times and 'There' in one case for i in range(5): impress("How-do-you-do") print("There") # Print 'Hullo' 'There' 5 times for i in range(5): print("Hello") print("There") # Print the numbers 0 to nine for i in range(10): print(i) # Two means to print the numbers ane to ten for i in range(1, 11): print(i) for i in range(10): print(i + 1) # Two ways to print the even numbers ii to 10 for i in range(2, 12, 2): impress(i) for i in range(5): impress((i + ane) * two) # Count down from 10 downward to i (not zero) for i in range(10, 0, -1): impress(i) # Impress numbers out of a list for i in [2, 6, four, 2, 4, vi, 7, 4]: print(i) # What does this print? Why? for i in range(3): print("a") for j in range(3): print("b") # What is the value of a? a = 0 for i in range(10): a = a + i print(a) # What is the value of a? a = 0 for i in range(10): a = a + one for j in range(10): a = a + 1 impress(a) # What is the value of a? a = 0 for i in range(10): a = a + 1 for j in range(10): a = a + ane print(a) # What is the value of sum? sum = 0 for i in range(ane, 101): sum = sum + i four.3 While Loops
A for loop is used when a plan knows information technology needs to repeat a block of code for a sure number of times. A while loop is used when a program needs to loop until a detail condition occurs.
Oddly enough, a while loop tin can be used anywhere a for loop is used. It tin can be used to loop until an increment variable reaches a certain value. Why accept a for loop if a while loop can practice everything? The for loop is simpler to utilise and code. A for loop that looks like this:
for i in range(10): print(i)
...tin exist done with a while loop that looks like this:
i = 0 while i < 10: print(i) i = i + ane
Line one of the while loop sets up a "lookout" variable that will be used to count the number of times the loop has been executed. This happens automatically in a for loop eliminating one line of lawmaking. Line 2 contains the bodily while loop. The format of the while loop is very similar to the if statement. If the condition holds, the code in the loop will repeat. Line 4 adds to the increment value. In a for loop this happens automatically, eliminating another line of code. Equally 1 can see from the lawmaking, the for loop is more compact than a while loop and is easier to read. Otherwise programs would do everything with a while loop.
A common mistake is to confuse the for loop and the while loop. The code below shows a developer that tin't quite make up his/her heed between a for loop or a while loop.
while range(10): impress(i)
Don't utilise range with a while loop!
The range function only works with the for loop. Do not utilise it with the while loop!
4.three.1 Using Increment Operators
Increment operators are often used with while loops. Information technology is possible to curt-hand the code:
i = i + 1
With the post-obit:
i += 1
In the while loop information technology would look similar:
i = 0 while i < 10: print(i) i += one
This can be washed with subtraction and multiplication also. For example:
i *= 2
Is the same every bit:
i = i * ii
Encounter if you can figure out what would this impress:
i = one while i <= 2 ** 32: print(i) i *= ii
4.three.2 Looping Until User Wants To Quit
A very common operation is to loop until the user performs a request to quit:
quit = "n" while quit == "n": quit = input("Do you want to quit? ") There may be several means for a loop to quit. Using a Boolean variable to trigger the event is a manner of handling that. Here's an example:
done = False while not done: quit = input("Do you lot want to quit? ") if quit == "y": done = True attack = input("Does your elf attack the dragon? ") if attack == "y": print("Bad selection, you died.") done = Truthful This isn't perfect though, because if the user says she wants to quit, the lawmaking will all the same ask if she wants to attack the dragon. How could y'all fix this?
Here is an example of using a while loop where the code repeats until the value gets close enough to 1:
value = 0 increment = 0.v while value < 0.999: value += increase increment *= 0.5 impress(value)
four.3.iii Common Problems With while Loops
The developer wants to count down from ten. What is wrong and how tin it exist fixed?
i = 10 while i == 0: print(i) i -= 1
What is incorrect with this loop that tries to count to 10? What will happen when it is run? How should information technology be fixed?
i = ane while i < 10: print(i)
iv.4 Example while Loops
Here'due south a program that covers the different uses of the while loop that we merely talked nigh.
# Sample Python/Pygame Programs # Simpson College Calculator Scientific discipline # http://programarcadegames.com/ # http://simpson.edu/computer-science/ # A while loop tin can be used anywhere a for loop is used: i = 0 while i < 10: print(i) i = i + 1 # This is the same equally: for i in range(10): print(i) # Information technology is possible to brusk hand the code: # i = i + 1 # With the following: # i += 1 # This can be done with subtraction, and multiplication equally well. i = 0 while i < ten: print(i) i += one # What would this impress? i = 1 while i <= 2**32: print(i) i *= 2 # A very common operation is to loop until the user performs # a request to quit quit = "n" while quit == "northward": quit = input("Do you want to quit? ") # In that location may be several ways for a loop to quit. Using a boolean # to trigger the outcome is a way of handling that. washed = False while not done: quit = input("Do you lot want to quit? ") if quit == "y": done = Truthful attack = input("Does your elf attach the dragon? ") if assault == "y": print("Bad option, you died.") done = True value = 0 increment = 0.5 while value < 0.999: value += increase increase *= 0.five print(value) # -- Common bug with while loops -- # The programmer wants to count down from x # What is wrong and how to set up it? i = 10 while i == 0: print(i) i -= 1 # What is wrong with this loop that tries # to count to x? What volition happen when it is run? i = 1 while i < x: impress(i) 4.5 Random Numbers
Random numbers are heavily used in computer science for programs that involve games or simulations.
4.v.1 The randrange Function
By default, Python does not know how to make random numbers. Information technology is necessary to have Python import a code library that can create random numbers. Then to apply random numbers, the first thing that should announced at the top of the program is an import argument:
import random
Just like with pygame, it is important non to create a file with the same name every bit what is being imported. Creating a file called random.py will cause Python to showtime importing that file instead of the system library that creates random numbers.
Subsequently this, random numbers can be created with the randrange function. For example, this code creates random numbers from 0 to 49. Past default the lower bound is 0.
my_number = random.randrange(50)
The next code example generates random numbers from 100 to 200. But like the range function the 2nd parameter specifies an upper-bound that is non inclusive. Therefore if you desire random numbers up to and including 200, specify 201.
my_number = random.randrange(100, 201)
What if you don't want a number, but a random item? That requires a list. We don't cover lists in particular until Chapter 7, just to give you preview of what selecting a random item out of a list would wait similar, see below:
my_list = ["rock", "newspaper", "scissors"] random_index = random.randrange(iii) print(my_list[random_index])
4.5.two The random Part
All of the prior code generates integer numbers. If a floating point number is desired, a programmer may apply the random function.
The code below generates a random number from 0 to 1 such as 0.4355991106620656.
my_number = random.random()
With some uncomplicated math, this number can be adapted. For example, the code below generates a random floating signal number betwixt x and 15:
my_number = random.random() * 5 + 10
four.six Review
4.vi.1 Multiple Selection Quiz
Click here for a multiple-selection quiz.
4.6.2 Short Answer Worksheet
Click here for the affiliate worksheet.
4.vi.3 Lab
Click here for the chapter lab.
You are not logged in. Log in here and track your progress.
Source: http://programarcadegames.com/index.php?chapter=loops
0 Response to "Using While Loop to Play a Game Again"
Post a Comment