CS 1110 - Fall 2015 - Previous Lab Projects

Lab 1 - August 27 - Getting Started

Lab this week is optional in that we will not be taking roll. However, this is an opportunity to come to ensure that you have Python and PyCharm installed and working properly on your laptops. If you do not come to lab, we will assume you have taken care of this yourself and you are ready to go when we start coding in lecture next week. So, if you have any doubts, come on down to lab, meet some of the TAs, and make sure you’re laptop is setup and ready to go!

Windows

  1. Download the Python installer at https://www.python.org/ftp/python/3.4.3/python-3.4.3.msi and then double-click the download to start the installation.
  2. At the Customize Python 4.3.4 screen, change “Add python.exe to Path” to “Will be installed on local hard drive”.
  3. Download the PyCharm installer at https://www.jetbrains.com/pycharm-educational/ - Click “Get PyCharm”. Double-click the download to start the installation.
  4. At the Installation Options screen, make sure to check “Create associations” - “.py”.

Mac

  1. Download the Python installer at https://www.python.org/ftp/python/3.4.3/python-3.4.3-macosx10.6.pkg and then double-click the download to start the installation.
  2. Download the PyCharm installer at https://www.jetbrains.com/pycharm-educational/ - Click “Get PyCharm”. Double-click the download to mount the image. Drag the icon to the Applications folder.

Lab 2 - September 3 - Counting Rooms

Activity 1: Test your logins!

If you are in a lab in Olsson 001, try out your Olsson 001 login. If you have trouble, talk to your lab TA.

Activity 2: Pairing

For this and all subsequent labs, you will work in pairs.

We will use a model called “pair programming” in this class. There are a few things to know about successful pairing under this model:

  • 2 minds, 1 focus. If at any point the two of you are doing distinct things, such as each typing on your own computer or each looking at your own piece of paper, then you are not pairing properly.
  • Driver and Navigator. At any given point in time, one partner will be the “driver”, controlling the keyboard, pencil, or other tool currently being used. The other will be the “navigator,” observing and commenting on the driver’s actions
  • Equality and Communication. Driver and navigator are equal partners; the ideas of both are equally important, and both should talk, both should listen when the other speaks, and both should treat the other’s ideas with respect.
  • Switch Roles. Which partner is driving should change at least every 15-20 minutes, if not more often.

Pairing in this model has many advantages both from a productivity and learning standpoint. One of these is generally an increase the intensity of focus, which can get tiring. Feel free to take breaks every now and then, but try not to distract other pairs during your breaks.

For more hints on successful pairing, you might want to watch this 10-minute video on your own time.

Activity 3: Grid of doors

Picture of door space

For this lab we will be programming a robot that has been dropped into a grid of square rooms. Each wall of each room has been painted a different color: the North wall is Neon, the East wall is Eggplant, the South wall is Sandy, and the West wall is Wallnut. Walls between rooms have doors in them, but walls on the edge do not. All of the doors are closed initially.

The robot knows how to

  • Check N (or Check E, or S, or W) to see if there is a door on that wall of its current room;
  • Go N (or E or S or W) to move one room over; and
  • Do basic math and remember numbers

If you ask it to Go through a wall that does not have a door, it isn’t smart enough to know it can’t so it will walk into the wall and damage itself.

We won’t be super formal in this lab. If we can tell what you are asking the robot to do, that’s good enough for us.

Activity 3.1: Simple Square

Suppose the robot is dropped into a square grid of rooms and starts in the north-west corner of the grid. Come up with an algorithm that the robot can use to figure out how many rooms are in the grid.

Is there any size grid for which your algorithm does not work? How about on a 1-by-1, or a 1000-by-1000?

In a 3-by-3 grid, how many times will the robot have to move through a door to run your algorithm? How about a 4-by-4? An n-by-n?

Assume that we want to save on robot fuel. Can you make an algorithm that uses fewer moves for the same size grid?

Once you have an algorithm you think is general (works for all size squares) and efficient (uses few moves), type it up and save it in a text file. You’ll submit all your algorithms at the end. Include a simple statement about how many moves it takes, on an n-by-n grid the robot moves through 2n+5 doors or something like that.

Activity 3.2: Simple Rectangular

Suppose the robot is dropped into a rectangular (not necessarily square) grid of rooms and starts in the north-west corner of the grid. Come up with an algorithm that the robot can use to figure out how many rooms are in the grid.

Type it up and save it on the same text file as before, including a description of the number of moves needed for an n-by-m grid. If your 3.1 algorithm still works, you are welcome to submit it again for 3.2.

Activity 3.3: Rectangular

Suppose the robot is dropped into a rectangular (not necessarily square) grid of rooms and might start in any arbitrary room in the grid. Come up with an algorithm that the robot can use to figure out how many rooms are in the grid.

Type it up and save it in the same text file as before, including a description of the number of number of moves your robot will make for an n-by-m grid. Since this will probably depend on the starting location of the robot, just tell us the biggest number you could see (assuming the robot started in the worst possible room).

If one of your previous two algorithms still works, you are welcome to submit it again for 3.3.

Activity 3.4: Stranger Grids

See how general you can make your algorithm. Can you get it to work on diamond-shaped grids of rooms? Grids with more complicated outlines? Grids where some rooms are missing in the middle? Grids where some walls between two rooms that do exist don’t have doors? Arbitrary mazes of rooms?

Type it up and save it in the same text file as before. At the beginning of the submission, include a description of the kinds of grids you think it can handle.

We are not looking for any particular functionality in activity 3.4; if you can’t get any more than 3.3 done, submit 3.3 and tell us it’s as much as you could do in the time we gave you.

