Some advice to help you implement the cars and trucks assignment:
Consider a rectangle shape from the drawCar method as an example. The rectangle’s upper left corner is at (100,150), width is 100, and height is 50.
def drawCar(x,y,scale):
pygame.draw.rect(surface, color,(100 + x, 50 + y, 100 * scale, 50 * scale)
# more shapes completing the car drawing
Then in “main”:
vehicle = random.randint(1,2)
x = random.randint(20,30)
y = random.randint(10,20)
scale = random.random()
if vehicle == 1:
drawCar(x,y,scale)
else:
drawTruck(x,y,scale)
1. Define all definitions without x, y and scale. 2. Test them all 3. Include x and y and test your program again. 4. Include the scale and test your program again. 5. Include the random component
doRectsOverlap and isPointInsideRect: Collision detection is figuring when two things on the screen have touched (that is, collided with) each other. For example, if the player touches an enemy they may lose health. Or the program needs to know when the player touches a coin so that they automatically pick it up. Collision detection can help determine if the game character is standing on solid ground or if there’s nothing but empty air underneath them.
In our games, collision detection will determine if two rectangles are overlapping each other or not. Our next example program will cover this basic technique.
Later in this chapter, we’ll look at how our Pygame programs can accept input from the user through the keyboard and the mouse. It’s a bit more complicated than calling the input() function like we did for our text programs. But using the keyboard is much more interactive in GUI programs. And using the mouse isn’t even possible in our text games. These two concepts will make your games more exciting!
Source Code of the Collision Detection Program
Much of this code is similar to the animation program, so the explanation of the moving and bouncing code is skipped. (See the animation program in the Animating Graphics Chapter for that.) A block will bounce around the window and bounce off each other.
On each iteration through the game loop, the program will read each Rect object in the list and the blocks will have a reaction.
The block is represented by a dictionary. The dictionary has a key named ‘rect’ (whose value is a pygame.Rect object) and a key named ‘dir’ (whose value is one of the constant direction variables like we had in last chapter’s Animation program).
Use the functions below to make the block react differently when they are close to each other.
## BouncingBlocks.py
## copy the animation.py
import pygame, sys, random
from pygame.locals import *
## add these two functions
def doRectsOverlap(rect1, rect2):
for a, b in [(rect1, rect2), (rect2, rect1)]:
# Check if a's corners are inside b
if ((isPointInsideRect(a.left, a.top, b)) or
(isPointInsideRect(a.left, a.bottom, b)) or
(isPointInsideRect(a.right, a.top, b)) or
(isPointInsideRect(a.right, a.bottom, b))):
return True
return False
def isPointInsideRect(x, y, rect):
if (x > rect.left) and (x < rect.right) and (y > rect.top) and (y < rect.bottom):
return True
else:
return False
How to use the functions:
if b['rect'].right > WINDOWWIDTH+15:
# block has moved past the right side
if b['dir'] == DOWNRIGHT:
b['dir'] = DOWNLEFT
if b['dir'] == UPRIGHT:
b['dir'] = UPLEFT
##### add the call to the doRectsOverlap by pairs of blocks
##### Make sure the indentations make sense!!!
if doRectsOverlap(b3['rect'], b2['rect']):
if b3['dir'] == UPLEFT:
b3['dir'] = DOWNLEFT
if b3['dir'] == UPRIGHT:
b3['dir'] = DOWNRIGHT
#### what other pairs do you want to check for overlaps???
# draw the block onto the surface
pygame.draw.rect(windowSurface, b['color'], b['rect'])
# draw the window onto the screen
pygame.display.update()
time.sleep(0.02)
2nd version of the Collision Detection is the program RepellGobbler_YI.py, the green food bounces off the bouncer as it gets closer to it.
Note: The food doesn’t have to bounce off the edges of the window. They run off the window for the RepellGobbler_YI.py. Hint for TheGobbler.py: use the attributes of the rectangle: width and length to increase the size of the gobbler. bouncer[‘rect’].width and bouncer[‘rect’].height.
Classwork: Discussions on concepts you should know:
pygame is so advanced that even the pygame module has its own modules
pygame.locals module contains many constant variables QUIT, K_ESCAPE and many more.
pygame.init() must always be included in your pygame programs
pygame.display.set_mode((500, 400), 0, 32) creates a pop up window of width 500 pixels and height 400 pixels. 0 is used for more options and color 32 for depth. If you want to know more about this syntax, here is the link
Surface object represents pop up windows.
Differences between values and reference values: a list variable name is actually a reference, the contents of the list are the values.
RGB referes to Red, Green and Blue
This method: basicFont.render(‘Hello world!’, True, WHITE, BLUE) creates a Surface object with the text drawn on it
Anti-aliasing can make your text and lines look blurry but smoother
A pygame rectangle is an object: Rect((left, top), (width, height)). pygame.Rect(left, top, width, height)
pygame.Rect objects have attributes, variables that are associated with an object
pygame.Rect objects have behaviors, methods that are associated with an object
But you can draw a rectangle with this syntax:pygame.draw.rect(windowSurface, color,( x , y , width, heigth))
where x is the x coordinate and y is the y-coordinate of the upper left corner of the rectangle.
If you are including text in your pygmae window,
text = basicFont.render(‘Hello world!’, True, WHITE, BLUE)
textRect = text.get_rect()
The next step then is to render the text by using the blit method: windowSurface.blit(text, textRect)
Important: before blit-ting and before drawing: windowSurface.fill(WHITE)
In Pygame, nothing is drawn to the screen until the pygame.display.update() function is called.
Finally, no pygame should miss the next lines:
while True: ….for event in pygame.event.get(): ……..if event.type == QUIT: …………pygame.quit() …………sys.exit()
The End
Homework: Read chapter 17 topics we covered in class.
Classwork: Modify CollisionDetection program so the green food bounces off the bouncer as it gets closer to the it, YI_RepellGobbler.py. Note: The food doesn’t have to bounce off the edges of the window. They run off the window.
3rd version of the Collision Detection is the program YI_RainyGobbler.py, the green food falls off the top of the window as the bouncer moves throuh the window in its own fashion way.
Classwork: Continue working on the program, WallBouncing_YI.py.
Home work: Keep on reading chapter 17.
Visit edmodo.com to answer the following questions from your reading material:
1. If a block is moving DOWNLEFT, how is the x coordinate behaving? how is the y coordinate behaving?
2. If a block is moving DOWNRIGHT, how is the x coordinate behaving? how is the y coordinate behaving?
3. If a block is moving UPLEFT, how is the x coordinate behaving? how is the y coordinate behaving?
4. If a block is moving UPRIGHT, how is the x coordinate behaving? how is the y coordinate behaving?
5. If a block is moving UPRIGHT, when would it bounce off the top of the window?
6. If a block is moving UPRIGHT, when would it bounce off the right side of the window?
7. If a block is moving DOWNRIGHT, when would it bounce off the bottom of the window?
8. If a block is moving UPLEFT, when would it bounce off the left side of the window?
9. Why did the author pick numbers 1, 3, 7, and 9 for the constants DOWNLEFT, DOWNRIGHT, UPLEFT AND UPRIGHT?
Think about your next program. It will be related to the animation.py but with a simple maze.
Classwork: Write a program, YI_BouncingOffWall.py similar to animation.py but with a short wall in the center of the window.
Challenge: Two walls in the center where the blocks will go through it. (Optional)
Home work: Keep on reading chapter 17.
Think about your next program. It will be related to the animation.py but with a simple maze.
Classwork: Write a pygame program, BouncingInMaze_YI.py. Use the code you learned in animation.py but with a simple maze like the one below.
Some of last previous years’ mazes:
Homework:
Visit edmodo.com to answer the following questions from Chapter 17 reading material:
1. If a block is moving DOWNLEFT, how is the x coordinate behaving? how is the y coordinate behaving?
2. If a block is moving DOWNRIGHT, how is the x coordinate behaving? how is the y coordinate behaving?
3. If a block is moving UPLEFT, how is the x coordinate behaving? how is the y coordinate behaving?
4. If a block is moving UPRIGHT, how is the x coordinate behaving? how is the y coordinate behaving?
5. If a block is moving UPRIGHT, when would it bounce off the top of the window?
6. If a block is moving UPRIGHT, when would it bounce off the right side of the window?
7. If a block is moving DOWNRIGHT, when would it bounce off the bottom of the window?
8. If a block is moving UPLEFT, when would it bounce off the left side of the window?
9. Why did the author pick numbers 1, 3, 7, and 9 for the constants DOWNLEFT, DOWNRIGHT, UPLEFT AND UPRIGHT?
Classwork: Write a pygame program, MazeBouncing_YI.py. Use the code you learned in animation.py but with a simple maze like the one below.
Homework:
Visit edmodo.com to answer these questions from Chapter 17.
1. Coming soon. 2. What is 0.2 in the line: time.sleep(0.2)? How is it calculated? 3. What would happen if time.sleep(0.2) was omitted? 4. What would happen if windowSurface.fill(BLACK) was omitted and time.sleep(0.2) is changed to time.sleep(1.0)?
Write a python/pygame program, memoryCards2_YI.py similar to previous program, flashCards1_YI.py. However, in this program the user doesn’t know where the matching card is since the cards are not showing their images. If the user guesses right, the sound should indicate so and the two cards go away. Just like in the previous assignment the sound indicate when it is wrong. The card should be expose so the user will remember where the cards are.
Homework: Start reading chapter 14 – Caesar Cipher
Classwork: Modify CollisionDetection program so the bouncer gets bigger when it eats the green food, TheGobbler_YI.py.
Announcement: Sean Shypula will be visiting PHS today. He will be talking about his journey from high school student to his current life on the “Bungie Farm”. We will welcome Sean in room 242 during periods 6 and 7. NOTE: make sure your permission slip gets signed by Wednesday.
Short Bio: Sean Shypula grew up in Miami, FL and from a young age was fascinated with computers and all things electronic. In an age before the widespread use of the internet, he managed to teach himself how to write simple programs on his Commodore 64 based upon a few CS books found in a public library, bits of source code found in the back pages of Byte magazine, and a lot of trial and error. He followed this passion into college earning a degree in Computer Engineering from the University of Florida in 2003. After college he decided to pursue his true goal of one day being able to make video games for a living, and in 2006 earned a Master’s degree in Computer Science from DigiPen Institute of Technology in Redmond, Washington. Sean was quickly hired by Bungie Studios, where he has happily been building the studio’s tools and infrastructure ever since. Sean’s credits include Halo 3, Halo ODST, Halo Reach, and the soon-to-be-released Destiny, which will be the first of a long series of games and the first new franchise for the studio since gaining their independence from Microsoft in 2007.
On edmodo.com:
1. What is the syntax to load an image?
2. What type of files can be images for pygame?
3. What is the syntax that defines the size of the image?
4. How do you create a pygame.mixer.Sound object?
5. What is the syntax to load the background music?
6. Describe the 3 argumenst in pygame.mixer.music.play(-1, 0.0). Homework: Read chapter 19 – Sound and Images
Visit edmodo.com to answer 8 questions from chapter 19
Write a python/pygame program, mySpritesAndSound_YI.py similar to spritesAndSound.py. However, in this program there are no cherries and no player but when you click on the black surface an image shows up. Have 10 different images so when you click with the mouse one of those random images is selected for display. The image should disappear when you release the mouse button. Find two different sounds, one for clicking and one for the release of the mouse button. Make sure you use at least one list.
Note: there are libraries of sound files online. Look for the right one for your application.
Homework: Keep on reading chapter 19 – Sound and Images
Simplified Space Invaders
https://www.mysteinbach.ca/game-zone/1755/alien-invaders/
You can simplify the invaders to have different shapes.
You can simplify the shape of the buildings.
The behavior of the game has to be the same:
a. The invaders move right to left as they move down.
b. The bullets destroy the invaders ( they disappear).
c. The bullets destroy the buildings ( they disappear).
d. Keep score and lives.
e. Final message: Game Over
Optional Challenge: Have different levels of difficulty
Encryption Assignment 1: A company has asked you to write a program, YI_myEncryption1.py to encrypt its data. Your program should read the entire string.
Start by converting every character to uppercase. Then find the ASCII code for the first character of the string and subtract 64 (for discussion’s sake, call this X). X is the key for the encryption. Go through the entire string: for each character use the key, X. You should return a string of integers (twice the length of the original string + 2, the ASCII value of the first character) but instead of letters, it is a list of encrypted ASCII codes.
NOTES:
1. Place the ASCII value of the first character in front of the string of numbers.
2. Keep the shift within the ASCII values of A through Z.
Example: Horse the code is: 728087906577
Homework: Write a program, YI_myDecryption1.py to decrypt a string of encrypted ASCII codes, first find the first two integers (if the EAC is 728077848487, the first two integers are 72. 72 is the first character of the string). This means that the first string’s encrypted ASCII code is 80. Change from 80 to its real ASCII value (figure out this algorithm on your own) and then subtract each two integers from the first real ASCII value.
Enforcing Privacy with Cryptography: The explosive growth of Internet communications and data storage on Internet-connected computers has greatly increased privacy concerns. The field of cryptography is concerned with coding data to make it difficult (and hopefully—with the most advanced schemes—impossible) for unauthorized users to read. In this exercise you’ll investigate a simple scheme for encrypting and decrypting data. A company that wants to send data over the Internet has asked you to write a program, myEncryption2_YI.py that will encrypt it so that it may be transmitted more securely. All the data is transmitted as four-digit integers. Your application should read a four-digit integer entered by the user and encrypt it as follows: Replace each digit with the result of adding 7 to the digit and getting the remainder after dividing the new value by 10. Then swap the first digit with the third, and swap the second digit with the fourth. Then print the encrypted integer.
Write a separate application, myDecryption2_YI.py that inputs an encrypted four-digit integer and decrypts it (by reversing the encryption scheme) to form the original number.
Classwork: Caesar Cipher
Create a new file in Idle with the following program: cipher.py
Cryptography
The science of writing secret codes is called cryptography.
German Lorenz cipher machine, used in World War II to encrypt very-high-level general staff messages
In cryptography, we call the message that we want to be secret the plaintext. The plaintext could look like this:
Hello there! The keys to the house are hidden under the flower pot.
How would encrypt it so it would become a secret message?
You can use Idle to answer some of the questions.
1. What is the ASCII table? What is the range of numbers that is used in the table?
2. What is the first number where the alphabet starts? Is it lower case or upper case?
3. How do you get the ASCII value of any letter or number (alphanumeric) in python?
4. How do you get the alphanumeric value of an integer in the range of the ASCII table?
5. Can you print all of the ASCII values?
6. Explain what a cipher is?
7. Run the cipher program and enter this sentence: “Doubts may not be pleasant, but certainty is absurd.” What is the encrypted sentence?
8. What does this ‘Hello’.isalpha() do in python shell?
9. What is the syntax to check if it is numeric?
10. What does this ‘HELLO’.isupper() do in python shell?
11. Explain what this code snippet does and what the purpose is in cipher.py:
if num > ord('Z'):
num -= 26
elif num < ord('a'):
num += 26
12. Explain the function getKey().
13. Explain the function getTranslatedMessage(mode, message, key).
Write a python/pygame program, FlashCards1_YI.py similar to previous program, mySpritesAndSound_YI.py. However, in this program, the user has to click on two matching cards. If the user guesses right, the sound should indicate so and so should the sound indicate when it is wrong.
Note: there are libraries of sound files online. Look for the right one for your application.
Homework: Keep on reading chapter 19 – Sound and Images
Friday is Pi Day – We will have a pi-day activity Starting tomorrow we are celebrating Pi day by writing a program to do one of the following: 1. Calculate the digits of Pi to highest possible precision 2. Illustrate how Pi works 3. Illustrate how Pi was discovered
The programs will be judge based on ingenuity and/or creativity. NOTE: You can use online resources to help you develop your program. You can not use already written programs.
Classwork: Write a pygame program, YI_MazeBouncing.py. Use the code you learned in animation.py but with a simple maze like the one below.
Homework:
Visit edmodo.com to answer these questions from Chapter 17.
January 4th, 2016
Welcome back! Class activity: Students will be presenting/discussing the following assignments: YI_PigLatinWord.py YI_PigLatinPhrase.py Homework: 1 Question on edmodo.com