pygame: installations

On a mac machine:

On a Windows machine:
Courtesy from Naomi

So first you would have to download pygame through http://python-gaming.com/pygame/ftp/pygame-1.9.2a0-cp35-none-win32.whl

After that, follow the steps on the “install pygame” section of this website: https://skellykiernan.wordpress.com/2015/01/04/python-pygame-install/. The only difference is that you will need to copy the pygame-1.9.2a-0-cp35-non-win32.whl file instead of the file that was in the first step. Moreover, you would be looking for python 3.5, not for python 3.4.

pygame: Olympic Rings

Graphics and Animations – Chapter 17

Homework:
Complete assignments

Classwork:
1. Write a python/pygame program, Olympic_Rings_YI.py. Draw the Olympic rings like the ones below.
Try to match up the colors and the relationship between the rings.

olympic_rings

Link for antialiased circles.
This link has more drawing options.

anti-alias

2. Write a pygame program, Cars_n_trucks_YI.py to draw a random number of different cars and/or trucks of different colors. Look at some examples bellow.
Draw composite basic shapes

Screen Shot 2014-02-26 at 5.49.41 AM Screen Shot 2014-02-26 at 5.49.46 AM Screen Shot 2014-02-26 at 5.49.54 AM Screen Shot 2014-02-26 at 5.50.01 AM

car3

truck4

Note 1: make them (at least 2 kinds of vehicles) colorful and filled in.
Note 2: create functions: drawCar and drawTruck. Both functions should take two parameters: the scaling factor (suggested factor should be less than 1) and translation constant so it can be placed in different locations. For translation only, the scaling factor should be 1 and for scaling only the translation constant should be zero.
Note 3: the cars and trucks should be placed on the surface in random locations.
Note 4: Keep on reading chapter 17

Geometry review:
Dialation:
Screen Shot 2016-02-22 at 8.14.05 AM

Translation:
Screen Shot 2016-02-22 at 8.16.36 AM

pygame: 1st Maze

Classwork:
Open pygameHelloWorld.py program and save it as Maze1_YI.py. Use what you learned in this program, rectangles, lines and text to draw a simple maze. Include the “Start” and “End” signs on the maze to indicate the beginning and end of the maze. Have a colorful but yet light background.

Open pygameHelloWorld.py program and save it as Maze2_YI.py. Use what you learned in this program, circles, lines, and text to draw a simple circular maze. Include the “Start” and “End” signs on the maze to indicate the beginning and end of the maze. Have a colorful but yet light background.

Warning!
Work on an easy maze like the one below
ClassicMaze

Resources:
For the second maze you will need to know how to draw arcs.

pygameDocumentation

Simple Example: Here is the code for a quarter of a green circle with radius 100

import math

pygame.draw.rect(windowSurface,RED,(50,50,100,100),5)
pygame.draw.arc(windowSurface, GREEN, (50,50,100,100),math.radians(0), math.radians(90),10)

quarterCircle

You can also draw the blue one:
twoQuarters

Can you guess the code for the blue arc in the bottom rectangle?
Explain what each parameter represents. Be concise and give different examples

pygame: Some advice to help you implement the cars and trucks assignment

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

pygame: The Bouncing Blocks Algorithm

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.

overlapping-rectangles

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).

overlapping-rectanglesVert

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)

pygame: TheGobbler.py

Next Chapter

Classwork: Modify CollisionDetection program so the bouncer gets bigger when it eats the green food, TheGobbler_YI.py.

Hint: use the attributes of the rectangle: width and length to increase the size of the gobbler.
bouncer[‘rect’].width and bouncer[‘rect’].height.

Collision Detection and Input

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.

Resources:

1st ed Collision Detection

pygame Documentation

pygame: pygame.Rect

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
  • Anti-aliasing

  • A pygame rectangle is an object: Rect((left, top), (width, height)).
    pygame.Rect(left, top, width, height)
  • Documentation

  • pygame.Rect objects have attributes, variables that are associated with an object
  • rectanglesattributes

  • pygame.Rect objects have behaviors, methods that are associated with an object
  • pygamerectangles

  • 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.

pygame: WallBouncing_YI.py

Classwork:
Continue working on the program, WallBouncing_YI.py.
Screen Shot 2014-03-07 at 11.09.04 AM
Home work: Keep on reading chapter 17.
Screen Shot 2014-03-07 at 9.30.28 AM

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.
Screen Shot 2014-03-07 at 9.29.25 AM

pygame: BouncingOffWall.py

Another good link for drawing shapes.

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)

Screen Shot 2014-03-07 at 11.09.04 AM
Home work: Keep on reading chapter 17.
Screen Shot 2014-03-07 at 9.30.28 AM
Think about your next program. It will be related to the animation.py but with a simple maze.
Screen Shot 2014-03-07 at 9.29.25 AM

pygame: BouncingInMaze_YI.py

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.
Screen Shot 2014-03-07 at 9.29.25 AM

Some of last previous years’ mazes:
Screen Shot 2015-03-16 at 8.39.27 AM

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?

pygame: MazeBouncing_YI.py

Screen Shot 2014-03-10 at 4.30.38 PM

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.
Screen Shot 2014-03-07 at 9.29.25 AM

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)?

pygame: SpritesAndSound_YI.py

Classwork:
More on spritesAndSound.py

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.

memoryFlashCards

Homework: Start reading chapter 14 – Caesar Cipher

Screen Shot 2014-05-13 at 8.12.31 AM

Sean Shypula and Luis Villegas

Next Chapter

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.

Screen Shot 2014-03-25 at 9.45.08 AM

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.

pygame: Run spritesAndSound.py

Classwork:
Run spritesAndSound.py

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

Chapter 19 – Sound and Images link
Screen Shot 2014-04-28 at 7.05.14 AM

pygame: mySpritesAndSound.py

Classwork:
Run spritesAndSound.py

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

Chapter 19 – Sound and Images link
Screen Shot 2014-04-28 at 7.05.14 AM

Algorithm: Simplified Space Invaders

April 27th, 2016

Collision detection and input

Simplified Space Invaders
space invaders

Simplified Space 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

Homework: Check edmodo.com

pygame: PixelArray

Quick announcements: PU students are coming after school today.

This Saturday at PU
splash

Classwork:
Use pixelArray from pygameHelloWorld.py to write the program drawpad_YI.py

drawingpad

# get a pixel array of the surface
pixArray = pygame.PixelArray(windowSurface)
pixArray[480][380] = BLACK

pygame: Drawpad_YI.py

Use pixelArray or other shapes from pygameHelloWorld.py and what you learned from previous assignments to write the program drawpad_YI.py

drawingpad

# get a pixel array of the surface
pixArray = pygame.PixelArray(windowSurface)
pixArray[480][380] = BLACK

Some helpful syntax:

pixArray = pygame.PixelArray(windowSurface)
pixArray[400][100] = BLACK
pixArray[pygame.mouse.get_pos()[0]][pygame.mouse.get_pos()[1]] = BLACK
del pixArray

pygame.mouse.get_pos()–> [x,y]
pygame.mouse.get_pos()[0] –> x
pygame.mouse.get_pos()[1] –> y