Once you have all 4 algorithms done, submit them all in this Google Form. Only one partner needs to submit!

Lab 3 - September 10 - Turtle Art Contest

Activity 1: Login and Record Attendance

We will be taking roll in lab each week! Please come to your assigned lab to be counted present!

Click “Lab Attendance” on the left-hand menu in Collab to register your attendance and keep up with your lab grade.
YOU MUST CLICK THE LARGE GREEN OR YELLOW BUTTON FOR YOUR ATTENDANCE TO COUNT!!

You must do this from a machine in Olsson 001 and not your laptop. If you have trouble, talk to your lab TA.

Activity 2: Pairing

For this and all subsequent labs, you will work in pairs.

We will use a model called “pair programming” in this class. There are a few things to know about successful pairing under this model:

  • 2 minds, 1 focus. If at any point the two of you are doing distinct things, such as each typing on your own computer or each looking at your own piece of paper, then you are not pairing properly.
  • Driver and Navigator. At any given point in time, one partner will be the “driver”, controlling the keyboard, pencil, or other tool currently being used. The other will be the “navigator,” observing and commenting on the driver’s actions
  • Equality and Communication. Driver and navigator are equal partners; the ideas of both are equally important, and both should talk, both should listen when the other speaks, and both should treat the other’s ideas with respect.
  • Switch Roles. Which partner is driving should change at least every 15-20 minutes, if not more often.

Pairing in this model has many advantages both from a productivity and learning standpoint. One of these is generally an increase the intensity of focus, which can get tiring. Feel free to take breaks every now and then, but try not to distract other pairs during your breaks.

For more hints on successful pairing, you might want to watch this 10-minute video on your own time.

Activity 3: Art Contest

Your goal with this lab is to make the neatest picture you can using the turtle and any example code we have provided. You can use any of the code posted on the lecture notes as a starting point, or you can use your own.

Make sure to look at the Turtle API. (Remember: the API is the “list of things that you can do with a class”)

Submission

Save a picture of your image by taking a screenshot and then cropping down to just your image using Paint on your machine. Ask your TA for assistance if needed.

Submit a .png file to the Turtle Art Gallery. Make sure to title your file like this:

930-mss2x-tbh3f.png

Use 930, 1100, 1230, 200, and 330 please so we can keep all the labs together and we know who you are!

The staff will pick our favorite images, with prizes awarded next lab!

Lab 4 - September 17 - Data Types

Turtle Winners!

Congrats to the following winners of the Turtle Art Contest!

Activity 1: Login and Record Attendance

We will be taking roll in lab each week! Please come to your assigned lab to be counted present!

Click “Lab Attendance” on the left-hand menu in Collab to register your attendance and keep up with your lab grade.
YOU MUST CLICK THE LARGE GREEN OR YELLOW BUTTON FOR YOUR ATTENDANCE TO COUNT!!

You must do this from a machine in Olsson 001 and not your laptop. If you have trouble, talk to your lab TA.

Activity 2: Recitation

The TAs will do a quick review lesson on data types before moving on to the in-lab activity.

Activity 3: Building a Magic 8 Ball

Your goal in this lab is to work with a partner write a program called magic_8_ball.py. The program will prompt the user to ask a question of the magic 8 ball. Your program should respond with a randomly-chosen answer from a list of answers that you create.

For example, a run of your program could look like this:

What question do you wish to ask the 8 ball?: Will I get a good grade in CS 1110?
You asked the 8 ball: Will I get a good grade in CS 1110?
The 8 ball says: “All signs point to yes!”

For this assignment, we are not auto-grading your results. So feel free to be creative with the prompts and responses! (Within reason, of course…)

We will, however, look at how you wrote the code. Specifically, how you solved the problem. How did you read in the question? How did you setup your list of responses? How easy would it be to add another response? Is it truly random?

Submission: Each partner should submit one .py file named magic_8_ball.py to the submission system. Please put both partners' names and id’s in two comments at the top of the file.

Lab 5 - September 24 - Decisions and Loops

Activity 1: Login and Record Attendance

We will be taking roll in lab each week! Please come to your assigned lab to be counted present!

Click “Lab Attendance” on the left-hand menu in Collab to register your attendance and keep up with your lab grade.
YOU MUST CLICK THE LARGE GREEN OR YELLOW BUTTON FOR YOUR ATTENDANCE TO COUNT!!

You must do this from a machine in Olsson 001 and not your laptop. If you have trouble, talk to your lab TA.

Activity 2: Recitation

The TAs will do a lesson on decision structures and loops before moving on to the in-lab activity.

Activity 3: Magic Square Verifier

Most people are familiar with Sudoku, a number puzzle that consists of nine squares with nine squares within each of those squares in which you write the digits 1 through 9 so that each large square, row, and column all have exactly one instance of each digit.

A smaller, simpler form of that is the Lo Shu Magic Square. A Lo Shu Magic Square has 9 boxes in a grid in which you also put each digit from 1 through 9 exactly once. The difference is that each row, column, and diagonal all sum to the same value, 15.

For example:

4 9 2
3 5 7
8 1 6

For this lab, write a program called lo_shu.py that will take in 9 numbers in a particular order that represents a Lo Shu Magic Square. You should respond to the user whether the square is or is not a valid Lo Shu Magic Square.

Assume you had a square that looked like this:

1 2 3
4 5 6
7 8 9

Your program’s output should look like this:

Numbers: 1 2 3 4 5 6 7 8 9
You entered:
1 2 3
4 5 6
7 8 9
[1, 2, 3] fails the test!
[7, 8, 9] fails the test!
Column 0 fails the test!
Column 2 fails the test!
This is not a Lo Shu Magic Square!

Another example might be:

