Lab 14 - Quiz Game + Project Work

December 1, 2016

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!

If you are in an Olsson lab, 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. Students in Lab 109 will do attendance via direction from the TA.

Activity 2: Course Evaluations

Do your course evaluations!

Activity 3: Quiz Show

Get into groups of 3, 4, or 5 students and then select a person to be the team captain / reporter / whatever.

That one person (and only that one person) should head to the URL provided by the TAs and put in a name for your team.

Then get ready for the first question!

Activity 4: Project Work

Spend any remaining time finishing up your projects!

Submission: There is no submission this week.

more ...

Lab 13 - Game Project Milestone

November 17, 2016

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!

If you are in an Olsson lab, 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. Students in Lab 109 will do attendance via direction from the TA.

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

Each partner should submit one .py file named game.py the submission system at https://archimedes.cs.virginia.edu/cs1110/. Please put both partners' names and id's in two comments at the top of the file. Don't worry if it doesn't work - we just want to see how things are going.

more ...

Lab 12 - Pong

November 10, 2016

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!

If you are in an Olsson lab, 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. Students in Lab 109 will do attendance via direction from the TA.

Activity 2: Pairing

Remember - work with your game project partner today! If you don't have a project partner yet, find one!

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:

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 submission system at https://archimedes.cs.virginia.edu/cs1110/. 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.

more ...

Lab 11 - gamebox Intro

November 3, 2016

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!

If you are in an Olsson lab, 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. Students in Lab 109 will do attendance via direction from the TA.

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 - https://goo.gl/forms/mMdlkCOMQ1bkAIzo1

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 may add more example code as we move through POTD 16 and the project.

You should also download and look over the gamebox API and introduction - https://cs1110.cs.virginia.edu/code/gamebox/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.2 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.

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:

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 https://cs1110.cs.virginia.edu/code/gamebox/gamebox.py and https://cs1110.cs.virginia.edu/code/gamebox/infinitejumper.py into a project and running infinitejumper.py.

Troubleshooting Notes:

  1. There is a chance that this will not work with your python installation if the python command is not recognized. 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 - https://dl.bintray.com/xquartz/downloads/XQuartz-2.7.11.dmg. Then, open a Terminal window (Applications -> Utilities -> Terminal) and paste the following commands in one at a time and run them individually:

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 https://cs1110.cs.virginia.edu/code/gamebox/gamebox.py and https://cs1110.cs.virginia.edu/code/gamebox/infinitejumper.py into a project and running infinitejumper.py.

Troubleshooting Notes:

  1. If you have trouble getting fonts / text to work, try opening a terminal window and running fc-list. Let that run to completion and try again.

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 https://cs1110.cs.virginia.edu/code/gamebox/gamebox.py and put it in the same PyCharm project.

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

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

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

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!). Take a look at the examples posted on the gamebox website for ideas on how to do some more basic things!

Submission

Each partner should submit one .py file named game_lab.py to the submission system at https://archimedes.cs.virginia.edu/cs1110/. 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.

more ...

Lab 10 - Log Hunt

October 27, 2016

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!

If you are in an Olsson lab, 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. Students in Lab 109 will do attendance via direction from the TA.

Activity 2: Take Quiz 5

While you are waiting for lab to start, click on Tests & Quizzes in Collab from either the desktop or laptop and take Quiz 5 - a short review quiz on the material we have covered thus far. If you do not complete it today, you have until Sunday to do so.

Activity 3: Starting Out

First, find a partner to work with! 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 file - http://cs1110.cs.virginia.edu/code/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 at http://its.virginia.edu/network/ipspace.html, 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 submission system at https://archimedes.cs.virginia.edu/cs1110/. 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.

Solution Code

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

Lab 9 - Wendy's

October 20, 2016

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!

If you are in an Olsson lab, 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. Students in Lab 109 will do attendance via direction from the TA.

Activity 2: Take Quiz 4

