CS 1110 - Spring 2016 - Previous Lab Projects

Lab 1 - January 21 - 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.5.1/python-3.5.1.exe and then double-click the download to start the installation.
  2. At the Customize Python 3.5.1 screen, change “Add python.exe to Path” to “Will be installed on local hard drive”. If this is not an option, make sure to check the box beside “Add python.exe to Path.”
  3. Download the PyCharm Community Edition installer at https://www.jetbrains.com/pycharm/download/. 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.5.1/python-3.5.1-macosx10.6.pkg and then double-click the download to start the installation.
  2. Download the PyCharm Community Edition installer at https://www.jetbrains.com/pycharm/download/. Double-click the download to mount the image. Drag the icon to the Applications folder.

Lab 2 - January 28 - 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 - February 4 - 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”)

Submission

Save a picture of your image by taking a screenshot and then cropping down to just your image.

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

930-OLS-mss2x-tbh3f.png

Use 930, 1100, 1230, 200, 330, 500, 630, or 800 along with either OLS or RICE for your lab location so we can keep all the labs together and we know who you are!

Then put in BOTH of your computing IDs, separated by dashes.

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

Lab 4 - February 11 - Data Types

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 lab submission system. Please put both partners' names and id’s in two comments at the top of the file.

Lab 5 - February 18 - 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. The system is set to give quick feedback, so check to see if your solution worked!

Lab 6 - February 25 - 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 score 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

We’ll continue to use the lab submission page for this lab. Only one partner needs to submit; the system will keep track of partners for you.

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

Lab 7 - March 3 - 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! You can work in teams up to 3 this week!

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:

spring break

You’ll record everything about today’s lab here: Google Form for Lab Submission So, open a text document and start keeping all your answers so you can submit this at the end of the lab!

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

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 - March 17 - 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: $$ )

Code To Start With

To help you out, here is some code to start with, including the headers for the functions you need to write. At no time should you hardcode anything from the list of restaurants, styles, or costs! Imagine how the program should run if we added all the places in Charlottesville.

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
import random

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

def get_random_restaurant():
    # Write your code here!

def get_restaurant_style(chosen_style):
    # Write your code here!

def get_restaurant_cost(chosen_cost):
    # Write your code here!


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, ")")

Submission: Each partner should submit one .py file named wahoospoon.py to the 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 - March 24 - 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

Find someone to work with!

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
11
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 you saved from the pop up windows 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:

http://maps.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 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 - March 31 - 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

Find someone to work with!

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 11 - April 7 - 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 16 and the project.

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

Activity 4: Installing PyGame

You should install PyGame on your laptop before you leave and we encourage you to do this first!

Windows: Download these two files to the same folder on your computer (such as your desktop). This assumes you are running Python 3.5.1 as you were instructed to install at the beginning of class. If this is not the case, a staff member may need to help you.

get-pip.py & pygame-1.9.2a0-cp35-none-win32.whl

Open a command window. To do this in Windows 10, click on the Windows icon and type: cmd and hit enter.

You need to be in the same directory in the command window as where you downloaded the files. For example, if you downloaded these to your desktop, type cd Desktop and hit enter. Downloads is the other most common directory where these files may be.

Then copy and paste the following into the command window and run these commands:

1
2
3
python get-pip.py
python -m pip install wheel
python -m pip install pygame-1.9.2a0-cp35-none-win32.whl

Go into PyCharm and verify that it worked by copying gamebox.py and infinitejumper.py into a project and running infinitejumper.py.

Troubleshooting Notes:

  1. There is a chance that this will not work with your python install. If you get errors, try to change these commands by replacing the python part of the command with the full path to your python install: c:\Users\<your login name>\AppData\Local\Programs\Python\Python35-32\python.exe Note that the install location may be different than this!

  2. Another thing to try if python cannot be found normally is to use py as the command instead of python.

  3. Some browsers are downloading the .whl file as a .zip file. Rename the file first!

  4. If you downloaded 64 bit python instead of 32 bit python (you can verify this by running python on the command line and look at the version), then use this whl file instead http://cs1110.cs.virginia.edu/code/gamebox/pygame-1.9.2a0-cp35-none-win_amd64.whl

Mac: Download and install XQuartz. Then, open a Terminal window (Applications -> Utilities -> Terminal) and paste the following commands in and run them:

1
2
3
4
5
6
7
xcode-select --install
ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
alias brew=/usr/local/bin/brew
brew install mercurial 
brew install git
brew install sdl sdl_image sdl_mixer sdl_ttf smpeg portmidi
pip3 install hg+http://bitbucket.org/pygame/pygame

Go into PyCharm and verify that it worked by copying gamebox.py and infinitejumper.py into a project and running infinitejumper.py.

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

Activity 5: Simple Example

Start by creating a new game. Call it game_lab.py. Then, if you haven’t already, 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 6: 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 7: 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 8: 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 9: Your Turn! Time for POTD 16!

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

Submission: Each partner should submit one .py file named game_lab.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 12 - April 14 - Pong

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

Remember to work with your project partner today! If you don’t have one, talk to a TA!

Activity 3: Starting Out

Today we are doing an example game in gamebox - specifically the classic game Pong. If you are unfamiliar with Pong, head over to http://www.ponggame.org/ to see what it’s all about.

We’ll play by a basic version of the rules:

  • There is a ball that bounces back and forth.
  • Move your paddle on your side of the screen to prevent it from getting past you.
  • If it gets past you, your opponent earns a point.
  • First player to 10 points wins.

After you’ve figured out how the game plays, copy the following files and code into a new Python file in the same directory as your gamebox.py file. (If you need a new copy, you can get that here, along with some other example code and a blank starter file).

Activity 4: Complete the Game

If you run the game as is, you should see what the game will look like, but nothing actually works. We have left comments in the pong.py file that describes the code you need to add to make the game work. Add some code, try it out, and keep going until you have a working Pong game!

Activity 5: Work on POTD 16 and the project!

Take the rest of the lab to work on your POTD and project games!

Submission: Each partner should submit one .py file named pong.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 - April 21 - 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: Both you and your partner should submit whatever you have in game.py at the end of lab. Don’t worry if it doesn’t work - we just want to see how things are going.