4 9 2
3 5 7
8 1 6

Your program’s output should look like this:

Numbers: 4 9 2 3 5 7 8 1 6
You entered:
4 9 2
3 5 7
8 1 6
This is a valid Lo Shu Magic Square!

While we know you could simply hardcode every possible row, column, and diagonal, you should intentionally make yourself do this with loops! Write a loop that will do ALL of the rows and another that will do ALL of the columns! The point of this lab is to help you with loops and if statements!

Submission: Each partner should submit one .py file named lo_shu.py to the lab submission system. Please put both partners' names and id’s in two comments at the top of the file.

Example Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# Mark Sherriff (mss2x)

sentinel = int(input("Starting number: "))

number = 0

number_list = []
higher = 0
lower = 0
same = 0

while number != -1:
    number = int(input("Give me a number (end with -1): "))
    if number == -1:
        continue
    if number == sentinel:
        same += 1
    elif number < sentinel:
        lower +=1
    else:
        higher +=1
    number_list.append(number)

print("You entered:", number_list)
print("Higher:", higher, "Lower:", lower, "Same:", same)

Answer code for the in-class assignment:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# Mark Sherriff (mss2x)

numbers = (input("Numbers: ")).split()

square = [[0,0,0],[0,0,0],[0,0,0]]

count = 0

is_square = True

for i in range(3):
    for j in range(3):
        square[i][j] = int(numbers[count])
        count += 1
# print(square)
print("You entered:")
for row in square:
    print(str(row[0]) + '\t' + str(row[1]) + '\t' + str(row[2]))

# check rows
for row in square:
    if sum(row) != 15:
        is_square = False
        print(str(row) + " fails the test!")

# check cols
for i in range(3):
    if square[0][i] + square[1][i] + square[2][i] != 15:
        is_square = False
        print("Column " + str(i) + " fails the test!")

# check diagonals
if square[0][0] + square[1][1] + square[2][2] != 15:
    is_square = False
    print("Left->Right diagonal fails the test!")

if square[0][2] + square[1][1] + square[2][0] != 15:
    is_square = False
    print("Right->Left diagonal fails the test!")

if not is_square:
    print("This is not a Lo Shu Magic Square!")
else:
    print("This is a valid Lo Shu Magic Square!")

Lab 6 - October 1 - This Little Piggy Played Dice

Activity 1: Login and Record Attendance

We will be taking roll in lab each week! Please come to your assigned lab to be counted present!

Click “Lab Attendance” on the left-hand menu in Collab to register your attendance and keep up with your lab grade.
YOU MUST CLICK THE LARGE GREEN OR YELLOW BUTTON FOR YOUR ATTENDANCE TO COUNT!!

Activity 2: Pairing

For this and all subsequent labs, you will work in pairs.

Activity 3: Starting Out

The TAs will walk you through how to play the game of Pig, discussing the basic game algorithm and how you might put together your own version.

If you are not familiar with the game, read up on the rules here: Pig - Dice Game Rules (We are playing the main game type, not one of the variants listed.)

Activity 4: Pseudocode

Here’s an outline of what the program will look like. This isn’t necessarily the only way to do it, but it’s one way to pull it off.

