Category Archives: Resources

Designing an algorithm

Classwork:

Designing an algorithm

Activity:
Work with a partner to design an algorithm: How to draw a picture given a set of instructions.
One student has a blank paper and the other student has a picture that will keep hidden.

Rules of the game:

  1. Don’t let your partner see the drawing.
  2. Your partner will draw the same shape on his/her paper by following your “set of instructions”.
  3. Write down the instructions as you give them.
  4. You can not use direct words that describes the image.
  5. Once finished, both look at the drawings and compare them.
  6. If the drawings don’t match, go back to your instructions and change them until you are satisfied.
  7. You and your partner reverse roles with a different picture though.
  8. Do the instructions need to be revised?

Homework:
Read the following articles linked bellow

Privacy violations – the dark side of social media
Screen Shot 2014-09-04 at 6.12.33 PM

Digital Explosion: Why Is It Happening, and What Is at Stake?
Screen Shot 2014-09-04 at 6.27.26 PM

Format: print format practice

Printing format review:

## Print format practice
## 1. add a new field: total = 500322.789856341 with 15 spaces and 4 decimals
## 2. change the field format for amount to be just 10 spaces long and 3 decimals
## 3. add a new field: name = "Tuesday" to be 8 spaces long

##       Question # 8 of 2nd review day

name = "Tuesday"
total = 500322.789856341
year = 23
amount = 567.435643231
print ("%4d%21.2f" % (year, amount))
print ("0000123456789012345678901234567890")
##
##>>> 
##  23               567.44
##0000123456789012345678901234567890
##>>> 

Format: Histogram

# Creating a histogram from a list of values.

int_values = []   # a list of values

# input 8 integers from user
print ("Enter 8 integers between the values of 1 and 10:")

for i in range( len(int_values) ):
   new_value = int( input( "Enter integer %d: " % ( i + 1 ) ) )
   int_values += [ new_value ]

# create histogram
print ("\nCreating a histogram from int_values:")
print ("%s %10s %10s" % ( "Element", "Value", "Histogram" ))

for i in range( len( int_values ) ):
   print ("%7d %10d  %s" % ( i, int_values[ i ], "*" * int_values[ i ] ))

Input/Output:

Enter 8 integers between the values of 1 and 10:
Enter integer 1: 1
Enter integer 2: 3
Enter integer 3: 4
Enter integer 4: 6
Enter integer 5: 5
Enter integer 6: 4
Enter integer 7: 3
Enter integer 8: 2

Creating a histogram from int_values:
Element      Value  Histogram
      0          1  *
      1          3  ***
      2          4  ****
      3          6  ******
      4          5  *****
      5          4  ****
      6          3  ***
      7          2  **
>>> 

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

Pi Day 2014

March 14th, 2014

PI DAY!!