Category Archives: Homework

Algorithm: Prepare for the Battleship

Continuing to prepare for the Battleship program

Classwork:

1. On a piece of paper decide in which edge you will place a 2 or 3-square ship.

2. Write a program, YI_4Edges.py to prompt the user for one of the edges locations on the 3 x 3 board and based on the user’s response write the code to find the ship and sink it.
– Use a list of three lists with 3 items each.
– Randomly select the edges where the program will place the ship.

Screen Shot 2015-02-02 at 7.32.57 AM Screen Shot 2015-02-02 at 8.06.20 AM

Algorithm: Preparing for the Battleship program Day 3

Preparing for the Battleship program

Classwork:

You can start working on the Battleship pygame program or you can choose to write a few programs to handle individual scenarios. Gradually, you will have the final version of the program.

Battleship development by parts:
Write a program, Corners4_YI.py to handle the following scenario:

– a hit is found on one of t the corners on the 3 x 3 board and based on the user’s response write the code to find the ship and sink it.

The idea at every scenario is to find a pattern so you can minimize the code and reuse it.

Use a list of three lists with 3 items each.
Randomly select the corner where the program will place the ship.

Screen Shot 2015-01-13 at 9.12.33 AM

Application’s Logistics:
Your program should only maintain as a minimum two boards:

1. The computer’s calls of the player’s ships locations.
2. The player’s guesses as either M(issed) or H(it).

Minimum requirements:
Display one board using pygame: either a or b
a. A board with the computer’s guesses with blue if it is a Miss or yellow and a portion of a ship if it is a Hit.
b. A board with the player’s guesses with blue if it is a Miss or yellow and a portion of a ship if it is a hit.

Some suggestions:

>>> listoflists=[['A','B','C'],['D','E','F'],['G','H','I']]
>>> for i in range(len(listoflists)):
        for j in range(len(listoflists[0])):
            print(listoflists[i][j],end=' ')
        print()

    
A B C 
D E F 
G H I 
>>> 

Algorithm: The Wheel of Fortune hangman n the game


Programming Project: The Wheel of Fortune
Write YI_WheelOfFortune.py using what you learned from hangman.py

Due date: November 25th, 2015

Screen Shot 2015-11-20 at 7.46.00 AM —> Screen Shot 2014-11-16 at 5.52.28 PMScreen Shot 2014-11-16 at 5.53.09 PM

For the last few days We have worked on understanding and assimilating Al Sweigart’s hangman.py program by taking the program apart and tracing it with different data to make sure we tested every line of code.

Now we can use the skills we learned to write a similar program to simulate the Wheel of Fortune. You can use the displayboard and getguess functions. You can collaborate with a partner but you should have your own program. No two programs should be alike!

The original game is multiplayer but you will implement it for only one player. Even though the behavior of the game should be reflected in your simulation, there are changes that have to be made to turn it into one player and still be a fun game. You might want to apply a penalty when the “lose a turn” comes up. This implementation of the Wheel of Fortune should handle only a word.

Somethings to keep in mind
Components that can help you through the process:

  1. A list of items on the wheel
  2. Random number for the spin simulation
  3. The “secret word”
  4. The “missed letters”
  5. The “correct letter”
  6. A “place holder” for the prizes

THE GAME

  1. Spin of the wheel: { gain or loss }
  2. If there is a gain, the player can guess a letter: { correct -> keeps the prize, incorrect -> loses the prize }
  3. The player can solve the puzzle before all the letters have been guessed.
  4. The player can buy a vowel if there is money in the “place holder”.
  5. The player gets to keep the prizes if the puzzle is solved.

NOTE: the program should allow the user to play the game after the puzzle was solved.

Algorithm: Hangman Game using what you learned


Hangman Game
More on lists:

What is the output from the next code snippet?

>>> wordIndex = 2
>>> print(wordIndex)
2
>>> print(['biology','chemistry','physics','algebra'][wordIndex])
physics
>>> 

Displaying the Board to the Player

def displayBoard(HANGMANPICS, missedLetters, correctLetters, secretWord):
    print(HANGMANPICS[len(missedLetters)])
    print()

    print('Missed letters:', end=' ')
    for letter in missedLetters:
        print(letter, end=' ')
    print()

    blanks = '_' * len(secretWord)

    for i in range(len(secretWord)): # replace blanks with correctly guessed letters
        if secretWord[i] in correctLetters:
            blanks = blanks[:i] + secretWord[i] + blanks[i+1:]

    for letter in blanks: # show the secret word with spaces in between each letter
        print(letter, end=' ')
    print()