Read through this algorithm and see if you have any questions.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
Program Setup (get all the variables you'll need, such as total score for the player and computer, temporary scores for both, etc.)

while neither has reached the needed score to win:
  
  while it is player 1's turn:
      Print the current score of both players
      roll the die (i.e. get a random number between 1 and 6)
      if the die comes up with a 1:
          the player loses any currently allocated points
          reset the temporary score
          switch to the computer's turn
      else:
          add the die roll to a temporary set of accumulated points
          ask if they want to roll again 
          if no:
              add the temporary set of points to the player's bank
              reset the temporary score
              switch to the computer's turn
      if player's total > score needed to win:
          print the winning message and end the game
      
      
  while it is the computer's turn:  
      # the computer's code goes here and looks similar to above, 
      # except you determine when the computer will end its turn as 
      # opposed to prompting the user
      # try different reasons to stop and see what works!  
      # for example, have the computer always keep rolling until it
      # banks 10 points before ending it's turn

Activity 5: Example Run

Here’s an example game where the score to reach is 50 (we use 50 here instead of 100 because playing to 100 takes a bit too much space… the game is the same). Your outputs do not have to exactly match ours, but this gives an idea of what the game could look like.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
Welcome to Pig!

Player: 0 Computer: 0
It's your turn!
You rolled a 2
You currently have 2 banked.
Do you wish to roll again (y/n)?: y

Player: 0 Computer: 0
It's your turn!
You rolled a 4
You currently have 6 banked.
Do you wish to roll again (y/n)?: y

Player: 0 Computer: 0
It's your turn!
You rolled a 5
You currently have 11 banked.
Do you wish to roll again (y/n)?: n
Your total socre is now: 11

Player: 11 Computer: 0
It's the computer's turn!
The computer rolled a 4
The computer has 4 banked.

Player: 11 Computer: 0
It's the computer's turn!
The computer rolled a 6
The computer has 10 banked.
The computer has chosen to end its turn.
The computer's score is now: 10

Player: 11 Computer: 10
It's your turn!
You rolled a 3
You currently have 3 banked.
Do you wish to roll again (y/n)?: y

Player: 11 Computer: 10
It's your turn!
You rolled a 1
PIG! Too bad! Your total is currently: 11

Player: 11 Computer: 10
It's the computer's turn!
The computer rolled a 3
The computer has 3 banked.

Player: 11 Computer: 10
It's the computer's turn!
The computer rolled a 4
The computer has 7 banked.
The computer has chosen to end its turn.
The computer's score is now: 17

Player: 11 Computer: 17
It's your turn!
You rolled a 5
You currently have 5 banked.
Do you wish to roll again (y/n)?: y

Player: 11 Computer: 17
It's your turn!
You rolled a 1
PIG! Too bad! Your total is currently: 11

Player: 11 Computer: 17
It's the computer's turn!
The computer rolled a 3
The computer has 3 banked.

Player: 11 Computer: 17
It's the computer's turn!
The computer rolled a 2
The computer has 5 banked.

Player: 11 Computer: 17
It's the computer's turn!
The computer rolled a 6
The computer has 11 banked.
The computer has chosen to end its turn.
The computer's score is now: 28

Player: 11 Computer: 28
It's your turn!
You rolled a 5
You currently have 5 banked.
Do you wish to roll again (y/n)?: y

Player: 11 Computer: 28
It's your turn!
You rolled a 5
You currently have 10 banked.
Do you wish to roll again (y/n)?: n
Your total socre is now: 21

Player: 21 Computer: 28
It's the computer's turn!
The computer rolled a 4
The computer has 4 banked.

Player: 21 Computer: 28
It's the computer's turn!
The computer rolled a 3
The computer has 7 banked.
The computer has chosen to end its turn.
The computer's score is now: 35

Player: 21 Computer: 35
It's your turn!
You rolled a 2
You currently have 2 banked.
Do you wish to roll again (y/n)?: y

Player: 21 Computer: 35
It's your turn!
You rolled a 4
You currently have 6 banked.
Do you wish to roll again (y/n)?: y

Player: 21 Computer: 35
It's your turn!
You rolled a 1
PIG! Too bad! Your total is currently: 21

Player: 21 Computer: 35
It's the computer's turn!
The computer rolled a 4
The computer has 4 banked.

Player: 21 Computer: 35
It's the computer's turn!
The computer rolled a 5
The computer has 9 banked.
The computer has chosen to end its turn.
The computer's score is now: 44

Player: 21 Computer: 44
It's your turn!
You rolled a 1
PIG! Too bad! Your total is currently: 21

Player: 21 Computer: 44
It's the computer's turn!
The computer rolled a 3
The computer has 3 banked.

Player: 21 Computer: 44
It's the computer's turn!
The computer rolled a 2
The computer has 5 banked.

Player: 21 Computer: 44
It's the computer's turn!
The computer rolled a 2
The computer has 7 banked.
The computer has chosen to end its turn.
The computer's score is now: 51
The computer wins! 51 to 21

Activity 6: Get Coding!

You have the pseudocode, you have an example, now get to it!

Submission

Each partner should submit one .py file named pig.py to the lab submission system. Please put both partners' names and id’s in two comments at the top of the file.

Even if you don’t finish, submit what you have.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# Mark Sherriff (mss2x)

import random

print("Welcome to Pig!")

done = False
player_temp_total = 0
player_total = 0
comp_temp_total = 0
comp_total = 0
turn = "player"
winning_score = 50

while not done:
    while turn == "player" and not done:
        print()
        print("Player:", player_total, "Computer:", comp_total)
        print("It's your turn!")
        roll = random.randint(1,6)
        print("You rolled a", roll)
        if roll == 1:
            turn = "computer"
            player_temp_total = 0
            print("PIG! Too bad! Your total is currently:", player_total)
        else:
            player_temp_total += roll
            print("You currently have " + str(player_temp_total) + " banked.")
            choice = input("Do you wish to roll again (y/n)?: ")
            if choice == 'n':
                player_total += player_temp_total
                player_temp_total = 0
                print("Your total socre is now:", player_total)
                turn = "computer"
        if player_total > winning_score:
            print("You win! " + str(player_total) + " to " + str(comp_total))
            done = True

    while turn == "computer" and not done:
        print()
        print("Player:", player_total, "Computer:", comp_total)
        print("It's the computer's turn!")
        roll = random.randint(1,6)
        print("The computer rolled a", roll)
        if roll == 1:
            turn = "player"
            comp_temp_total = 0
            print("PIG! Too bad! The computer's total is currently:", comp_total)
        else:
            comp_temp_total += roll
            print("The computer has " + str(comp_temp_total) + " banked.")
            if comp_temp_total > 6 or comp_total + comp_temp_total > winning_score:
                print("The computer has chosen to end its turn.")
                comp_total += comp_temp_total
                comp_temp_total = 0
                print("The computer's score is now:", comp_total)
                turn = "player"
        if comp_total > winning_score:
            print("The computer wins! " + str(comp_total) + " to " + str(player_total))
            done = True

Lab 7 - October 8 - Playing Card Encryption

Activity 1: Login and Record Attendance

We will be taking roll in lab each week! Please come to your assigned lab to be counted present!

Click “Lab Attendance” on the left-hand menu in Collab to register your attendance and keep up with your lab grade.
YOU MUST CLICK THE LARGE GREEN OR YELLOW BUTTON FOR YOUR ATTENDANCE TO COUNT!!

Activity 2: Pairing

Find someone to work with!

Activity 3: Starting Out

The TAs will give an overview of the activity, in which you learn a bit more about encryption and (hopefully) see how difficult it might be!

Activity 4: Get your cards!

You need to come up with your own encryption scheme! Take the deck of cards and figure out an algorithm for encrypting a message! Specifically:

Jefferson’s Monticello

You’ll record your algorithm here: Google Form for Lab Submission Keep the form open for the next steps as well! (Writing your answers in a text document and copy it over wouldn’t be a bad idea.)

Your algorithm cannot be a 1-to-1 correspondence from card to letter. You must be creative here! Do something a bit devious (but still decryptable)! (Also, 1-to-1 won’t work terribly well because there are a lot of ‘e’s in the message.)

Encrypt the message and stack the deck so the message is read from top to bottom. Place the Jokers at the end of your message to separate it from the rest of the deck.

Activity 5: Decrypt a message

You’ll now trade your deck with another group. Your task is to try to reverse engineer the other group’s encryption algorithm. You know the message! See if you can figure it out!

Record your best guess on the same form as before: Google Form for Lab Submission

Activity 6: Debrief

Get with the group you traded with and compare notes. Did you get it right? How hard was it? What information did you need? Could you have done it with more time? Write down your thoughts again on the same form, and then submit: Google Form for Lab Submission

Lab 8 - October 15 - WahooSpoon

Activity 1: Login and Record Attendance

We will be taking roll in lab each week! Please come to your assigned lab to be counted present!

Click “Lab Attendance” on the left-hand menu in Collab to register your attendance and keep up with your lab grade.
YOU MUST CLICK THE LARGE GREEN OR YELLOW BUTTON FOR YOUR ATTENDANCE TO COUNT!!

Activity 2: Pairing

Find someone to work with!

Activity 3: Starting Out

The TAs will review how functions work and why we want to use them. They will also go through a few basic examples of writing methods.

Activity 4: Setup

If you’ve never used UrbanSpoon, it’s an app that helps you choose a restaurant to go to based on some choices and a whole lot of randomness. We’re going to build a simplified version of this app using functions.

Create a file called wahoospoon.py. Start off by setting up some variables to store restaurant names, styles, and costs. Our suggestion is to use three lists in which the indexes of each restaurant lines up with its style and cost.

1
2
3
4
5
import random

restaurants = ["Sticks", "Yuan Ho", "Melting Pot", "East Garden"]
styles = ["Casual", "Chinese", "Fancy", "Chinese"]
costs = ["$", "$", "$$$", "$$"]

Of course, add your own entries here!

Activity 5: Prompt The User and Get Lunch!

Write code to choose between three options: get a random restaurant, get a random restaurant based on style, and get a random restaurant based on cost.

It should look something like this:

Welcome to WahooSpoon!
1. Get a random restaurant
2. Get a random restaurant based on style
3. Get a random restaurant based on cost
Choice?:

If the user chooses 1, you should call a function called get_random_restaurant() to get a random restaurant. The function should return three strings: the name of the restaurant, the style, and the cost.

If the user chooses 2, you should print the list of available styles, removing any duplicates from this printed list. Prompt the user for which style the user wants. Then call a function called get_restaurant_style(chosen_style) to get a random restaurant. The function should only take the style the user types as a parameter. The function should return three strings: the name of the restaurant, the style, and the cost.

If the user chooses 3, you should print the list of available costs, removing any duplicates from this printed list. Prompt the user for which cost the user wants. Then call a function called get_restaurant_cost(chosen_cost) to get a random restaurant. The function should only take the cost the user types as a parameter. The function should return three strings: the name of the restaurant, the style, and the cost.

An example run could look like this:

Welcome to WahooSpoon!
1. Get a random restaurant
2. Get a random restaurant based on style
3. Get a random restaurant based on cost
Choice?: 2
{‘Fancy’, ‘Chinese’, ‘Casual’}
What style would you like?: Chinese
We’re going to East Garden today! (Style: Chinese / Cost: $$ )

Submission: Each partner should submit one .py file named wahoospoon.py to the lab submission system. Please put both partners' names and id’s in two comments at the top of the file.

You must submit on time! Even if you don’t finish, submit what you have.

Example Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# Mark Sherriff (mss2x)
import random

restaurants = ["Sticks", "Yuan Ho", "Melting Pot", "East Garden"]
styles = ["Casual", "Chinese", "Fancy", "Chinese"]
costs = ["$", "$", "$$$", "$$"]

def get_random_restaurant():
    i = random.randint(0,len(restaurants)-1)
    return restaurants[i], styles[i], costs[i]

def get_restaurant_style(chosen_style):
    random_style = ""
    while random_style != chosen_style:
        i = random.randint(0,len(restaurants)-1)
        random_style = styles[i]

    return restaurants[i], styles[i], costs[i]

def get_restaurant_cost(chosen_cost):
    random_cost = ""
    while random_cost != chosen_cost:
        i = random.randint(0,len(restaurants)-1)
        random_cost = costs[i]

    return restaurants[i], styles[i], costs[i]


print("Welcome to WahooSpoon!")
print("1. Get a random restaurant")
print("2. Get a random restaurant based on style")
print("3. Get a random restaurant based on cost")
choice = int(input("Choice?: "))
if choice == 1:
    r, s, c = get_random_restaurant()
elif choice == 2:
    print(set(styles))
    style = input("What style would you like?: ")
    r, s, c = get_restaurant_style(style)
else:
    print(set(costs))
    cost = input("What cost would you like?: ")
    r, s, c = get_restaurant_cost(cost)

print("We're going to", r, "today! (Style:", s, "/ Cost:", c, ")")

Lab 9 - October 22 - Wendy’s

Activity 1: Login and Record Attendance

We will be taking roll in lab each week! Please come to your assigned lab to be counted present!

Click “Lab Attendance” on the left-hand menu in Collab to register your attendance and keep up with your lab grade.
YOU MUST CLICK THE LARGE GREEN OR YELLOW BUTTON FOR YOUR ATTENDANCE TO COUNT!!

Activity 2: Pairing

Pairing matters a bit more this week! Whoever you partner with today should be your partner for the Email Hunt project. You will be working with this person for the next few weeks, both on that assignment and on all labs (since you may have time in lab to work on the project). Once you have picked who you will be working with, register your partnership here.

If you are in a lab with an odd number of people, the TAs will create a group of 3. Also, if you don’t have a partner today, the TAs will assign you a partner if needed.

Activity 3: Starting Out

Today the TAs are going to review reading files. They’ll also introduce how to import the webbrowser library so you can open your computer’s default web browser to a particular URL.

Activity 4: Finding Your Location

Our goal for this lab is to write a program that will find the closest Wendy’s location to a given set of GPS coordinates (like you were using a GPS unit in your car). Then we want to open Google Maps to show where that Wendy’s is.

Create a new python file called wendys.py. Also download wendys.csv and put it into your project directory.

You are going to need some locations to test with. So go put some addresses you know in the tool here: http://www.gps-coordinates.net/

To start you out, the GPS coordinates for Rice Hall are: (38.0317274,-78.5110432).

Write down your test coordinates. You don’t need EVERY decimal place of precision…

Activity 5: Reading the File

Using the example code that we have done in class the past few days, write code that will loop through the wendys.csv file and compare the coordinates the user entered to the coordinates from the .csv file. Note that the 0 position in the .csv is the latitude and the 1 position is the longitude. First, prompt the user for their current latitude and longitude.

Since we want to find the closest Wendy’s, we need a way to figure out the distance between two sets of GPS coordinates. Copy and paste the following method in your wendys.py file.

GPS Distance Calculation
1
2
3
4
5
6
7
8
9
10
import math

def distance_between(lat_1, lon_1, lat_2, lon_2):
    theta = lon_1 - lon_2
    dist = math.sin(lat_1 * math.pi / 180.0) * math.sin(lat_2 * math.pi / 180.0) + math.cos(lat_1 * math.pi / 180.0) * math.cos(lat_2 * math.pi / 180.0) * math.cos(theta * math.pi / 180.0)
    dist = math.acos(dist)
    dist = dist * 180.0 / math.pi
    dist = dist * 60 * 1.1515

    return dist

You can execute this code by calling:

1
distance = distance_between(user_lat, user_lon, wendys_lat, wendys_lon);

Here, the user_lat and user_lon are what the user typed in and wendys_lat and wendys_lon are the 0 and 1 columns from the .csv (remember you can get these after you split the line… look at the examples from class!).

The result distance here is the distance in miles.

Loop through the entire file, keeping up with which Wendy’s gave you the shortest distance from the user’s coordinates to that Wendy’s coordinates. Save that information in some variables that you setup!

Activity 6: Google Maps

Now let’s put it on a map!

We can take the address (which is the combination of columns 4, 5, and 6 from the .csv) and create a web address object (URI) that Java can use to open your computer’s default browser.

1
2
# You'll need this at the top of your file
import webbrowser

Once you have imported the webbrowser library, you’ll need to create the proper URL for Google Maps.

The URL should look like:

https://www.google.com/maps?q= + the address (created by concatenating columns 4, 5, and 6 from the .csv)

You’ll also need to replace all the spaces in the address with + signs, since spaces aren’t allowed in URLs.

1
2
url = url.replace(' ', '+')
webbrowser.open(url)

Give it a shot and see what Wendy’s you can find!

Submission: Each partner should submit one .py file named wendys.py to the lab submission system. Please put both partners' names and id’s in two comments at the top of the file.

You must submit on time! Even if you don’t finish, submit what you have.

Example Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# Mark Sherriff (mss2x)

import math
import webbrowser

google_maps_url = "https://www.google.com/maps/@35.372742,-81.954957,15z?hl=en"

def distance_between(lat_1, lon_1, lat_2, lon_2):
    theta = lon_1 - lon_2
    dist = math.sin(lat_1 * math.pi / 180.0) * math.sin(lat_2 * math.pi / 180.0) + math.cos(lat_1 * math.pi / 180.0) * math.cos(lat_2 * math.pi / 180.0) * math.cos(theta * math.pi / 180.0)
    dist = math.acos(dist)
    dist = dist * 180.0 / math.pi
    dist = dist * 60 * 1.1515

    return dist

#lat = float(input("Current latitude: "))
#lon = float(input("Current longitude: "))

lat = 38.0322727
lon = -78.50997339999999
datafile = open("wendys.csv", "r")

closest_dist = 200
closest_wendys = ""

for line in datafile:
    entry = line.split(";")
    dist_to_wendys = distance_between(lat, lon, float(entry[0]), float(entry[1]))
    if dist_to_wendys < closest_dist:
        google_maps_url = "https://www.google.com/maps?q=" + str(entry[4]) + "+" + str(entry[5]) + "+" + str(entry[6])
        closest_dist = dist_to_wendys
        closest_wendys = entry[2]

datafile.close()

print("The closest Wendy's (", closest_wendys, ") is", closest_dist, "miles away.")
google_maps_url = google_maps_url.replace(' ', '+')
webbrowser.open(google_maps_url)

Lab 10 - October 29 - Harvesting Emails

Activity 1: Login and Record Attendance

We will be taking roll in lab each week! Please come to your assigned lab to be counted present!

Click “Lab Attendance” on the left-hand menu in Collab to register your attendance and keep up with your lab grade.
YOU MUST CLICK THE LARGE GREEN OR YELLOW BUTTON FOR YOUR ATTENDANCE TO COUNT!!

Activity 2: Pairing

You should be working with your Email Hunt project partner this week.

Activity 3: Starting Out

The TA’s will review what a regular expression is and how to test your expressions with a website like http://www.regexr.com/ or https://regex101.com/.

Activity 4: Selecting our Target… er… Test Subject

We’re going to practice our email hunting on our good friends in the Systems Engineering department!

http://www.sys.virginia.edu/people/faculty.html

Create a new python file called practice_email_finder.py. Write a program that will print as many of the valid email addresses you can find on the SIE faculty page.

While we’ve discussed in class how we can isolate emails, there’s a few issues we have to work through with this particular set of raw data:

  • More than one email per line: The SIE website is basically one HUGE single line of text with no line breaks. So you can’t just loop over every line - you have to look for multiple emails within the same line.
  • Duplication: You’re going to find multiple instances of nearly every email address.
  • Email Formats: We’ve discussed basic emails - those of the form a@b.com. But what if there are multiple periods? What if it doesn’t end in .edu? What if it isn’t a computing ID?

If you do the basics of what we did in class, you can pretty quickly find these email addresses:

['rrbailey@virginia.edu', 'siegradadministration@virginia.edu']

But there’s a lot more than that! See how many email addresses you can find!

You can use any combination of string manipulation and regular expression matching that you want.

One thing you might want to look at is the findAll() function that’s a part of the re library - findAll()

Submission: Each partner should submit one .py file named practice_email_finder.py to the lab submission system. Please put both partners' names and id’s in two comments at the top of the file.

You must submit on time! Even if you don’t finish, submit what you have.

Example Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# Mark Sherriff (mss2x)

import urllib.request
import re

website = urllib.request.urlopen("http://www.sys.virginia.edu/people/faculty.html")

found_emails = []

for line in website:
    decoded = line.decode('UTF-8').strip()
    regex = re.compile(r"[a-z]+@[a-z]+\.[a-z]+")
    results = regex.findall(decoded)

    if len(results) != 0:
        for email in results:
            if email not in found_emails:
                found_emails.append(email)
    # if results != None:
    #     found_emails.append(results.group())

print(found_emails)

Lab 11 - November 5 - Reading Web Logs

Activity 1: Login and Record Attendance

We will be taking roll in lab each week! Please come to your assigned lab to be counted present!

Click “Lab Attendance” on the left-hand menu in Collab to register your attendance and keep up with your lab grade.
YOU MUST CLICK THE LARGE GREEN OR YELLOW BUTTON FOR YOUR ATTENDANCE TO COUNT!!

Activity 2: Pairing

You should be working with your Email Hunt project partner this week.

Activity 3: Starting Out

The TA’s will quickly review regular expressions again. Remember - you can test your expressions with a website like http://www.regexr.com/ or https://regex101.com/.

Activity 4: Combing Through Data

For lab today, we’re going to look through a relatively large data set - the log file from the server running our course website.

The server’s name is stardock.cs.virginia.edu. This machine is hosting the websites for multiple classes, the office hours queue for 1110, 1113, and 2110, and all of Sherriff’s own personal projects. Can you figure out what takes up the most traffic? Where are people accessing the server from - on grounds or at home?

We’re going to look a one 24-hour time period - noon on Sunday, Nov 1, 2015 through noon on Monday, Nov 2, 2015. Please download this file and put in into your PyCharm project directory. The file is really too large to download each time.

access.log - 19.2 MB

Open the file in a text editor if you want to see what the data looks like. Here is an example:

172.26.30.213 - - [01/Nov/2015:12:00:14 -0500] “GET /oh/queue_count.php HTTP/1.1” 302 1886 “https://stardock.cs.virginia.edu/oh/” “Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.80 Safari/537.36”

The important bits here are:

  • 172.26.30.213 - This is the IP address where the request is coming from.
  • [01/Nov/2015:12:00:14 -0500] - The date and time of the request.
  • GET /oh/queue_count.php - The HTTP command being executed. This says “go find me this page and send it to me.”
  • https://stardock.cs.virginia.edu/oh/ - This is the referring URL. It shows what page someone was on when the command executed.
  • The rest of the line - This provides OS and browser information.

Activity 5: Answering Questions

Create a new python file called log_hunt.py where you will write your program.

There are a number of interesting questions we could answer by looking at this data. When was the most traffic? Was something going on then (office hours, an assignment due, etc.)? Where did most of the traffic come from?

We’ll limit ourselves to two specific questions:

  • What referrer was generating the most traffic?
  • What wireless network were more people on a the time - wahoo or cavalier?

For the first question, you should create a regular expression that can find all of the URLs on a given line. Feel free to do some Google searching to help you with this! Then using whatever method you want (dictionary, list, etc.) figure out which URL was generating the most traffic.

For the second question, you should create a regular expression that can find all of the IP addresses on an given line. Be careful - the Google Chrome browser version looks suspiciously like an IP address, so you’ll have to account for that. By checking the network info page at ITS, we can see which IP ranges are assigned to the various networks. To make things slightly simpler, we’ll say that any IP address that starts with 172.25. is on cavalier and any that starts with 172.27. is on wahoo. Report back how many requests come from each domain set.

Submission: Each partner should submit one .py file named log_hunt.py to the lab submission system. Please put both partners' names and id’s in two comments at the top of the file.

You must submit on time! Even if you don’t finish, submit what you have.

Example Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# Mark Sherriff (mss2x)

import re

log_file = open("access.log", "r")

ip_addresses = {}
urls = {}

wahoo_address = 0
cavalier_address = 0

regex = re.compile(r"[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}")
regex_url = re.compile(r"https:\/\/(\w|\.|\/)*")

for line in log_file:
    results = regex.findall(line)
    url_results = regex_url.search(line)
    for address in results:
        if address.startswith("172.25."):
            cavalier_address += 1
        if address.startswith("172.27."):
            wahoo_address += 1

        if address in ip_addresses:
            ip_addresses[address] += 1
        else:
            ip_addresses[address] = 1
    if url_results != None:
        url = url_results.group()
        if url in urls:
            urls[url] += 1
        else:
            urls[url] = 1

print(ip_addresses)
print(urls)
print(wahoo_address)
print(cavalier_address)

Lab 12 - November 12 - gamebox Intro

Activity 1: Login and Record Attendance

We will be taking roll in lab each week! Please come to your assigned lab to be counted present!

Click “Lab Attendance” on the left-hand menu in Collab to register your attendance and keep up with your lab grade.
YOU MUST CLICK THE LARGE GREEN OR YELLOW BUTTON FOR YOUR ATTENDANCE TO COUNT!!

Activity 2: Pairing

You are about to start working on a new project! You can work with the same partner or find a new one! Once you have found a partner, ONE partner should fill out this form: Game Project Partner Registration

Activity 3: Starting Out

This week we are going to begin working with gamebox - a library that will aid you in creating your own video game. First you’ll need to download gamebox.py and put it in your PyCharm project directory. You will be able to find gamebox and all of our example code at https://cs1110.cs.virginia.edu/code/gamebox. We will be adding more example code as we move through POTD 15 and the project.

You should also download and look over the gamebox API and introduction - gamebox.pdf

Activity 4: Simple Example

Start by creating a new game. Call it first_game.py. Then download gamebox.py and put it in the same PyCharm project.

Every PyGame / gamebox game looks basically the same. Start with the template code below:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# blank game template

import pygame
import gamebox
camera = gamebox.Camera(800,600)

def tick(keys):
    # to check if a key is pressed do, e.g., if pygame.K_LEFT in keys
    # to check the mouse, use camera.mouse (for position) or camera.mouseclick (for buttons)

    # typically here you update the position of the characters
    # then you call camera.draw(box) for each GameBox you made

    # usually camera.display() should be the last line of the tick method
    camera.display()

ticks_per_second = 30

# keep this line the last one in your program
gamebox.timer_loop(ticks_per_second, tick)

Your code will mostly go inside the tick function. This function is called 30 times per second (as you can see from the code). You should typically leave it at 30. You can add other functions and variables outside of tick, but the main part of your game will go here.

Run this game. You should see a blank box.

Activity 5: Adding to the Game

Let’s add a small, basic character to our game and give us control over it. Change your code so it looks like this now:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# our first game
import pygame
import gamebox

camera = gamebox.Camera(800,600)
character = gamebox.from_color(50, 50, "red", 30, 60)

def tick(keys):
    if pygame.K_RIGHT in keys:
        character.x += 5
    if pygame.K_LEFT in keys:
        character.x -= 5
    camera.clear("cyan")
    camera.draw(character)
    camera.display()
ticks_per_second = 30

# keep this line the last one in your program
gamebox.timer_loop(ticks_per_second, tick)

Give it a try! See what happens when you use the left and right keys!

Activity 6: Gravity

Let’s add some code to make our character obey gravity.

First, after you create the character, give it a yspeed:

character.yspeed = 0

Then, inside tick, you can apply gravity to your character:

character.yspeed += 1

character.y = character.y + character.yspeed

Try out your code!

Activity 7: Making a floor

Well… that was interesting. Let’s add a floor so our character doesn’t fly off the screen.

ground = gamebox.from_color(-100, 600, "black", 3000, 100)

Then, inside tick but above camera.display() add:

camera.draw(ground)

And… that almost works. We need to handle the collision.

1
2
3
4
5
6
if character.bottom_touches(ground):
    character.yspeed = 0

if character.touches(ground):
    character.move_to_stop_overlapping(ground)

The first if statement makes it so your character stops falling. The second statement ensures it doesn’t get stuck inside the floor! This can happen if the character is moving too fast when the collision occurs.

Activity 8: Your Turn! Time for POTD 15!

For the rest of lab, you should start working on your own POTD 15 (separate from your partner!).

Activity 9: Installing PyGame

You should try to install PyGame on your laptop before you leave.

Windows: Download these two files to the same folder on your computer (such as your desktop). Then double click install.bat to start the process. Go into PyCharm and verify that it worked by trying the code above.

install.bat & PyGame

If double clicking the install.bat file isn’t working, move install.bat and PyGame to the your Python install directory and try again (should be something like C:\Python34). Another thing to try if it is hanging on the terminal window and not doing anything is to run the commands like this: python -m pip install wheel and python -m pip install pygame-1.9.2a0-cp34-none-win32.whl

Mac: Download and install XQuartz. Then, download this install.sh file and run it to install the other components. Go into PyCharm and verify that it worked by trying the code above. If double-clicking the install.sh file doesn’t seem to work for you, open a Terminal window (you can do this by clicking on the magnifying glass in the upper right corner of your Mac and typing Terminal) and typing the following (assuming you saved the install.sh file to your Desktop):

cd Desktop (then hit Return)

bash install.sh (Return)

PLEASE see a TA or professor if you need assistance getting this installed!

Submission: Each partner should submit one .py file named first_game.py to the lab submission system. Please put both partners' names and id’s in two comments at the top of the file.

You must submit on time! Even if you don’t finish, submit what you have.

Lab 13 - November 19 - Game Project Work

Activity 1: Login and Record Attendance

We will be taking roll in lab each week! Please come to your assigned lab to be counted present!

Click “Lab Attendance” on the left-hand menu in Collab to register your attendance and keep up with your lab grade.
YOU MUST CLICK THE LARGE GREEN OR YELLOW BUTTON FOR YOUR ATTENDANCE TO COUNT!!

Activity 2: Find your gamebox partner and get to work!

We are giving you this week to work on your games. Stay the entire time, get help from the TAs, and work on your projects!

Submission: There is no submission this week.