While you are waiting for lab to start, click on Tests & Quizzes in Collab from either the desktop or laptop and take Quiz 4 - a short review quiz on the material we have covered thus far. If you do not complete it today, you have until Sunday to do so.

Activity 4: 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. Find a partner to work with and get ready to go!

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 https://cs1110.cs.virginia.edu/code/wendys.csv and put it into your project directory. (If you wish, you can load the file from the Internet using the urllib.request.urlopen() command as well.)

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.

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:

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.

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

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

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

Submission

Submission: Each partner should submit one .py file named wendys.py to https://archimedes.cs.virginia.edu/cs1110/. Please put both partners' names and id's in two comments at the top of the file.

Submit before you leave! Even if you don't finish, submit what you have.

Solution Code

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

Lab 8 - WahooSpoon

October 13, 2016

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!

If you are in an Olsson lab, 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. Students in Lab 109 will do attendance via direction from the TA.

Activity 2: 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.

Then find someone to work with for this week!

Activity 3: 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.

import random

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

Of course, add your own entries here!

Activity 4: 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.

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 at https://archimedes.cs.virginia.edu/cs1110/. 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.

Solution Code

{% codeblock lang:python %}

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

more ...

Lab 7 - Playing Card Encryption

October 6, 2016

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!

If you are in an Olsson lab, 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. Students in Lab 109 will do attendance via direction from the TA.

Activity 2: No Quiz this week!

Taking a week off since there was a test last week.

Activity 3: Pairing

Find some folks to work with! You can work in teams up to 3 this week!

Activity 4: 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 for this lab. Your algorithm cannot be a 1-to-1 correspondence from card to letter. In other words, you just can't do Ace of Hearts is 'A', 2 of Hearts is 'B', etc. You must be creative here! Do something a bit devious (but still decryptable)!

Here's what you need to do:

  1. Get a deck of cards and consider how you could encrypt the following message: break was too short
  2. 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.
  3. Work with your partners to come up with your encryption scheme (cipher) and then encrypt the exact message above.
  4. 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

more ...

Lab 6 - This Little Piggy Played Dice

September 29, 2016

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!

If you are in an Olsson lab, 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. Students in Lab 109 will do attendance via direction from the TA.

Activity 2: Take Quiz 3

While you are waiting for lab to start, click on Tests & Quizzes in Collab from either the desktop or laptop and take Quiz 3 - a very short review quiz on the material we have covered thus far. If you do not complete it today, you have until Sunday to do so.

Activity 3: Starting Out

First, find a partner to work with today if you have not yet done so.

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.

# Here are some suggested variables you might need:
player_temp_total = 0
player_total = 0
comp_temp_total = 0
comp_total = 0
turn = "player"
winning_score = 50

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) - something like roll = randint(1,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.

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

Submission: Each partner should submit one .py file named pig.py to https://archimedes.cs.virginia.edu/cs1110/. Please put both partners' names and id's in two comments at the top of the file.

Submit before you leave! Even if you don't finish, submit what you have.

more ...

Lab 5 - Decisions and Loops

September 22, 2016

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!

If you are in an Olsson lab, 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. Students in Lab 109 will do attendance via direction from the TA.

Activity 2: Take Quiz 2

While you are waiting for lab to start, click on Tests & Quizzes in Collab from either the desktop or laptop and take Quiz 2 - a very short review quiz on the material we have covered thus far. If you do not complete it today, you have until Sunday to do so.

Activity 3: Recitation

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

Activity 4: 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!

Consider you could do something like this to read in the square from the user:

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

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

for row in range(3):
    for col in range(3):
        square[row][col] = int(numbers[count])
        count +=1

The double for loop here will allow you to populate the list of lists called square from a single list of ints that the user enters. You are not required to use the code above if you have another way you want to do it.

Submission: Each partner should submit one .py file named lo_shu.py to https://archimedes.cs.virginia.edu/cs1110/. 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!

more ...