Open a new window and create a python program, YI_displayBoard.py and copy the following code:

secretWord = 'apple'
blanks = '_' * len(secretWord)
correctLetters = 'l'
blanks

for i in range(len(secretWord)): # replace blanks with correctly guessed letters
    if secretWord[i] in correctLetters:
        blanks = blanks[:i] + secretWord[i] + blanks[i+1:]

for letter in blanks: # show the secret word with spaces in between each letter
    print(letter, end=' ')
print()

Change the correctLetters variable and play with the program until you figure out how it works.
There is a post in edmodo.com for you to submit the file and to explain how the program works.


Homework:
Write YI_WheelOfFortune.py using what you learned from Hangman.py

1. Have the variable secretWord changed to secretPhrase and have a value assigned to it.
2. Prompt the user for a letter and display it in the right positions if it is in the secretPhrase. Otherwise, send a message to the player “incorrect” and keep track of how many times the player guesses the wrong letters.
3. Terminate the game after 5 tries. Display “game over” if it fails. Otherwise, displays “You are a winner!!” and add message with the prize(s)

Dictionaries

Classwork:

Two ways to create a dictionary in python:
1.

grocery1 = {'lettuce': 1.99, 'tomato': 0.49, 'onion': 0.35, 'olives': 0.99}

2.

grocery2 = {}
grocery2['lettuce'] = 1.99
grocery2['tomato'] = 0.49
grocery2['onion'] = 0.35
grocery2['olives'] = 0.99
grocery2
{'olives': 0.99, 'tomato': 0.49, 'onion': 0.35, 'lettuce': 1.99}

Two ways to insert a new key-value pair to the dictionary:
1.

grocery1['lemon'] = 0.78
grocery1
{'olives': 0.99, 'lemon': 0.78, 'tomato': 0.49, 'onion': 0.35, 'lettuce': 1.99}

2.

grocery1.update({'potato':1.10})
grocery1
{'lemon': 0.78, 'onion': 0.35, 'potato': 1.1, 'olives': 0.99, 'tomato': 0.49, 'lettuce': 1.99}

Two ways to create a list of the keys of the dictionary:
1.

keys = grocery1.keys()
keys
dict_keys(['lemon', 'onion', 'potato', 'olives', 'tomato', 'lettuce'])
for key in keys:
print(grocery1[key], end = '-')
0.78-0.35-1.1-0.99-0.49-1.99-

print(keys)
dict_keys(['onion', 'tomato', 'olives', 'lettuce'])
for key in keys:
print(key, end = ' ')
onion tomato olives lettuce

2.

keys_list = list(grocery1.keys())
keys_list
['lemon', 'onion', 'potato', 'olives', 'tomato', 'lettuce']
 

Two ways to create a list of values:
1.

values_list = []
for key in keys:
    values_list += [grocery1[key]]

values_list
[0.78, 0.35, 1.1, 0.99, 0.49, 1.99]
 

2.

val_list = grocery1.values()
val_list
dict_values([0.78, 0.35, 1.1, 0.99, 0.49, 1.99])
 

More to know:

x = 'lemon' in grocery
x
True

y = 'carrot' in grocery
y
False

How to delete a key-value entry pair from a dictionary:

grocery1 = {'lettuce': 1.99, 'tomato': 0.49, 'onion': 0.35, 'olives': 0.99}
del grocery1['lettuce']
grocery1
{'onion': 0.35, 'tomato': 0.49, 'olives': 0.99}

In edmodo.com
Homework:
Answer the following questions in edmodo.com

1. Do lists allow duplicate elements? what about dictionaries?

adict = {'a':1,'b':2,'a':4}
adict
{'a': 4, 'b': 2}

2. What are two ways to insert key–> value pairs into a dictionary.
3. Can different ‘types’ of keys be used in the same dictionary?
4. What happens when you try entering a value for a key that is already in the dictionary?
5. Create a scenario in which you would use a dictionary (without using the grocery example from these slides), and explain why you’d use a dictionary rather than a list.

Gota, you were right. Here is another way to add a key-value pair to a dictionary from stackoverflow.com

x = {1:2}
print x
{1: 2}

x.update({3:4})
print x
{1: 2, 3: 4}

Dictionaries: One more look

Dictionaries in python

Interesting code found in some python Scrabble programs:
scrabble

word = input("Enter a four letter word ")
word = word.upper()
letterNum = {'A':1,'E':1,'D':2,'R':2,'B':3,'M':3,'V':4,'Y':4,'J':8,'X':8}

What does the following line print?

print(letterNum['A'])

How was it used in the scrabble program?
One possible answer:

value = 0
for i in word:
    value += letterNum[i]

print(value)

Another possible answer:

letterValue = [0,0,0,0]
for i in range(4):
    letterValue[i] = letterNum[word[i]]

print(letterValue)

Classwork:
Work in python’s shell and copy and paste your work on edmodo.com’s post: Dictionary – Clwk 1/8 – Basic Concepts

Create a dictionary: ‘hello’ is the key and ‘hola’ is the value

spanishDictionary = {'hello':'hola','goodbye':'adios','one':'uno','two':'dos'}

Access a value with the key

word = input("what word would like to translate to spanish? ")
palabra = spanishDictionary[word]

Add a new key and value:

spanishDictionary.update({'blue':'azul'})
print(len(spanishDictionary))

Delete a key and the value:

del(spanishDictionary['blue'])

Replace the value of a key:

spanishDictionary['goodbye'] = 'chau'

Remove all items:

spanishDictionary.clear()

You can have a different type of value:

numbers = {'one':1,'two':2,'three':3,'four':4,'five':5}


print( numbers['two'] * numbers['three'])

You can have a different type of key and a different type of value:

numbers = {90:0,91:1,92:2,93:3}

print(numbers[92] * numbers[93])

Homework:
Add ten more words to the dictionary. Write a sentence in English and then translate it to Spanish or the language you chose. Add this new code to the original post.

Dictionaries: Mad Libs

Classwork: having fun with lists.

Screen Shot 2015-11-02 at 2.13.55 PM

Screen Shot 2015-11-02 at 2.14.33 PM

DIY Mad libs: Write your own mad lib program, YI_MadLibs.py using lists. You might want to have a theme.
Recipe:
1. Create 9 lists for adjectives, adverbs, nouns or plural nouns, verbs, exclamations, numbers, colors, and names. You can prompt the user for name to fill your list of names but all the other lists should already contained the items.

  1. Generate 9 random digits one for each of the lists. The range will depend on the number of items each list has.
  2. Create a sentence with the choice of each list. Make sure you put them in the right order!
  3. Prompt the user whether he or she wants to play again.

NOTE:
Adjectives: describes something (green, squishy, cute)
Adverbs: describes an action (quickly, carefully, silently)
Nouns: person, place or thing (car, house, child)
Plural noun: people, places or things (cars, houses, children)
Verbs: an action (run, jump, swim)
Exclamations: wow!, oh!, yuck!

Something to keep in mind:
Find the words for your lists in such a way that fit “nicely” into your theme sentence.

You can play with this site to get an idea:
Screen Shot 2015-11-02 at 2.07.39 PM

Dictionaries: MySpanishDictionary_YI.py

Dictionaries
Screen Shot 2016-01-06 at 1.34.15 AM

dictionary methods

Assignment:
Write a python program, YI_MySpanishDictionary.py using functions and dictionaries.

    Note: You can use a different language. Name your program according to the language you are using.

  • Hardcode a dictionary’s english word (key) and its spanish translation (value) for several english words (entries in the dictionary)
  • Display a menu for the user to choose:
    1. Translate an english word
    2. Display all english words in the dictionary
    3. Add new english/spanish entries
    4. Delete english/spanish entries.

  • Include an introduction
  • Exit the program properly
  • Do not forget to keep your code well documented
  • Pasting your code on the post is a requirement
  • Attaching your file is also a requirement

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

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

pygame: space invaders

Collision detection and input

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

Simplified Space Invaders
space invaders

Cryptography: myEncryption1_YI.py

Classwork:
ASCII table

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.

Cryptography

Classwork:
ASCII table
Encryption Assignment 2:

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.

Cryptography

Classwork:
Screen Shot 2015-05-14 at 9.26.24 PM
Caesar Cipher
Create a new file in Idle with the following program: cipher.py

Cryptography

The science of writing secret codes is called cryptography.
220px-Lorenz-SZ42-2
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).

Homework
Explain Brute Force