After around two months of using the iPad, I wanted to do another review! It’s hard to imagine what it was like before I had the iPad as it’s really changed the way I study and the amount of things I need to bring around. Not only have I been relying on my computer less, but especially during the holiday it was nice to be able to go out and do work (and not have to lug around so many devices and notebooks).
In today’s blog post, I want to detail the pros and cons of my study habits with the iPad:
Pros!
AP Studying: Both my sister and I can attest to the fact that the iPad has changed the way we have studied for APs. Instead of wasting so much paper doing FRQ and MCQ practice on paper, we can now pull up a blank document on the iPad and do them on the iPad. Organisation of practice FRQs for reference later on has also been improved!
Motivation:It sounds really weird, but having the iPad has motivated me to study more. When I’m bored instead of switching on my phone, I change the colour of the pen I’m using and do more work!
To do lists and random notes: I used to waste a lot of paper on making to do lists. Those have now seamlessly been added to my calendars digitally through the iPad.
Multitasking: I talked about this in my previous blog post, but the multitasking feature on the iPad has helped me in the way I study. I can have my bio textbook out and write notes, or have Albert.io out and do MCQ practice. It makes studying much more convenient and much more accessible.
Furthermore, after interim I’ve been working a lot on self improvement as one of my goals for the rest of the year. I downloaded the headspace app and have been doing good breathing exercises on there as well!
Cons 🙁
After using the iPad for a lot of reviewing and studying I found that there were some minor things that were slightly inconvenient. The first was the apple pencil charging. Although the pencil charges really quickly, I never thought I would find myself in the position where I need to charge a pencil! But all in all, it’s quite effective as when my apple pencil hits 0% I give myself a break to let the pencil charge.
Eye pain– Between staring at my phone, computer and iPad, my eyes started to hurt a lot more. I ended up having to take a short break and write some notes on paper. I think that moderation on screen time helps a lot!!!
So far, the experience with the iPad has been a positive change for multiple reasons. One of the main benefits of using the iPad so far has been the amount of paper I’m saving from using the iPad. Taking science and math courses, it’s very easy to waste a lot of paper on scrap work. Ever since I started using the iPad, I’ve been able to do my scrap work on my iPad instead of on paper. This helped me reduce the amount of books I carry to school as well as the amount of paper I use. In terms of a specific course, I started to do all of my Ap Chem work on the iPad instead of on paper. Since chemistry involves a lot of calculations and a lot of practice, I used the app notability to do all my homework and class work on. The receptiveness of my Chem teacher was quite good as she allowed me to use the iPad in class to take notes.
I’ve been using my iPad for countless of different tasks related to school. From planning club meetings to jotting down to do lists, I’ve been using apps like Notability and all the Google apps. At first, I was skeptical about taking notes on the iPad, but after giving it ago I prefer it more to normal paper due to convenience. I used the Notability app to edit my Hum papers and to do workings for chem.
One feature that I’ve found super useful so far is the split screen feature. I’ve used this to take notes on Biology, but also to reference charts and tables for chem. One application that I’d love to try is the calculator app or Procreate. The calculator app is the same one the math teachers use. The app is similar to the calculator and would mean on most days I would need to only bring my iPad to school (the amount of things to carry would be limited!) I think that in terms of getting procreate, it’d help a lot with the design work I’m doing. From poster making to designing murals for school walls, the app would be super helpful in creating some sort of space for me to create.
One thing that I would love to try out is just bringing my iPad to school and seeing if I could do a day without my computer. I think that on most days I don’t use my computer at school and take out my iPad anyway – I’d love to test out to see if my iPad could be an alternative in replacing my computer.
Down below I’ve attached a couple of pictures of the things I’ve been doing on my iPad.
Throughout the holiday we were challenged to continue coding through codeacademy. The aim of this was to continue to code, and to not lose the language throughout our holiday. At first, I found the codeacademy quite repetitive, but after a while, I managed to incorporate five minutes into each day of the break. Some of the code was different from what we used in class, but overall the codeacademy was a good refresher to what we were already taught within the coding class.
A day at the supermarket (sublesson):
This subsection talked mostly about how to use lists and dictionaries:
BeFOR We Begin:
For loops:
For loops are used in order iterate through all of the elements in a list from the left-most to the right-most.
for item in [1, 3, 21]:
print item
A variable, in this case “item”, can be a variable between for and in. Remember that within the brackets to put perhaps the list you want to print from. For example if the list is named names= [Adam, Benny, Catherine] that in the for loop you make a new variable (eg. item) and you want to print all of the items in the list. Your code will look like this:
for items in [names]: print items
This is KEY!:
webster = {
"Aardvark" : "A star of a popular children's cartoon show.",
"Baa" : "The sound a goat makes.",
"Carpet": "Goes on the floor.",
"Dab": "A small amount."
}
# Add your code below!
for key in webster:
print webster[key]
For this code I had to print the definition of each item in the “dictionary”. This meant creating the variable key and for key in webster, we would print an amount or a certain part of the dictionary.
List and Functions:
For this task, the program asked for the me to code a function that counted the number of times the word fizz is found within a list:
def fizz_count(x):
count = 0
for item in x:
if item=="fizz":
count= count+1
return count
print fizz_count(["fizz", "buzz", "fizz"])
The code essentially is a function that takes from the list “x”. The function counts how many times the string “fizz” is in the list. Since the aim of the code is to create a count, the count variable is used and for every item that equals “fizz”, will make the counter go up by one.
Your own store:
Create a inventory of the different items that you keep at your store:
for fruit in stock:
total = total +(stock[fruit] * prices[fruit])
print total
For this section I had to create a code that multiplied the stocks of fruit, by the prices of the fruit. In order to do this we started off with the stock of each fruit. For the fruits in stock, the total would be equal to the total added to the fruit stock number with the prices of the fruit.
Making a purchase:
For each number in the list, we add that number to the running sum of the total. In order to make a code that takes both the lists and dictionaries; combines them and makes a price into count, we had to use the for in loop.
shopping_list = ["banana", "orange", "apple"]
stock = {
"banana": 6,
"apple": 0,
"orange": 32,
"pear": 15
}
prices = {
"banana": 4,
"apple": 2,
"orange": 1.5,
"pear": 3
}
# Write your code below!
def compute_bill(food):
total= 0
for item in food:
total += prices[item]
return total
def compute_bill(food):
total= 0
for item in food:
if stock [item] > 0:
total += prices[item]
stock[item]= stock[item]- 1
return total
For this part in the code, we had to create a program and modify the program that we already made. For this part we only did the for loop if the item was in stock. If it was in stock, so when it equaled to more than 0, then the total would equal to the price of the item. It would also mean that the stock of the item was less, which would equate in the item stock being one less.
Here is my summative project on making a google reminder PE makeup program, that we hope will help the PE teachers in the future.
Day 1 Reflection:
Today we used the time to go to different people and ask about the different problems that occur in our school environment. We made a form in order to try to not only have the opinions of our small group, but also the general public of school. By getting out and doing the survey, it allowed us to empathise with our audience about the specific problems that we saw around school. We had two main problems that we saw, so we tried to see which one was a larger problem that affected more people. In order to do this, we produced a form that briefly outlined the two problems, and asked the user which problem affected them more.
For next class, we hope to finish up the survey, and ask the PE department what they think of our ideas, and some feedback that they have. Furthermore, we hope to start the project, and possibly start to code it.
Here is the form that we used for the empathy part of the problem.
We first started with making three subcategories: medical, school, and other problems. When we first started to make these subcategories, we then just started to list the problems that we saw. After listing all the problems, we managed to narrow it down to six different problems and solutions that could be feasible. We then discussed which ones would be better, and would interest us more. However, we narrowed it down so we still had two left, in which we then could make a survey about the different ideas, and empathise with the user on which one was better.
After we got to the two ideas, we then used the time to make the form so that we could go out and ask people not only which problem affected them more, but also their take, and why the problem does affect them.
What was the problems we looked at?
The problems that we narrowed the survey to was the problem of dehydration and the mile counter.
The first was the dehydration problem:
Many people in our world today face the problem of dehydration; I myself have also faced this problem before, in which it is not the forgetfulness of drinking water, but that you simply don’t feel thirsty, when in fact are dehydrated. When this occurs, many people fail to get up and drink more water. By doing so, they are negligent to the fact that they are dehydrated. After doing some research, we realised that we lose water even by breathing, and so when we don’t put in more water into our body, we can get dehydrated. Most adults should be drinking eight eight ounce cups of water every single day. However, statistics have shown that in general people drink around 5 cups of water, which is not enough for daily input. Furthermore, in a school environment, many students forget to drink water as its not widely accessible to fill up water, and some people simply forget. Other times, people will not drink water after they exercise or after PE, and most often, people will not drink during class, which means that they do not drink water for a whole 1 hour and 30 minutes.
The second problem we noticed in school was the problem of the mile run:
The mile itself, or running it, is a process that every student in HKIS must undergo in order to get a grade for PE. The problem, therefore, is not the mile itself, but instead that of tracking it. A PE class on average will be 20-23 students, in which when all running the mile at the same time, the teachers have to keep the times and laps of each student on the top of their heads. Many choose to run it in two separate groups, where one group will run then the next so there is less kids to track, while other PE classes choose to use the pairing off method, where every student has a partner that is tracking their mile. However, even though these are great compensations, it is still not both time efficient and effective.
The third problem that we noticed:
This problem was when someone does the 12 minute swim. Sometimes, the person who is counting your laps can get distracted and miscounts how many are left. This could not only affect your performance, because you have to take count of how many laps you swam, but it could also affect your grade at the end.
What was the solutions?
Solution #1 for the dehydration problem:
Through programming we hoped that we could create a water bottle that would have different markings on it, in which at a certain time in the day when the water was still touching the mark, it would send a reminder to the phone or apparatus about the fact that the person has to drink water. Since the bottle and the computer or device is linked, it would send the reminder only if its noticed that the person hasn’t drunk water. This would help students and any person not forget to drink water. This would reduce the issue of neglecting to drink water.
Solution #2 for the dehydration problem:
Create some sort of reminder device, like a watch or other wearable device that would allow the user to see and track how much water the have had that day. By doing this, it would allow the user to track how much water they were drinking. This could be a wearable device that tracks the water, and also reminds a person to drink more water.
Solution #1 for the mile tracking problem:
Have a watch like device worn by all students that is connected to a DFID reader of some sort. This would mean that every time a person runs a lap, their watch would be like a bar code scanner, and it would be able to track their lap time, as well as the overall time. This would be stored on a database, that could be accessed by students to see how they can improve, as well as the teachers. With this database, it also allows them to track their improvement and also how many IFs they will need to do based o this .
For this solution you would need to produce a scanner, and make a watch with some sort of barcode. Also, it would need to have some sort of indicator if you pass the reader, so that it beeps or does some sort of command that would tell the user that they have just completed a lap. Furthermore, this device would help because the field is not shaped to a 400 meter field, but instead one that is slightly smaller. Hence, this will make the tracking for teachers even harder, where if there was a tracking device it would put more ease on the teachers.
What was our form (step by step)
The first part of the form was to create awareness. This is the description at the top of the questionnaire in which explained more about the questions, and what the purpose of the form was. The first question that we made was whether the user had had any problems with PE. These problems were varied in the answers, but most had to do with the tracking of the mile and the twelve minute swims.
The next part was mainly a mixture of empathy questions so that we could really see what people’s perspectives on the problem were. By asking questions that opened the solutions up to the audience, it allowed us to see the viewer’s opinions on these issues.
The other questions followed similar formats. From this we hoped not only to get an insight with our users, but also be able to find out how they would approach these issues.
What did people say:
We are still gathering the information from different people, but once we get a good variety, we will be able to compile what they say into a reflection.
Final reflection:
Overall, the project today went well. I think it’s safe to say that so far we have all been having a lot of fun, especially since we were able to finally solve some of the problems we saw in our world through programming. It’s also fun to see these problems, and be able to come up with creative solutions. Furthermore, going through the entire learning and design process cycle again with programming this time is enticing and interesting. Through doing the survey today, it really opened my eyes towards what people thought were problems, and what they thought the solutions could be.
Day 2 Reflection:
Today we went to see some of the PE teachers down in the middle school. We interviewed them to see what exactly we could help them with to make their lives slightly easier. Throughout this interview we learned more about what exactly they wanted to see in their program.
Idea #1:
The PE teachers wanted a program in which would be like a drag and drop method alike to powerschool, where they could easily make the grading system more user friendly. Although this idea was very interesting, it was too similar to the Powerschool. However, as we further empathised with them, the program they described was very similar to schoology. We realised that the middle school teachers were still not using schoology as a platform for grades even though at times this platform would be more efficient. We decided this was a good opportunity to start the middle school and boost the schoology use throughout. Furthermore, the platform we would have created would have been one that would have been not as efficient as a professional platform such as schoology.
Idea #2:
Since the first idea was too similar to schoology, we then asked them what other things that they hd problems with. One that was mentioned was the fact that the system for doing PE makeups wasn’t as good as it should be. Teachers found it difficult to track the makeups, and students were also forgetting that they had to makeup classes.
We decided in the end to go with the second idea, something that was realistic in the time frame given. In order to do this, we decided to utilise the google scripts, so that we could use the different google apps and link them together. By doing this, it would allow an easy way for students to fill out a form, and it would automatically send the student and the teacher an email based on the things that they filled out in the for.
We had to redo our questionnaire, and ask the teachers of their opinions. Most of the questions that we asked the PE teachers were after we listened to what they said, then adjust the questions to gather more information.
Here is the recording of the interview we did with the teachers:
Empathy:
Throughout the project we exercised a lot of empathy. It was because we kept gathering new data, and asked questions to different audiences that we were able to create a product that fit what the users needed. We asked questions about mile trackers, dehydration, and finally found out that the users really needed a product that was more like a reminder system. We realised that sometimes we see things that are problems in our society, but the majority of the people, or the audience we see best fit, may have more urgent products that they need created.
Design thinking sentence:
We wanted to create a reminder system that would not only send a reminder email to the student, but also notify the teacher about the makeup the students needed to do. By doing this, we hope to alleviate any sort of problems that would have been faced when asking students to do a makeup. This system would also create a google calendar event, that would then later be shown in the calendar for both the student and the teachers.
Materials needed:
1. Google scripts
2. Google form
3. Java script
HEre is some of the planning documents we had:
The process of creating the reminder system:
One of the first things that we did was set up a google document that started to plan what the reminder system would do. This allowed us to play and work towards a goal in mind on what exactly our reminder system would do. Furthermore, we had to discuss with Mr. Lin about the most effective way for us to make this reminder system. We settled on making it with google scripts, which would allow us to utilise all the different accounts and google apps.
This was our original planning document, with the start of the pseudo code as well. Since we had never used google scripts before, it was hard to make the pseudo code. However, as the process continued, we managed to understand the code, and what it would look like in python.
This was our code to send the email, and make a mail merge. By doing this, we were able to use the different items and answered in the form inside the email as the email would help to remind the student of what they need to do for their PE makeup. The email that was sent would be on form submit, which means that every time a user submits the form, the form would record it, and send an email based on what the user inputted.
We decided for the pseudo code and flow chart to write it all out by hand so we could better visualise all of the parts of our code:
Here you can see the two parts of the code and how they relate to each other. Through this code, you are able to see the parts of the code, as well as the key aspects and how they are relative to the functions of the code.This first part you can see a visual flowchart of how our code works. It explains what happens on a superficial level, in terms of how the form is filled in, and an email is being sent.
Here we show the different way that the program works. We decided to explain some of the flow chart as a written infographic, in which people (normal people) could understand the basis of how our code works. This means that we explained what would happen on a superficial level. So the form is submitted and thus the email is sent to the people who have submitted the form. We also chose to include different ways the form could be used besides the way we used it to make a PE make up form. Some of the ways we thought of wasany situation where the people would need to send out a form to ask their colleagues to fill out, and gather information. It could also work for large competitions, or conferences, where the form could be sent out and the email would come back as a reply.
Here we showed the pseudo code simplified. The code itself is self explanatory, as the java script used in google scripts will have titles that show exactly what that variable, or part does. In order to complete this we also used some of the indexes that were found on the google script website. This allowed us to find some of the sources, and understand the code better. Furthermore, we explained the calendar function within the code. This part was mostly theoretical, since we learned the code, but didn’t have enough time to add it, and make it function along side the email code. However, the calendar feature is one that was quite interesting, since after filling out the form, the people
Here we showed how the email merge setting worked.
function sendEmails() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var dataSheet = ss.getSheets()[0];
var dataRange = dataSheet.getRange(2, 1, dataSheet.getMaxRows() - 1, 11);
This first part was used as a function that was called throughout the entire code, to gather the data from the sheet, and use it throughout the sheet. We used the special ways functions of google scripts in order to get the data from the sheet. One of the problems that we did face was that the code at first was set for the max rows to be limited to 4 -1= 3 rows. This meant that when we added more rows, the email function didn’t work. Once we were able to find the piece of code that controlled this, we were able to change the max rows so that it could fit how many rows we had. We then adjusted the last number, in order for the code to read more rows. The code above gets a range that contains the data in the spreadsheet.
var templateSheet = ss.getSheets()[1];
var emailTemplate = templateSheet.getRange("A1").getValue();
Here we showed how the email merge setting worked. The code above retrieves the string template that will be used to generate the personal emails. Now, it allows the PE teachers to draft an email, and in the email draft template, the ${“”} can be used to show which cells the word needs to be replaced by.
// Create one JavaScript object per row of data.
objects = getRowsData(dataSheet, dataRange);
// For every row object, create a personalized email from a template and send
// it to the appropriate person.
for (var i = 0; i < objects.length; ++i) {
// Get a row object
var rowData = objects[i];
// Generate a personalized email.
// Given a template string, replace markers (for instance ${"First Name"}) with
// the corresponding value in a row object (for instance rowData.firstName).
var emailText = fillInTemplateFromObject(emailTemplate, rowData);
var emailSubject = "MS PE Makeup Reminder";
MailApp.sendEmail(rowData.emailAddress, rowData.emailAddress, emailSubject, emailText);
}
}
This code is what sends the actual email. It was fascinating to see how with such little code could make an email send to the user. Furthermore, the function “FillInTemplateFromObject” is used to match the code and fill in the email response.
The variableData is used to retrieve the value of a data object. This is done by normalising the marker name. By doing this, and normalising the name, it allows us to replace all the markers with the string made by the form. This data could replace the object.
// Replaces markers in a template string with values define in a JavaScript data object.
// Arguments:
// - template: string containing markers, for instance ${"Column name"}
// - data: JavaScript object with values to that will replace markers. For instance
// data.columnName will replace marker ${"Column name"}
// Returns a string without markers. If no data is found to replace a marker, it is
// simply removed.
function fillInTemplateFromObject(template, data) {
var email = template;
// Search for all the variables to be replaced, for instance ${"Column name"}
var templateVars = template.match(/\$\{\"[^\"]+\"\}/g);
// Replace variables from the template with the actual values from the data object.
// If no value is available, replace with the empty string.
for (var i = 0; i < templateVars.length; ++i) {
// normalizeHeader ignores ${"} so we can call it directly here.
var variableData = data[normalizeHeader(templateVars[i])];
email = email.replace(templateVars[i], variableData || "");
}
return email;
}
getRowsData iterates row by row in the input range and returns an array of objects. // Each object contains all the data for a given row, indexed by its normalized column name.
Arguments:
– sheet: the sheet object that contains the data to be processed
– range: the exact range of cells where the data is stored
– columnHeadersRowIndex: specifies the row number where the column names are stored.
// This argument is optional and it defaults to the row immediately above range;
// Returns an Array of objects.
function getRowsData(sheet, range, columnHeadersRowIndex) {
columnHeadersRowIndex = columnHeadersRowIndex || range.getRowIndex() - 1;
var numColumns = range.getEndColumn() - range.getColumn() + 1;
var headersRange = sheet.getRange(columnHeadersRowIndex, range.getColumn(), 1, numColumns);
var headers = headersRange.getValues()[0];
return getObjects(range.getValues(), normalizeHeaders(headers));
}
// For every row of data in data, generates an object that contains the data. Names of
// object fields are defined in keys.
// Arguments:
// - data: JavaScript 2d array
// - keys: Array of Strings that define the property names for the objects to create
function getObjects(data, keys) {
var objects = [];
for (var i = 0; i < data.length; ++i) {
var object = {};
var hasData = false;
for (var j = 0; j < data[i].length; ++j) {
var cellData = data[i][j];
if (isCellEmpty(cellData)) {
continue;
}
object[keys[j]] = cellData;
hasData = true;
}
if (hasData) {
objects.push(object);
}
}
return objects;
}
// Returns an Array of normalized Strings.
// Arguments:
// - headers: Array of Strings to normalize
function normalizeHeaders(headers) {
var keys = [];
for (var i = 0; i < headers.length; ++i) {
var key = normalizeHeader(headers[i]);
if (key.length > 0) {
keys.push(key);
}
}
return keys;
}
// Normalizes a string, by removing all alphanumeric characters and using mixed case
// to separate words. The output will always start with a lower case letter.
// This function is designed to produce JavaScript object property names.
// Arguments:
// - header: string to normalize
// Examples:
// "First Name" -> "firstName"
// "Market Cap (millions) -> "marketCapMillions
// "1 number at the beginning is ignored" -> "numberAtTheBeginningIsIgnored"
function normalizeHeader(header) {
var key = "";
var upperCase = false;
for (var i = 0; i < header.length; ++i) {
var letter = header[i];
if (letter == " " && key.length > 0) {
upperCase = true;
continue;
}
if (!isAlnum(letter)) {
continue;
}
if (key.length == 0 && isDigit(letter)) {
continue; // first character must be a letter
}
if (upperCase) {
upperCase = false;
key += letter.toUpperCase();
} else {
key += letter.toLowerCase();
}
}
return key;
}
// Returns true if the cell where cellData was read from is empty.
// Arguments:
// - cellData: string
function isCellEmpty(cellData) {
return typeof(cellData) == "string" && cellData == "";
}
// Returns true if the character char is alphabetical, false otherwise.
function isAlnum(char) {
return char >= 'A' && char <= 'Z' ||
char >= 'a' && char <= 'z' ||
isDigit(char);
}
// Returns true if the character char is a digit, false otherwise.
function isDigit(char) {
return char >= '0' && char <= '9';
}
Here is a video of our code working:
Furthermore, we tried to create a code that would allow us to make a calendar event based on what the form filled out. After following some of the code from different sources, we saw how it fundamentally worked as individual parts, but when we tried to put it together, it didn’t fully work according to plan.
Here is the code:
/**
* A special function that inserts a custom menu when the spreadsheet opens.
*/
function onOpen() {
var menu = [{name: 'Set up conference', functionName: 'setUpConference_'}];
SpreadsheetApp.getActive().addMenu('Conference', menu);
}
/**
* A set-up function that uses the conference data in the spreadsheet to create
* Google Calendar events, a Google Form, and a trigger that allows the script
* to react to form responses.
*/
function setUpConference_() {
if (ScriptProperties.getProperty('calId')) {
Browser.msgBox('Your conference is already set up. Look in Google Drive!');
}
var ss = SpreadsheetApp.getActive();
var sheet = ss.getSheetByName('Sheet 1');
var range = sheet.getDataRange();
var values = range.getValues();
setUpCalendar_(values, range);
setUpForm_(ss, values);
ScriptApp.newTrigger('onFormSubmit').forSpreadsheet(ss).onFormSubmit()
.create();
ss.removeMenu('Conference');
}
/**
* Creates a Google Calendar with events for each conference session in the
* spreadsheet, then writes the event IDs to the spreadsheet for future use.
*
* @param {String[][]} values Cell values for the spreadsheet range.
* @param {Range} range A spreadsheet range that contains conference data.
*/
function setUpCalendar_(values, range) {
var cal = CalendarApp.createCalendar('Conference Calendar');
for (var i = 1; i < values.length; i++) {
var session = values[i];
var title = session[0];
var start = joinDateAndTime_(session[1], session[2]);
var end = joinDateAndTime_(session[1], session[3]);
var options = {location: session[4], sendInvites: true};
var event = cal.createEvent(title, start, end, options)
.setGuestsCanSeeGuests(false);
session[5] = event.getId();
}
range.setValues(values);
// Store the ID for the Calendar, which is needed to retrieve events by ID.
ScriptProperties.setProperty('calId', cal.getId());
}
/**
* Creates a single Date object from separate date and time cells.
*
* @param {Date} date A Date object from which to extract the date.
* @param {Date} time A Date object from which to extract the time.
* @return {Date} A Date object representing the combined date and time.
*/
function joinDateAndTime_(date, time) {
date = new Date(date);
date.setHours(time.getHours());
date.setMinutes(time.getMinutes());
return date;
}
/**
* Creates a Google Form that allows respondents to select which conference
* sessions they would like to attend, grouped by date and start time.
*
* @param {Spreadsheet} ss The spreadsheet that contains the conference data.
* @param {String[][]} values Cell values for the spreadsheet range.
*/
function setUpForm_(ss, values) {
// Group the sessions by date and time so that they can be passed to the form.
var schedule = {};
for (var i = 1; i < values.length; i++) {
var session = values[i];
var day = session[1].toLocaleDateString();
var time = session[2].toLocaleTimeString();
if (!schedule[day]) {
schedule[day] = {};
}
if (!schedule[day][time]) {
schedule[day][time] = [];
}
schedule[day][time].push(session[0]);
}
// Create the form and add a multiple-choice question for each timeslot.
var form = FormApp.create('Conference Form');
form.setDestination(FormApp.DestinationType.SPREADSHEET, ss.getId());
form.addTextItem().setTitle('Name').setRequired(true);
form.addTextItem().setTitle('Email').setRequired(true);
for (var day in schedule) {
var header = form.addSectionHeaderItem().setTitle('Sessions for ' + day);
for (var time in schedule[day]) {
var item = form.addMultipleChoiceItem().setTitle(time + ' ' + day)
.setChoiceValues(schedule[day][time]);
}
}
}
/**
* A trigger-driven function that sends out calendar invitations and a
* personalized Google Docs itinerary after a user responds to the form.
*
* @param {Object} e The event parameter for form submission to a spreadsheet;
* see https://developers.google.com/apps-script/understanding_events
*/
function onFormSubmit(e) {
var user = {name: e.namedValues['Name'][0], email: e.namedValues['Email'][0]};
// Grab the session data again so that we can match it to the user's choices.
var response = [];
var values = SpreadsheetApp.getActive().getSheetByName('Conference Setup')
.getDataRange().getValues();
for (var i = 1; i < values.length; i++) {
var session = values[i];
var title = session[0];
var day = session[1].toLocaleDateString();
var time = session[2].toLocaleTimeString();
var timeslot = time + ' ' + day;
// For every selection in the response, find the matching timeslot and title
// in the spreadsheet and add the session data to the response array.
if (e.namedValues[timeslot] && e.namedValues[timeslot] == title) {
response.push(session);
}
}
sendInvites_(user, response);
sendDoc_(user, response);
}
/**
* Add the user as a guest for every session he or she selected.
*
* @param {Object} user An object that contains the user's name and email.
* @param {String[][]} response An array of data for the user's session choices.
*/
function sendInvites_(user, response) {
var id = ScriptProperties.getProperty('calId');
var cal = CalendarApp.getCalendarById(id);
for (var i = 0; i < response.length; i++) {
cal.getEventSeriesById(response[i][5]).addGuest(user.email);
}
}
/**
* Create and share a personalized Google Doc that shows the user's itinerary.
*
* @param {Object} user An object that contains the user's name and email.
* @param {String[][]} response An array of data for the user's session choices.
*/
function sendDoc_(user, response) {
var doc = DocumentApp.create('Conference Itinerary for ' + user.name)
.addEditor(user.email);
var body = doc.getBody();
var table = [['Session', 'Date', 'Time', 'Location']];
for (var i = 0; i < response.length; i++) {
table.push([response[i][0], response[i][1].toLocaleDateString(),
response[i][2].toLocaleTimeString(), response[i][4]]);
}
body.insertParagraph(0, doc.getName())
.setHeading(DocumentApp.ParagraphHeading.HEADING1);
table = body.appendTable(table);
table.getRow(0).editAsText().setBold(true);
doc.saveAndClose();
For this code, we coded the parts we understood first. Some of the parts were how the document would be connected towards the form ad the calendar. This meant that using the function sendDoc, this document would be sent as an Itenary to the user. Furthermore, through the event series ID, the calendar would be set up.
Throughout the code we managed to use the function of triggers. Triggers allowed us to create the program to run every single time a new event was created, or the form was created. The triggers allow for on form submit, which then allows the entire program to run throughout this time.
Here is our testing document. Since Java script on google script was completely new to us, we faced many errors. Some of which we still need to fix, but we managed to fix majority of the problems faced.
Here is the videos explaining the code, and some of the challenges we faced:
Teamwork:
I feel like for this project teamwork was a bit of a challenge. In general, to split the work three ways is difficult, especially if we were learning a whole new language to code in. I also feel like even though I tried to spread the work pretty evenly, most of the time it was hard to give work out if the work was all in the new programming language. I think that overall, the brainstorming part went well as a team, but the actual programming took a toll on our teamwork, and the work wasn’t spread as evenly.
Conclusion:
Thus, throughout this project I learned not only how to make a reminder system, but more importantly learned that coding itself is not a hard thing to learn. The hardest part about coding is empathising with our audiences. Although the code at times was frustrating, and the code is still not perfect now, the end goal was less of a finished product, but a product that in the end would help our users in the best way possible. We changed our project from a mile tracker, to balance board, to a dehydration bottle, to a gradebook and lastly to the reminder system, all to best fit our audience. It was this process where we learned and empathized most with our audience.
I came into the course thinking that the empathy part was terrible, and completely useless, but now I realise that coding is just a tool in order to help us help our audience better. I came in thinking that the empathy part was useless, and that we should have been instead using the class time to go over functions, and lists. I came throughout this project, whilst lerning a complete new language, that coding itself is one that is something you can learn if you put your heart to, but empathy is one that makes purpose behind the code made.
Furthermore, for the course review, I think it was one of the best classes that I have taken, because throughout it, I managed to see how I really wanted to pursue computer science as some part of my learning path. I realised that the coding language, and everything tech, had fascinated me throughout this course. Furthermore, it pushed me to challenge logic, and think clearer in my other subjects as well. Most importantly, I had fun throughout the course, and all the projects we did, I was glad to challenge myself, and find the different methods to code the same things. It was due to this class where I found another passion of mine, that I want to pursue in the future. I also think that through this course I learned to be more self motivated, because the entire point of coding is for it to be a project that you do have to search things up online and utilise your teachers around you. Hence, I think that this class was one of the best classes I have taken this semester, and I can’t wait to learn more through SDLT, as well as AP Computer Science!!
Citations:
GOOGLE. “Overview of Google Apps Script | Apps Script | Google Developers.” Google Developers. Google, Github, 12 Aug. 2016. Web. 18 Jan. 2017.
Hugo Fierro. “Tutorial: Simple Mail Merge | Apps Script | Google Developers.” Google Developers. Google, 13 May 2016. Web. 18 Jan. 2017.
In today’s lesson we started to work on our formative piece. For this formative, our task is to make an operation game cooperating the makey makey, and possibly pygame. Working in groups of 2,3, or 4, we started to brainstorm ideas for the project. Our first step was to go to pinterest and look at the different games that were made with pinterest. As a group, we went through multiple different ideas, and what was practical, or challenging to make. Some of the ideas that we looked at were creating quizzes, and the operation game. However, we decided finally on making a lifesize piano, that people could step on and it would play songs or music depending on the keys that the user stepped on.
For this lesson, we started with creating the pseudo code, brain frames, and different designs that we would look at. Furthermore, we looked at the different types of pianos we could make, and made a blueprint to work with.
For our design, we really wanted to focus on what was important for the design, and the purpose of creating this. We wanted to create something that did relate or help a certain audience. We researched more into obesity, a large problem throughout the entire world, and things that could help relieve stress. In our environment today, especially with finals coming up, stress was a large issue we wanted to help reduce in our society today. One of the main stress relievers that have been scientifically proven is to play an instrument. So this sort of drived us to making a piano, and one that is lifesized so you can play it with your friends. Furthermore, we also wanted to do something that could help people dealing with health issues. So we decided to make a lifesize piano, which would allow our audience to move and be active whilst creating music.
This part of our project is crucial for the long run. Not only do we now have a goal and purpose of our project, but also we have a pseudo code to work off of. This is important because the pseudo code allows anyone, that codes in any language, do you use this code and be able to have a functioning code. Furthermore this part was crucial in finding our purpose. This brings us back to the empathy cycle, because anyone who is willing to learn to code can code. In order to have a successful website, app, or code, you need a purpose. Without a purpose, nobody can gain from this, and it becomes little of value. By having a purpose, it allows us to move forward with a goal in mind and tweak our project based on our audience.
This is our flow chart, and some of our initial sketches that we drew. By creating a flow chart, we were able to visualise all the things that we had to do, and helped us plan the project thoroughly.
Here is a photo of our materials list, and some of our sketches of how the piano was going to be connected. By doing this, it allowed us to think about the resources we were using, and this enables us to start working next class straight away without missing equipment.
The drawing gave us a better idea of how the connections would work. We decided at this point to make it first with scratch, then to move on and challenge ourselves from there.
The pseudo code was necessary for us to think about how the program was going to look like. The pseudo code, we learned this class, is very essential to any piece of code, so that people that program in various different programs are able to make the same thing with the pseudo code at hand.
1. Print “Would you like to play Just Dance: Bach at it again?”
If awnser = yes:
Print “Do you want to try the song, “Mary hadda little lamb?””
2. If awnser is yes:
Print ” Okay!! Get ready for the notes to appear on your screen”
Print song function
If awnser is no:
Print “Try to create your own song, then.”
3. Print “Would you like to record your song?”
If awnser = yes:
Print “Your song has been saved”
If else:
Print “Ok, this is a one time thing!”
If else:
Print “Ok”
Go back to the begining code
4. Function song
While keys are being pressed:
If B note / space bar is pressed :
Play recoding of B
If A note / left arrow is pressed :
Play recording of A
If G note / right arrow is pressed :
Play recording of G
If D note / up arrow is pressed :
Play recording of D
If E note / down arrow is pressed :
Play recording of E
If F note / W key is pressed :
Play recording of F
If A# note / E key is pressed :
Play recording of A#
If C# note / S key is pressed :
Play recording of C#
If D# note / A key is pressed :
Play recording of D#
If F# note / D key is pressed :
Play recording of F#
If else:
Print “Not on mat!! Get Back on”
5. Function record:
add a record function
This was our psuedo code for the class.
For next class we hope that we can be able to make our piano, and test it out with scratch. Furthermore, we hope to learn more about how we could use pygame to code the game. It will be interesting to learn how to do this, and incorporate our coding from before in order to do this.
Reflection:
Today’s class today went really well, and the whole process has been a smooth one so far. I’m excited to see where this will go! Furthermore, I think that it’ll be exciting to improve our original piano, and code it with pygame, as well as be able to hopefully help people through this project!
Day 2+3 :
In today’s class:
In today’s class we worked mostly on constructing the piano to work, and for us to be able to make it function like how it is supposed to function. it was interesting o find out how hard this project in general were, but also how in the beginning we underestimated the project. We didn’t expect it to be so hard, especially when we tried to challenge ourselves throughout the entire project.
For this specific project, our testing document was mostly to test out the different connection s between the makey makey, and the actual keyboard. Furthermore, since we tried this on multiple different codes, we had to test out each and every one of the codes. By making the tracking document earlier, this allowed us to be able to track our progress throughout the entire project, and for us to be able to document the problems we had throughout the entire project.
In these couple of lessons we tried to get two more programs besides scratch to work. Since we had three people, we had three different tasks for us to do. Mia helped to work on the actual making and pseudo code for the piano. I helped with mostly the first part of the design thinking, and tried to figure out how to use pygame.
One of the challenges I faced was that I couldn’t download the application of pygame. A complicated process, one that involved a lot of interesting steps, was not possible over the span of the time we had to do the formative. However, I did learn how to code and insert the different music files in if my computer did have the pygame to work off of.
In the small piece of code above, we see a sample of how to import these sound files within the computers code.
Some of the problems when we tried to import the sound file:
1. The sound file that I took form my computer didn’t have any sound when we transferred it, so therefore didn’t play anything
2. The code can only read wav files, in which the file that I used was a mp3 file.
In the two classes we tested out using the raspberry, and also pygame, but mostly tried to figure out how to use arduino. Arduino was the code that Sonia managed to pick up, and it basically was a extension to the makey makey board, which enabled us to be able to have more keys within our piano and make a whole octave. For this project, I tried to work upon making the pygame code. I learnt the code in order to do this, but failed to actually complete this. My computer was not able to download the pygame, and for an entire class I tried to install it onto the dell computer thinking that it could help. I hope for future projects that I can download the pygame into my coding.
In the videos provided below, we are able to see the piano first draft working.
In this photo you can see us working on the piano. By doing this, we had to try the different conductivity things. So we had to try the piano barefoot, and the shoe idea.
The makey makey formative overall was a fun process, and one that allowed us to explore different ways to code. I had a lot of fun collaborating with my group to make this, and it was fun to know that this could potentially be helpful to many children in the future.
Makey Makey is a interesting way to incorporate code, and design into one product. It allows for easy prototyping, and for an intuitive design. The Makey Makey can be used to turn ordinary objects, and small pieces of code, into cool pianos, different games, and even balance boards.
Which programs can you use to program a Makey Makey?
The programs we could use is python, or pygame, but we mostly used scratch for this project. This is because Makey makey was mostly new to all of us, so the scratch let us easily create code, and see the product being made. Furthermore, it showed us that we didn’t need long and complicated code to do cool projects.
Other projects you could create with Makey Makey.
After researching online, I found out that you can create quite a lot with Makey Makey. The first project that Sonia and I made was a keyboard made with just paper, and some connectivity. We then could compose songs out of it. It was shown that we could make controllers for games as well using the Makey makey. I think something interesting we could do next is perhaps making some sort of gym equipment, like a mat that allows us to track activity, similarly like:
Or perhaps a makey makey that could help compose music. So for the down key to be pressd, and it tracks what note it is.
The Makey Makey is an interactive way to use coding to create games and other designs. It allows us to use our imagination and link an actual device or game to our code to see it working. For the first lesson of using the makey makey, it was mostly us just playing around and sort of getting used to the concept of using the makey makey board. It was fascinating because before this we were simply using the code to make something that was a simple game. Now we had extended this to other mediums, and could even connect things outside, and program the makey makey.
This formative exercise built upon the previous lessons, and extended our knowledge of how we could apply the makey makey. This project was to make a timer linked to the balance board, in which would time how long you were on the board for. However, when the board touched the metal, it would stop the timer.
For this exercise, we used scratch to program our makey makey. Scratch is a easy drag and drop sort of code, which allowed us to focus on how the makey makey connected with the code, and how it reacted to it.
These are some of the screenshots of the code that we used. Although slightly different from python, the functions weren’t too hard to use, and it was neat that we could test it first using the little scratch cat first. The logic behind the code was slightly different, and each part was separated instead of as one large block.
We started off with making the timer first. We put the timer into a forever loop, which was broken by the timer to 0 when the downbar was pressed. So to put it into python code, the downbar being pressed was alike to a global function, which stopped every other part of the code, and breaked it.
We attached it to the down bar because we wanted the time to only stop when the balance board was touching on the metal on either side. After, we tested the code, we then attached it to the makey makey. The drawn diagram below is to showcase the connections we put onto the makey makey, and attached to the balance board, which was connected to our computer for the timer.
Some of the things that went well was the connection between the computer and the makey makey. It was pretty intuitive in the way that we had to use it, and all the connections seemed to make sense. I really enjoyed the project because we saw when it worked, and when it didn’t we worked collaboratively to try to solve our problems.
We found some of the parts quite challenging, especially since I have never used scratch before. The programming blocks were different, and we had to do some research before to get some ideas on how to make the code for the balance board. However, after researching more about it, we were able to start the makey makey, and the process as well as the coding got easier from then on out.
So far we have the name input, and the balance board worked. But if we had more time, we would have loved to incorporate the score for the time, and for the computer to save the score. By doing this, it would let the user track their progress, and their highest score.
Here is a video of our balance board code in action:
I tried something different for the video, and sort of summed up the main points of the blog post down below. I did an audio recording above it trying to explain the code, as well as to show how the code works.
Day 2+3 reflection:
Step by step explanation of the code:
varglobal=0
def function_startagain ():
startagain= input (print("Do you want to start the quiz again, press 1 (exit) or 2 (start again)"))
global varglobal
if startagain== "2":
print (funct_game())
if startagain==1:
varglobal==1
The first part of the code was defining the global variables. Global variables are extremely helpful, especially when you want to break the code throughout (so this code can be used in any situation, and it will be able to break the code, and start the game again. It is extremely helpful throughout the game, when someone loses ( as it helps to ask the user whether or not they would like to restart the game.
def funct_game ():
vbeginning= input("This is the international trivia competition. Your categories are as follows"
"\n 1. Animals"
"\n 2. General Trivia")
while vbeginning!= "1" or "2":
if vbeginning == "1":
vstart= input("Are you ready to begin on your topic: Animals")
if vstart=="yes":
print ("Let's get started!")
vquestion1= input ("Starting a little easy. Your first question is, I have four legs but no tail. "
"\n Usually I am heard only at night. What am I? "
"\n Your options are: "
"\n 1. A monkey "
"\n 2. A cat "
"\n 3. A ladybird"
"\n 4. A frog ")
if vquestion1 == "4" :
print ("Good Job! You are correct! ")
vint= (18)
vguess= int(input("Next question is a little bit more challenging."
"\n Your question is How many species of penguins are there?"
"\n the answer is between 10-20"))
This next part is a sample of the code throughout the first part of the game. This part uses multiple if and else statements in order to perform the task at hand. I used this as a basis beginning, before adventuring off to other parts of code. The if and else statements are quite easy to follow, as they simply ask the user to input their answer. If the answer is correct, then there will be the next question
Pros:
This method I found was the easiest to code, and made the most sense in my head. I could understand everything, and was more comfortable with this method.
Cons:
This was not the most effficient method in order to perform the task at hand. There are other methods that I tested out that worked better then this one, so I used this mostly as a foundation, as well as a comparison to other types of the code.
Syntax errors that were faced.
Throughout the code, I actually faced quite a few syntax errors. This was because when doing the game based on if and else statements, the indents got quite messy after a while. It was especially hard because some of the indents were halfway indents, so when trying to line up the else statements, it became really hard.
Another syntax that i faced was definitely making the decision of using if variable != “” or if variable == “” . In some places one worked better then the other, and sometimes there were cases where the other worked and one didn’t. I am still researching into why this occurred, but have made some conclusions that the code was just more sensitive in some places then others.
vguess= int(input("Next question is a little bit more challenging."
"\n Your question is How many species of penguins are there?"
"\n the answer is between 10-20"))
while vguess!= vint:
if vguess > vint:
print("The number is lower")
vguess=int(input("Guess a number frm 10-20"))
if vguess < vint:
print("The number is higher ")
vguess =int(input("Guess a number frm 10-20"))
For this question in the animal section, I knew I wanted to give the user a guessing sort of answer choice instead of multiple choice. It became quite fun in order to solve it , because it was interesting to apply the guess the number game to the summative piece. I suddenly realised that all the code that we have done prior to the summative could actually be incorporated in some manner. Besides using the guess the number game, I also incorporated some of the guess the word game, and used the formative as a check and reference.
The guess the name was used for the last question of the animal section. I thought that it was quite interesting to see how it could be applied to making the user guess the answer instead of multiple choice.
if vquestion6 != "Shadow":
print ("It's something that trails behind you")
vgiveup= input (" Do you want to give up?")
if vgiveup == "no" or "No":
vquestionafterprompt= input ("Try again!"
"\n 1. Shadow"
"\n 2. Sharpie "
"\n 3. Water "
"\n 4. Trick question")
if vquestionafterprompt!="1":
print ("Too bad, you lose")
print(function_startagain())
else:
print ("Good job!You have beaten the quiz! ")
print (function_startagain())
Furthermore, I learnt more about how to use text files. i have never used text files before, so I had to do some prior research before hand to get some ideas on what this would look like:
text_file= open ("write_it.txt","w")
lines= input("What is your name")
if lines=="1":
print ("Hi")
text_file=open ("write_it.txt", "r")
print (text_file.read())
text_file.close()
This is a small piece of code showcasing what a text file would look like. I thought that maybe I could write an entire quiz as a text file and store it there, then use the text file and print it. I would also like to see if i could use it to store the count, as well as their name and age.
Here is the pdf version of my pseudo code, and brain frame. At the start of the game I was skeptical of making this, because I wasn’t exactly sure how and where to start. However, after a few tries, I managed to get started, and everything fell into place.
Use of the brain-frame:
I use the brain-frame to help me to organise all of the material given to me, and to ensure that I am remembering to include everything into my code. It sort of acts as a checklist for everything. I find the brain-frame convenient to use, because it sort of gives me an idea of the layout of everything, as well as some key points that I need to remember throughout. Through making the brain frame, it allowed me to make a skeleton of the entire game at hand, so that I could visualise what exactly needed to be coded.
Brain-frame vs pseudo code:
After making the brain frame, I decided to compare and contrast the advantages of each of the starting templates, and which ones would’ve been more helpful. I personally prefer to use the brain frame, because putting it in order of pseudo code can be quite a large task for me to do, and I feel like I can visualise things better when I have all the things I need to include in a brain frame, and for me to order it in that manner. Through the brain frame, it allowed me to think openly, and move around things in the correct order.
Reflection:
Overall, today’s class went really well, and I learnt a lot about the different ways to make a quiz. I tried multiple different methods to get the hand at both if and else statements, as well as the use of functions. Before this activity, I still wasn’t as comfortable with using the functions, but after, I think I am starting to get used to the entire use. Through this activity, I could also start to see which one of the codes were more effective, and the importance of planning before hand. I also realised that at the beginning I was trying to do too many things at once, which made the entire process just confusing, rather than helpful. I’m excited to start to learn more about text files at home, and apply it next class.
One other thing that I found really helpful, was to keep trying throughout the process, and to try to make sample codes first of the process I want to try out.
def funct_vquestion11 ():
vquestion11 = input ("What's your favorite day?")
if vquestion11== "1" :
print (funct_vquestion12())
def funct_vquestion12 ():
vquestion12= input ("Good job! What's your fav food?")
if vquestion12 == "2":
print (funct_vquestion13())
def funct_vquestion13 ():
vquestion13= input ("Good job! What's the capital of Japan")
def funct_vquestion14 ():
vquestion14= ("1+2=?")
Since I was still not familiar with the function use, I decided to test it out the functions with a small bit of code first. So I tested it out with the code above ( the answers don’t really make sense for the questions, but this was just trial, so I wasn’t concerned about the logic of the question, but more so, the format, and the logic of the code.) There are many ways to apply functions to the code at hand, but I tried to use it by defining all my functions, and relating two questions at a time, and putting that into one large code at the end. I tried different techniques, but this one seemed like it was working the most, and I could logically follow it the best.
My plan for next time:
1. Incorporate the sample function part into the code
2. Incoporate the text file into the code
3. Write more about the text file used
4. productivity and use of time?
Day 2:
Today i worked on getting the text file working, as well as getting the function game to work well. The text file took a long time for me to work out, especially since I have never worked with the text files before. It was a fun challenge to solve all the different errors that I encountered along the way, and it was satisfying to be successful in the end.
Functions game:
For the functions part I tried something different from most of the other codes that I have worked with the functions. For example, in a lot of my previous codes I used the function without anything else, just the function of print. This time, I tried to make the functions related to every other function. So the function 1, would only print if the function before that ( the user input the right answer for the previous function) I had tested with a small piece of code last time, and it worked, so for this part I modelled after the sample code, and tried to make the code for the second part of the game. Some of the errors that I faced was that I couldn’t put the if and else statements all into one function. What I mean by this is that I envisioned one of the functions to have if and else statements throughout, and to define my functions underneath that. However, this didn’t work and jammed up the entire code, so it was better to do it part by part, and to only do it per two functions.
Overall, I think that this way of doing the code was easier and took up less code then the other methods. It seemed to take up the least amount of code, or the same amount as the text file method.
This was the testing part that I modelled after to get the rest of my code to work for this part of the game.
def funct_vquestion12 ():
vquestion12= input ("Good job! What's your fav food?")
if vquestion12 == "2":
print (funct_vquestion13())
def funct_vquestion13 ():
vquestion13= input ("Good job! What's the capital of Japan")
def funct_vquestion14 ():
vquestion14= ("1+2=?")
By using this, I modelled the rest of my code for this part of the game. Basically, I was able to take this small part of code, and follow that example to make the entire second game.
Text files:
For the third game, I used the text files. Text files was something that we haven’t done before, so it was interesting to see how we could use them in the game. Basically text files can be used to store text, instead of writing it out onto lines. It’s easy storage for large pieces of text, that can be called later throughout your code.
For the game that I made, the text files became good to store the entire quiz, and I would call certain lines up for each question. I had some problems here, especially since I hadn’t worked with text files before. I wanted to call a certain amount of lines, and had a long trial and error process in order to try to figure out how to do it. Before this however, I had to learn how to create text files, open them, import them, and the different functions that the text files could provide. Once I found out how to use the text file, (open, read, and write) I then moved onto brainstorming how this could be helpful for the game. I debated on using this for the count function. So the text file would store the score that the user had. I then also realised you could use this text file to store names, but ended up going with the function of creating an entire game through the text file.
How this worked was that the text file was created, and I could write my entire quiz through the text file. Then, in my main code, I could call up certain lines of the text from the text file. For this part I had to use the for i in range function which allowed me to call certain lines of code. This was hard at first to figure out, because I wasn’t using the for loop, and instead used just range. This printed out the code in a very weird way, with \n and all the choices on one line. It was okay, but it didn’t print in the way that I wished it did. So I continued to work on the code, and find a better way to complete the same task.
print ( "Good job! ")
vcounter=vcounter+1
print ("Your score is:",vcounter ,"!")
for i in range (7,14):
print (text_file.readline())
vquestion21 = input ("Input 1,2,3, or 4")
if vquestion21!= "1":
print ("Tough luck! Better luck next time!")
print ("Your final score is:",vcounter ,"!")
print (function_startagain())
Above is a sample part of the code using the text file. I had to research some of the specific commands for text files, which included the read lines function, and calling the text file, and closing it. It was interesting to see how intuitive the code was, and how I could incorporate if and else statements throughout the code as well.
In terms of which code is better, and more efficient (text file, if and else statements, or functions) I believe that the text files or the functions were one of the most efficient pieces of code. The text file definitely proved to be effective, especially since it meant that my code wasn’t going to be filled with lines of text. The functions put everything before hand, and outside of the main part of the code, so inside the actual game function it was only one line of code since all my functions were inter-related. The if and else statements took up the most lines of code, and were the least effective throughout. In order to code the same thing, the functions and text files took up less than half the amount of code, to create the same game.
Testing document:
In order to keep track of all the errors that I made throughout the code, we created something called the testing document. This allowed us to reference previous errors we fixed to solve new errors, and acted like a log of progress as well. This I imagine, will be very helpful in the long run, and can help us with remembering previous errors we have done, and fix them.’
Overall, I feel like the entire project was not only fun, and interesting, but also one that was challenging and at times hard. Comparing it to the formative is very hard, especially since the approach to the code was very different for each one. I was, however, able to reference some of the code that I had previously. I found it hard but fun to incorporate the text files, and feel as if throughout this project I have become more confident with my coding abilities. Furthermore, i feel like the coding language has become more familiar to me, and I can now think and envision what the code would look like.Final Reflection:
Code:
Day 1 code:
varglobal=0
def function_startagain ():
startagain= input (print("Do you want to start the quiz again, press 1 (exit) or 2 (start again)"))
global varglobal
if startagain== "2":
print (funct_game())
if startagain==1:
varglobal==1
#define functions
def funct_vquestion11 ():
vquestion11 = input ("What's your favorite day?")
if vquestion11== "1" :
print (funct_vquestion12())
def funct_vquestion12 ():
vquestion12= input ("Good job! What's your fav food?")
if vquestion12 == "2":
print (funct_vquestion13())
def funct_vquestion13 ():
vquestion13= input ("Good job! What's the capital of Japan")
def funct_vquestion14 ():
vquestion14= ("1+2=?")
def funct_game ():
vbeginning= input("This is the international trivia competition. Your categories are as follows"
"\n 1. Animals"
"\n 2. General Trivia")
while vbeginning!= "1" or "2":
if vbeginning == "1":
vstart= input("Are you ready to begin on your topic: Animals")
if vstart=="yes":
print ("Let's get started!")
vquestion1= input ("Starting a little easy. Your first question is, I have four legs but no tail. "
"\n Usually I am heard only at night. What am I? "
"\n Your options are: "
"\n 1. A monkey "
"\n 2. A cat "
"\n 3. A ladybird"
"\n 4. A frog ")
if vquestion1 == "4" :
print ("Good Job! You are correct! ")
vint= (18)
vguess= int(input("Next question is a little bit more challenging."
"\n Your question is How many species of penguins are there?"
"\n the answer is between 10-20"))
while vguess!= vint:
if vguess > vint:
print("The number is lower")
vguess=int(input("Guess a number frm 10-20"))
if vguess < vint:
print("The number is higher ")
vguess =int(input("Guess a number frm 10-20"))
if vint == vguess:
print("This is the right number! Good job")
vquestion3= input("What jumps when it walks and sits when it stands?"
"\n 1. Kangaroo "
"\n 2. Ladybug "
"\n 3. Dandelion "
"\n 4. Lion ")
if vquestion3=="1":
print ("Good job! You're on a roll!")
vquestion4= input ("I had no fathers, only a grandfather. I shall bear"
"\n no sons, only daughters. What am I? "
"\n 1. Ant "
"\n 2. Bee "
"\n 3. Carpet "
"\n 4. Dolphin")
if vquestion4== "2" :
print("Good job! You are doing well! Only a few more questions!")
vquestion5=input ("What is the easter bunny's favorite type of dance?"
"\n 1. Hip hop"
"\n 2. Any dance"
"\n 3. K-pop"
"\n 4. Canto-pop")
if vquestion5== "1" :
print ("You've almost beaten the quiz!")
vquestion6= input("What part of a bird isn't in the sky and can swim but not get wet?"
"\n the correct answer starts with s, ends with w, and has 6 letters.")
if vquestion6 != "Shadow":
print ("It's something that trails behind you")
vgiveup= input (" Do you want to give up?")
if vgiveup == "no" or "No":
vquestionafterprompt= input ("Try again!"
"\n 1. Shadow"
"\n 2. Sharpie "
"\n 3. Water "
"\n 4. Trick question")
if vquestionafterprompt!="1":
print ("Too bad, you lose")
print(function_startagain())
else:
print ("Good job!You have beaten the quiz! ")
print (function_startagain())
else:
print (" You gave up! Too bad, you lose! ")
print (function_startagain())
else:
print ("Good job!You have beaten the quiz!")
else:
print ("Tough luck, you lose!")
print (function_startagain())
else:
print (" Too bad, you lose! ")
print (function_startagain())
else :
print ("Incorrect! You are out!")
print (function_startagain())
else:
print (function_startagain())
#start of game two
if vbeginning=="2":
print(funct_vquestion11())
print (funct_game())
Day 2 code
varglobal=0
def function_startagain ():
startagain= input (print("Do you want to start the quiz again, press 1 (exit) or 2 (start again)"))
global varglobal
if startagain== "2":
print (funct_game())
if startagain==1:
varglobal==1
#define functions
def funct_vquestion11 ():
vquestion11 = input ("Which number is the only even prime? "
"\n 1. 2 "
"\n 2. 3"
"\n 3. 4 "
"\n 4. 5")
if vquestion11== "1" :
print (funct_vquestion12())
else:
print ("Incorrect! You are out!")
print (function_startagain())
def funct_vquestion12 ():
vquestion12= input ("Good job! Where's french fries from?"
"\n 1. France "
"\n 2. USA "
"\n 3. Germany "
"\n 4. Belgium")
if vquestion12 == "4":
print (funct_vquestion13())
else:
print ("Incorrect! You are out!")
print (function_startagain())
def funct_vquestion13 ():
vquestion13= input ("Good job! What's the capital of Japan"
"\n 1. Tokyo "
"\n 2. Nagasake "
"\n 3. Hokaido"
"\n 4. Germany")
if vquestion13== "1":
print (funct_vquestion14())
else:
print ("Incorrect! You are out!")
print (function_startagain())
def funct_vquestion14 ():
vquestion14= input ("1+2=?"
"\n 1. 3 "
"\n 2. 4"
"\n 3. 5"
"\n 4. 6")
if vquestion14=="1":
print (funct_vquestion15 ())
else:
print ("Incorrect! You are out!")
print (function_startagain())
def funct_vquestion15():
print ("Good job! You did really well!")
print ( function_startagain())
#this should be used for the second part of the game
def funct_game ():
vcounter=0
vbeginning= input("This is the international trivia competition. Your categories are as follows"
"\n 1. Animals"
"\n 2. General Trivia"
"\n 3. Random")
while vbeginning!= "1" or "2" or "3":
if vbeginning == "1":
vstart= input("Are you ready to begin on your topic: Animals press 1 to begin")
if vstart=="1":
print ("Let's get started!")
vquestion1= input ("Starting a little easy. Your first question is, I have four legs but no tail. "
"\n Usually I am heard only at night. What am I? "
"\n Your options are: "
"\n 1. A monkey "
"\n 2. A cat "
"\n 3. A ladybird"
"\n 4. A frog ")
if vquestion1 == "4" :
print ("Good Job! You are correct! ")
vcounter=vcounter+1
print ("Your score now is",vcounter ,"!")
vint= (18)
vguess= int(input("Next question is a little bit more challenging."
"\n Your question is How many species of penguins are there?"
"\n the answer is between 10-20"))
while vguess!= vint:
if vguess > vint:
print("The number is lower")
vguess=int(input("Guess a number frm 10-20"))
if vguess < vint:
print("The number is higher ")
vguess =int(input("Guess a number frm 10-20"))
if vint == vguess:
print("This is the right number! Good job")
vcounter=vcounter+1
print ("Your score now is",vcounter ,"!")
vquestion3= input("What jumps when it walks and sits when it stands?"
"\n 1. Kangaroo "
"\n 2. Ladybug "
"\n 3. Dandelion "
"\n 4. Lion ")
if vquestion3=="1":
print ("Good job! You're on a roll!")
vcounter=vcounter+1
print ("Your score now is",vcounter ,"!")
vquestion4= input ("I had no fathers, only a grandfather. I shall bear"
"\n no sons, only daughters. What am I? "
"\n 1. Ant "
"\n 2. Bee "
"\n 3. Carpet "
"\n 4. Dolphin")
if vquestion4== "2" :
print("Good job! You are doing well! Only a few more questions!")
vquestion5=input ("What is the easter bunny's favorite type of dance?"
"\n 1. Hip hop"
"\n 2. Any dance"
"\n 3. K-pop"
"\n 4. Canto-pop")
vcounter=vcounter+1
print ("Your score now is",vcounter ,"!")
if vquestion5== "1" :
print ("You've almost beaten the quiz!")
vcounter=vcounter+1
print ("Your score now is",vcounter ,"!")
vquestion6= input("What part of a bird isn't in the sky and can swim but not get wet?"
"\n the correct answer starts with s, ends with w, and has 6 letters.")
if vquestion6 != "Shadow":
print ("It's something that trails behind you")
vgiveup= input (" Do you want to give up?")
if vgiveup == "no" or "No":
vquestionafterprompt= input ("Try again!"
"\n 1. Shadow"
"\n 2. Sharpie "
"\n 3. Water "
"\n 4. Trick question")
if vquestionafterprompt!="1":
print ("Too bad, you lose")
print(function_startagain())
else:
print ("Good job!You have beaten the quiz! ")
print ("Your final score is:",vcounter ,"!")
print (function_startagain())
else:
print (" You gave up! Too bad, you lose! ")
print ("Your final score is:",vcounter ,"!")
print (function_startagain())
else:
print ("Good job!You have beaten the quiz!")
print ("Your final score:",vcounter ,"!")
print (function_startagain())
else:
print ("Tough luck, you lose!")
print ("Your final score is:",vcounter ,"!")
print (function_startagain())
else:
print (" Too bad, you lose! ")
print ("Your final score is:",vcounter ,"!")
print (function_startagain())
else :
print ("Incorrect! You are out!")
print ("Your final score is:",vcounter ,"!")
print (function_startagain())
else:
print (function_startagain())
#start of game two
if vbeginning=="2":
print(funct_vquestion11())
if vbeginning =="3":
text_file= open ("write_it.txt1", "r")
for i in range (0,5):
print (text_file.readline())
vquestion20= input ("Input 1, 2, 3, or 4")
if vquestion20 != "1":varglobal=0
def function_startagain ():
startagain= input (print("Do you want to start the quiz again, press 1 (exit) or 2 (start again)"))
global varglobal
if startagain== "2":
print (funct_game())
if startagain==1:
varglobal==1
#define functions
def funct_vquestion11 ():
vquestion11 = input ("Which number is the only even prime? "
"\n 1. 2 "
"\n 2. 3"
"\n 3. 4 "
"\n 4. 5")
if vquestion11== "1" :
print (funct_vquestion12())
else:
print ("Incorrect! You are out!")
print (function_startagain())
def funct_vquestion12 ():
vquestion12= input ("Good job! Where's french fries from?"
"\n 1. France "
"\n 2. USA "
"\n 3. Germany "
"\n 4. Belgium")
if vquestion12 == "4":
print (funct_vquestion13())
else:
print ("Incorrect! You are out!")
print (function_startagain())
def funct_vquestion13 ():
vquestion13= input ("Good job! What's the capital of Japan"
"\n 1. Tokyo "
"\n 2. Nagasake "
"\n 3. Hokaido"
"\n 4. Germany")
if vquestion13== "1":
print (funct_vquestion14())
else:
print ("Incorrect! You are out!")
print (function_startagain())
def funct_vquestion14 ():
vquestion14= input ("1+2=?"
"\n 1. 3 "
"\n 2. 4"
"\n 3. 5"
"\n 4. 6")
if vquestion14=="1":
print (funct_vquestion15 ())
else:
print ("Incorrect! You are out!")
print (function_startagain())
def funct_vquestion15():
print ("Good job! You did really well!")
print ( function_startagain())
#this should be used for the second part of the game
text_file = open ("write_it.txt", "w")
text_file.write = ("You have done really well so far in the game!")
text_file.close ()
text_file= open ("write_it.txt", "r")
print (text_file.read ())
text_file.close
def funct_game ():
vcounter=0
vbeginning= input("This is the international trivia competition. Your categories are as follows"
"\n 1. Animals"
"\n 2. General Trivia"
"\n 3. Random")
while vbeginning!= "1" or "2" or "3":
if vbeginning == "1":
vstart= input("Are you ready to begin on your topic: Animals press 1 to begin")
if vstart=="1":
print ("Let's get started!")
vquestion1= input ("Starting a little easy. Your first question is, I have four legs but no tail. "
"\n Usually I am heard only at night. What am I? "
"\n Your options are: "
"\n 1. A monkey "
"\n 2. A cat "
"\n 3. A ladybird"
"\n 4. A frog ")
if vquestion1 == "4" :
print ("Good Job! You are correct! ")
vcounter=vcounter+1
print ("Your score now is",vcounter ,"!")
vint= (18)
vguess= int(input("Next question is a little bit more challenging."
"\n Your question is How many species of penguins are there?"
"\n the answer is between 10-20"))
while vguess!= vint:
if vguess > vint:
print("The number is lower")
vguess=int(input("Guess a number frm 10-20"))
if vguess < vint:
print("The number is higher ")
vguess =int(input("Guess a number frm 10-20"))
if vint == vguess:
print("This is the right number! Good job")
vcounter=vcounter+1
print ("Your score now is",vcounter ,"!")
vquestion3= input("What jumps when it walks and sits when it stands?"
"\n 1. Kangaroo "
"\n 2. Ladybug "
"\n 3. Dandelion "
"\n 4. Lion ")
if vquestion3=="1":
print ("Good job! You're on a roll!")
vcounter=vcounter+1
print ("Your score now is",vcounter ,"!")
vquestion4= input ("I had no fathers, only a grandfather. I shall bear"
"\n no sons, only daughters. What am I? "
"\n 1. Ant "
"\n 2. Bee "
"\n 3. Carpet "
"\n 4. Dolphin")
if vquestion4== "2" :
print("Good job! You are doing well! Only a few more questions!")
vquestion5=input ("What is the easter bunny's favorite type of dance?"
"\n 1. Hip hop"
"\n 2. Any dance"
"\n 3. K-pop"
"\n 4. Canto-pop")
vcounter=vcounter+1
print ("Your score now is",vcounter ,"!")
if vquestion5== "1" :
print ("You've almost beaten the quiz!")
vcounter=vcounter+1
print ("Your score now is",vcounter ,"!")
vquestion6= input("What part of a bird isn't in the sky and can swim but not get wet?"
"\n the correct answer starts with s, ends with w, and has 6 letters.")
if vquestion6 != "Shadow":
print ("It's something that trails behind you")
vgiveup= input (" Do you want to give up?")
if vgiveup == "no" or "No":
vquestionafterprompt= input ("Try again!"
"\n 1. Shadow"
"\n 2. Sharpie "
"\n 3. Water "
"\n 4. Trick question")
if vquestionafterprompt!="1":
print ("Too bad, you lose")
print(function_startagain())
else:
print ("Good job!You have beaten the quiz! ")
print ("Your final score is:",vcounter ,"!")
print (function_startagain())
else:
print (" You gave up! Too bad, you lose! ")
print ("Your final score is:",vcounter ,"!")
print (function_startagain())
else:
print ("Good job!You have beaten the quiz!")
print ("Your final score:",vcounter ,"!")
print (function_startagain())
else:
print ("Tough luck, you lose!")
print ("Your final score is:",vcounter ,"!")
print (function_startagain())
else:
print (" Too bad, you lose! ")
print ("Your final score is:",vcounter ,"!")
print (function_startagain())
else :
print ("Incorrect! You are out!")
print ("Your final score is:",vcounter ,"!")
print (function_startagain())
else:
print (function_startagain())
#start of game two
if vbeginning=="2":
print(funct_vquestion11())
if vbeginning =="3":
text_file= open ("write_it.txt1", "r")
for i in range (0,5):
print (text_file.readline())
vquestion20= input ("Input 1, 2, 3, or 4")
if vquestion20 != "1":
print ("Incorrect! You are out!")
print ("Your final score is:",vcounter ,"!")
print (function_startagain())
else:
print ( "Good job! ")
vcounter=vcounter+1
print ("Your score is:",vcounter ,"!")
for i in range (7,14):
print (text_file.readline())
vquestion21 = input ("Input 1,2,3, or 4")
if vquestion21!= "1":
print ("Tough luck! Better luck next time!")
print ("Your final score is:",vcounter ,"!")
print (function_startagain())
else:
print ("Good job!")
vcounter=vcounter+1
print ("Your score now is",vcounter ,"!")
for i in range (15,21):
print (text_file.readline())
vquestion23= input ("Input 1,2,3, or 4")
if vquestion23!= "4":
print ("Better luck next time! ")
print ("Your final score is:",vcounter ,"!")
print (function_startagain())
else:
print ("Good Job!")
vcounter=vcounter+1
print ("Your score now is",vcounter ,"!")
for i in range (22,28):
print (text_file.readline())
vquestion24= input ("Input 1,2,3, or 4")
if vquestion24!= "1":
print ("Better luck next time! ")
print ("Your score is:",vcounter ,"!")
print (function_startagain())
else:
print ("Good Job!")
vcounter=vcounter+1
print (vcounter)
break
text_file.close()
print (funct_game())
Citations:
Ivoz. “OpenTechSchool.” OpenTechSchool – Working With Text Files. OpenTechSchool, 2013-2014. Web. 22 Nov. 2016.
Pythonforbeginners. “Reading and Writing Files in Python.” Python For Beginners. TreeHouse, 8 July 2013. Web. 22 Nov. 2016.
Stack Overflow. “Python – Read File from and to Specific Lines of Text.” Stack Overflow. StackExchange, 16 Sept. 2011. Web. 22 Nov. 2016.
Mind map At the very beginning of our project, we made a mind map in order to showcase the different aspects we were thinking of including. By making these aspects it helped us to visualise the different things that happened in the game, and some of the genera outlines of the game.
Pseudo Code: This was our pseudo code for the adventure game. We made the pseudo code in order to help us manage the actual coding. Whilst creating the pseudo code, I didn’t think that it would help. It was only when I had started coding did i realise the pseudo code was good reference for the code, especially at times where the coding language is hard to understand.
Aim of the game: To allow the user to continue throughout their story Ask users to input their name Ask users to input their age
Print: You are stuck on a deserted island, known to be filled with mysteries of both the past and present. You wake up on the beach of the island with a chill up your back, and a mysterious feeling that you are being followed. You brush yourself off, and look around the island. Your stomach is growling, but you try to think clearly about your next options. You scratch your options into the sand: Indent: 1. Go to the faraway abandoned hut Indent: 2. Go into the forest Indent: 3. Search for people. Input: Which option do you choose? Which one holds your fate?
Faraway Hut: Print: After long contemplation, and seeing dark clouds hovering over the island, bursting to rain, you decide to go to the abandoned hut and seek shelter. You enter the hut, and notice that it looks empty. Input: Explore the house, or hide in one of the rooms and seek refuge just for the night?
Explore the house Print: You start to explore the rooms of the house, and notice a lot of guns hung up on the walls. After exploring all the rooms, and notice that the hut is empty, you finally start to relax. You sit in one of the lounge chairs in the main part of the hut, but the wind blares a chilly breath of air, and you shiver. You walk over to the window, and try to close it, but you aren’t tall enough. You reach on your tippy-toes and try to close the latch. Whilst doing it, you fall out the window, into a pit of thorns. The thorns dig deep into your skin, and you bleed to death. You die. The End.
Hide in one of the rooms Print: You take refuge in the kitchen and hear a man walk down the steps of the hut. Input: You hide again, or you greet him
If user inputs: You hide again
Then print: You hide, and go to the backyard of his hut. But you walk into a pit of thorns, and bleed to death. You die. The End 2. If the user inputs: Greet the man Then print: the man greets you with a smile and hugs you- a weird embrace especially since you have never met him. However, during the embrace, you still don’t completely trust him, and feel his pocket. A gun shaped indent. Do you take the gun, or do you run for you life If input is: Take the gun Print: When you take the gun you feel victorious. But as you look around, and see human heads hanging as prizes on the walls, you paralyse. You look around, suddenly forgetting that you just stole a gun from a madman. As you look at the room, you realise that the entire room not only has bloody human heads but also guns. Not just one gun, but many guns. Too many for your liking. But before you know it, the man shoot you five times. You die. The End. If input is: Run for your life. Print: You try to run, but realise this was all a dream. The hut had been latched close since you arrived. The man was watching you since you came on the island. He chuckles softly, and whispers like the madman he is. Tears streaming down your face, you see him take a knife, and say something about adding you to his pretty collection. You stare around the room, and realise all the monuments are dead humans. You have a panic attack, and he kills you when you have fainted. The end, you die.
Print: Go into the Forest:Print: You get lost. You are scared, and darkness is falling. Suddenly, you fall into a pit with poisonous vipers. You die. The End.
Search for People: Print: You pick up a conch shell on the beach. Suddenly, you hear someone calling for you. Input: Do you go towards the sound (1), or ignore the call (2)? If Input is 2, Print: You try to live alone, but you cannot manage to suffice on your own. You eventually die from starvation. If input is 1, Print: You find a chubby boy with thick spectacles stuck in brambles. You help him out, and discover his name is PIggy. He sees that you have a conch shell, and asks if you know how to blow it. You don’t, and he offers to teach you. Input: Accept (1) or decline (2)? If input is 1, Print: You learn to blow the conch, and when you finally succeed in making a sound, the deep note resonates through the entire island. Over the course of one hour, boys ranging from 6 year olds to 19 year olds stream out of the forest, until eventually an entire choir of boys come out, with a redhead leading the way. All the boys want you to become their leader, but the redhead, Jack, seems to want to be leader too. Input: Do you let Jack share leadership with you (1), or be a dictator (2)? If input is 1, Print: You guys split the leadership and he and his choir helps the group hunt, while you and the others help create a signal fire to get rescued. Your leadership seems harmonious and works really well, living long enough to witness a plane see your signal fire and rescue you. You get rescued and return home safely. Congratulations, you’ve survived! If input is 2, Print: Jack gets jealous and rebels. He and his hunters become more and more uncivilised until they become savages and split from the group. Eventually, out of revenge, Jack and his choir come back and convince your crew that you are a misleading chief. Your group and Jack’s group both set out and rip you apart, until all your remains are washed out into the sea. The End. If input is 2, Print: You and Piggy decide to stay and create a fire, but a wild boar stumbles towards your source of light. Input: Do you fight (1) or flee(2)? If input is 1, Print: You both die trying to kill the wild boar. The End. If is 2, Print: You run away, but a herd of pigs corner you, separating you from Piggy. You get gored to death. The End.
The code, and some of the syntax errors we overcame:
Some of the syntax errors we faced:
One of the problems that we faced was getting the program to loop on itself. So once a person dies, the game will ask the user to restart or to quit the program. At first we weren’t sure on how we wanted to carry out this program. So after some research and talking to Mr. Lin, we found out that the best way to do this was to create a global function. By creating the global function it allows us to call it up, and break the function at any time to ask the user to restart.
varglobal=0
def function_startagain ():
startagain= input (print("Do you want to start the game again, press 1 (exit) or 2 (start again)"))
global varglobal
if startagain== "2":
print (funct_game())
if startagain==1:
varglobal==1
This shows the function that can be called up by throughout the entire program to be able to quit the program.
Another syntax error that we faced was the combination of the two programs. In order to save time Sonia and I split up the code so that we could be more efficient with time. However, when we got to combining the codes together, we realised that we used two very different approaches to making the code, and therefore there was some things that we had to fix. For example, she used mostly functions and simply called up the function when she needed to use it. I took a different approach to this, and tried to make the program based on mainly if and else statements, combined with a while statement, and incased within a function. When we combined the two codes, we then managed to learn about different ways to solve the same problem, and learned the different perspectives.
Another syntax error that we faced was the different indentations. The indentations were a problem made that were at times hard to fix. Sometimes there were the indent errors due to the combination of the two codes, but we managed to go through each line and solve the errors that were presented. The only problem with indent errors was that I had to remind myself when I had to indent the breaks.
Another syntax error I faced was one that dealt with the functions, and if and else statements. Since at times there were if and else statements. These if and else statements were hard especially if you had a statement like this inside another one, or a while statement. For example, if we had the user choose between two options, and one of those options led to another question, an if and else statement had to be used within the statement that was already there. This led to many problems with not only indentations but also aspects of the code.
Interpretation of the code:
varglobal=0
def function_startagain ():
startagain= input (print("Do you want to start the game again, press 1 (exit) or 2 (start again)"))
global varglobal
if startagain== "2":
print (funct_game())
if startagain==1:
varglobal==1
def function_v3a12():
v3a12 = input(print("""Do you fight (1) or flee(2)? """));
if v3a12 == "1":
print("""You both die trying to kill the wild boar. The End. """);
if v3a12 == "2":
print("""You run away, but a herd of pigs corner you, separating you from Piggy. You get gored to death. The End. """)
def function_v3a11():
v3a11 = input(print("""Do you let Jack share leadership with you (1), or be a dictator (2)?"""))
if v3a11 == "1":
print("""You guys split the leadership and he and his choir helps the group hunt, while you and the others help create a signal fire to get rescued. Your leadership seems harmonious and works really well, living long enough to witness a plane see your signal fire and rescue you. You get rescued and return home safely. Congratulations, you’ve survived!""")
if v3a11 == "2":
print("""Jack gets jealous and rebels. He and his hunters become more and more uncivilised until they become savages and split from the group. Eventually, out of revenge, Jack and his choir come back and convince your crew that you are a misleading chief. Your group and Jack’s group both set out and rip you apart, until all your remains are washed out into the sea. The End.""");
def function_v3a1():
v3a1 = input(print("""Accept (1) or decline (2)? """))
if v3a1 == "1":
print("""You learn to blow the conch, and when you finally succeed in making a sound, the deep note resonates through the entire island. Over the course of one hour, boys ranging from 6 year olds to 19 year olds stream out of the forest, until eventually an entire choir of boys come out, with a redhead leading the way. All the boys want you to become their leader, but the redhead, Jack, seems to want to be leader too. """);
print(function_v3a11())
if v3a1 == "2":
print("""You and Piggy decide to stay and create a fire, but a wild boar stumbles towards your source of light. """);
print(function_v3a12())
In this first part it was where we defined all the variables before we managed to use them. This is where the pseudo code came in handy, because we knew exactly what needed to be in a variable before we started the game. By already knowing what we wanted to store in the variable, it allowed us to create those variables first, and move into the rest of the code without any problems.
def funct_game():
vBeginning= input("You are stuck on a deserted island, "
"known to be filled with mysteries of both "
"the past and present. You wake up on the beach "
"of the island with a chill up your back, and a mysterious "
"feeling that you are being followed. You brush yourself off,"
" and look around the island. Your stomach is growling, but y"
"ou try to think clearly about your next options. You scratch "
"your options into the sand:"
"\n" " 1. Go to the faraway abandoned hut"
"\n" " 2. Go into the forest "
"\n" " 3. Search for people.")
The next part of the code was actually starting the game. In order to do this we had to put everything into a function of its own, so that we could call up the function and print it. This means that it sort of makes all the main code into one piece (which would be helpful if this was one selection out of many games)
while vBeginning != "1" or "2" or "3":
if vBeginning == "1":
print (" After long contemplation, "
" seeing dark clouds hovering over "
"the island, bursting to rain, you decide to go "
"to the abandoned hut and seek shelter. You enter the "
"hut, and notice that it looks empty.")
vhut= input ("Explore the house (1), or hide in one "
"of the rooms and seek refuge just for the night? (2) ")
if vhut== "2":
print ("You take refuge in the kitchen and hear a man walk down the "
"steps of the hut.")
vhide= input("Do you greet the man(1), or do you continue to hide.(2)")
if vhide == "2":
print ("You hide, and go to the backyard of his hut. But you walk into a pit of thorns, and bleed to death. You die. The End ")
print (function_startagain())
break
else:
print("The man greets you with a smile and hugs you- a weird embrace especially since you have never met him. However, during the embrace, you still don’t completely trust him, and feel his pocket. A gun shaped indent. ")
vgun=input ("Do you take the gun (1), or do you run for your life (2)")
if vgun == "2":
print (" You try to run, but realise this was all a dream. The hut had been latched close since you arrived. The man was watching you since you came on the island. "
"He chuckles softly, and whispers like the madman he is. Tears streaming down your face, you see him take a knife, and say something about adding you to his pretty collection. "
"You stare around the room, and realise all the monuments are dead humans. You have a panic attack, and he kills you when you have fainted. The end, you die.")
print (function_startagain())
break
else:
print ("When you take the gun you feel victorious. But as you look around, and see human heads hanging as prizes on the walls, you paralyse. "
"You look around, suddenly forgetting that you just stole a gun from a madman. As you look at the room, you realise that the entire room not only has bloody "
"human heads but also guns. Not just one gun, but many guns. Too many for your liking. But before you know it, the man shoot you five times. You die. The End.")
print (function_startagain())
break
This part of the code was the part that I tried to code, but not all of it ( just majority to try to explain) Through this part, I made all the different options into inputs, and for the input answer to be in a true or false ( if this equals to something, then an action will be followed) Once I got the hang of doing this, I completed the code with the same use of different if and else statements. I put the entire code into a while loop. This is to ensure the user will click 1 2 or 3 in the beginning of the game ( and if they don’t then the computer will simply keep asking them for it. As you can see at the end of the code, a break and a print ( function_startagain ()) is used. This is two things. The first is that when you die, the program breaks, and will ask/print the function of restarting the code explained earlier.
if vBeginning == "2":
print("""You get lost. You are scared, and darkness is falling. Suddenly, you fall into a pit with poisonous vipers. You die. The End.""")
print (function_startagain())
break
elif vBeginning == "3":
print("""You pick up a conch shell on the beach. Suddenly, you hear someone calling for you. """)
v3a = input("""Do you go towards the sound (1), or ignore the call (2)?""")
while v3a != "1" or "2":
if v3a == "1":
print("""You find a chubby boy with thick spectacles stuck in brambles. You help him out, and discover his name is PIggy. He sees that you have a conch shell, and asks if you know how to blow it. You don’t, and he offers to teach you. """)
print(function_v3a1())
break
elif v3a == "2":
print("You try to live alone, but you cannot manage to suffice on your own. You eventually die from starvation. ")
print (function_startagain())
break
For Sonia’s part of the code, she started by defining all the functions first, and in the main code simply called up the functions when needed. This seems like less code, and the more efficient way to do this code, but I feel as if it could’ve gotten quite confusing with the functions and calling them up if they were questions that could’ve been simply inputs.
Lists:
fruitList = ["apple", "orange", "banana", "grape"," tomato", "mango"]
print (fruitList [1])
#by printing the string, we can also add in other brackets a number, to print one from the list
#concatenation, adds the number lists together
numberList1 = [1,2,3]
numberList2 = [6,7,8]
numberList3= numberList1 + numberList2
print (numberList3)
#doing the same thing, in fact once you get the variable defined, you don't have to write the list again.
numberList4 = (numberList2 [1])*(numberList2[2])
print ( "\n" ,numberList4, "\n" )
To start off the lists we began with making the list itself. In order to create a list you have to use the square brackets, and name the variable. Lists are helpful for many things, especially when you want to call different parts of a list ( you then don’t have to keep defining variables, as its all in the list) I also imagine this to be helpful for data collection, and when you have lists of numbers. After making the list itself, we started to add and do different things with our lists, and combinations with the list that we have gotten. So for example, if we wanted to print the list, but we only wanted to print certain parts of the list ( like the first thing in our list, in this case was a fruit), we could use the position of the word in our list, and the computer would print that after we define this. Furthermore, we also did some refreshing on the indentations. This indenting will definitely come in handy for our choose your own adventure game, to make it look more professional.
#slicing, you can use this:
#Slices a phrase, is the starting point and the last number is the ending point.
#If these are left blank then python assumes that the start position is the beginning of the list, and the end of the list.
print (fruitList[2:5])
print (fruitList [:4])
print (fruitList [5:])
Another fun thing we can do with our lists, is that we can slice the list. This means we can print maybe only a selected amount of the list given, or to only print part of the list. Slicing can also help with the creation of substrings.
fruitList [1] = "Kiwi" #changes the position one fruit to Kiwi Edits the list
print (fruitList)
Furthermore, in the list, we can also choose to change certain parts of the list. This means that throughout the code, you can then change certain parts of your lists at different positions.
Another concept we learned was creating lists within lists. So this means you have multiple lists within the list itself. You can also call up different parts of the list, since there are multiple different parts ( you can choose to call the first part of the second part of the same list)
inventoryList = ["sword","armour","shield","healing potion"]
print ( inventoryList )
inventoryList.sort () #inserts it in the middle #sort, makes it sort
print (inventoryList)
Furthermore, you can also choose to sort different lists. This makes the list into alphabetical order.
#list count - how many times the element appears on the list
#list extend,
#list.pop #removes an element from the list
v_fruit= fruitList.pop ()
print (fruitList)
print (v_fruit ) #this helps show what we have removed
v_fruit1= fruitList.pop (0)
print (v_fruit1) #this is to check that it worked
fruitList.reverse ()
print (fruitList)
Another trick we learned today was list count. This counted how many times a certain element appeared on the list. There was also list extend, which helps to combine two lists into one larger list. Furthermore, the list.pop can be used to remove certain aspects of the list. We also reviewed concepts like length, in which helps calculate the length of the element, and the minimum and maximum function. Reflection: Today in class we learnt about how to make lists, and different functions that we can do with the lists, such as how to sort the list, and other helpful tips and tricks. We started to then apply these list functions, as well as inputs into a game, and a brain frame, to make a choose your own adventure game. The brain frame was really helpful in order to sort of map out what we wanted to do with our game, and what direction we were headed for it. After creating the brain frame, we were then able to create our pseudo code with a clearer message in mind. Overall, i really enjoyed the choose your own adventure, as it helped us incorporate some of our concepts, and creativity into a short game that might actually be fun to play.
fruitList = ["apple", "orange", "banana", "grape"," tomato", "mango"]
print (fruitList [1])
#by printing the string, we can also add in other brackets a number, to print one from the list
#concatenation, adds the number lists together
numberList1 = [1,2,3]
numberList2 = [6,7,8]
numberList3= numberList1 + numberList2
print (numberList3)
#doing the same thing, in fact once you get the variable defined, you don't have to write the list again.
numberList4 = (numberList2 [1])*(numberList2[2])
print ( "\n" ,numberList4, "\n" )
#slicing, you can use this:
#Slices a phrase, is the starting point and the last number is the ending point.
#If these are left blank then python assumes that the start position is the beginning of the list, and the end of the list.
print (fruitList[2:5])
print (fruitList [:4])
print (fruitList [5:])
#this idea of slicing is taking a list, and only commanding part of it to do something
fruitList [1] = "Kiwi" #changes the position one fruit to Kiwi Edits the list
print (fruitList)
olympicList= (["Beijing", 2010],["London", 2012],["Rio", 2016])
print (olympicList)
print (olympicList [1])
print (olympicList [1][0])
#append list methods, grab things
inventoryList = ["sword","armour","shield","healing potion"]
print ( inventoryList )
inventoryList.sort () #inserts it in the middle #sort, makes it sort
print (inventoryList)
#list count - how many times the element appears on the list
#list extend,
#list.pop #removes an element from the list
v_fruit= fruitList.pop ()
print (fruitList)
print (v_fruit ) #this helps show what we have removed
v_fruit1= fruitList.pop (0)
print (v_fruit1) #this is to check that it worked
fruitList.reverse ()
print (fruitList)
v_index = fruitList.index ("banana") #position of banana in the List
print (v_index) #prints out wher ethe banana is in the list
print (fruitList)
print (len(fruitList))
print ( "apple" in fruitList)
print (fruitList)
print (min(fruitList))
#minimum of the list
print (fruitList)
print (max(fruitList))
The code for the game:
varglobal=0
def function_startagain ():
startagain= input (print("Do you want to start the game again, press 1 (exit) or 2 (start again)"))
global varglobal
if startagain== "2":
print (funct_game())
if startagain==1:
varglobal==1
def function_v3a12():
v3a12 = input(print("""Do you fight (1) or flee(2)? """));
if v3a12 == "1":
print("""You both die trying to kill the wild boar. The End. """);
if v3a12 == "2":
print("""You run away, but a herd of pigs corner you, separating you from Piggy. You get gored to death. The End. """)
def function_v3a11():
v3a11 = input(print("""Do you let Jack share leadership with you (1), or be a dictator (2)?"""))
if v3a11 == "1":
print("""You guys split the leadership and he and his choir helps the group hunt, while you and the others help create a signal fire to get rescued. Your leadership seems harmonious and works really well, living long enough to witness a plane see your signal fire and rescue you. You get rescued and return home safely. Congratulations, you’ve survived!""")
if v3a11 == "2":
print("""Jack gets jealous and rebels. He and his hunters become more and more uncivilised until they become savages and split from the group. Eventually, out of revenge, Jack and his choir come back and convince your crew that you are a misleading chief. Your group and Jack’s group both set out and rip you apart, until all your remains are washed out into the sea. The End.""");
def function_v3a1():
v3a1 = input(print("""Accept (1) or decline (2)? """))
if v3a1 == "1":
print("""You learn to blow the conch, and when you finally succeed in making a sound, the deep note resonates through the entire island. Over the course of one hour, boys ranging from 6 year olds to 19 year olds stream out of the forest, until eventually an entire choir of boys come out, with a redhead leading the way. All the boys want you to become their leader, but the redhead, Jack, seems to want to be leader too. """);
print(function_v3a11())
if v3a1 == "2":
print("""You and Piggy decide to stay and create a fire, but a wild boar stumbles towards your source of light. """);
print(function_v3a12())
def funct_game():
vBeginning= input("You are stuck on a deserted island, "
"known to be filled with mysteries of both "
"the past and present. You wake up on the beach "
"of the island with a chill up your back, and a mysterious "
"feeling that you are being followed. You brush yourself off,"
" and look around the island. Your stomach is growling, but y"
"ou try to think clearly about your next options. You scratch "
"your options into the sand:"
"\n" " 1. Go to the faraway abandoned hut"
"\n" " 2. Go into the forest "
"\n" " 3. Search for people.")
while vBeginning != "1" or "2" or "3":
if vBeginning == "1":
print (" After long contemplation, "
" seeing dark clouds hovering over "
"the island, bursting to rain, you decide to go "
"to the abandoned hut and seek shelter. You enter the "
"hut, and notice that it looks empty.")
vhut= input ("Explore the house (1), or hide in one "
"of the rooms and seek refuge just for the night? (2) ")
if vhut== "2":
print ("You take refuge in the kitchen and hear a man walk down the "
"steps of the hut.")
vhide= input("Do you greet the man(1), or do you continue to hide.(2)")
if vhide == "2":
print ("You hide, and go to the backyard of his hut. But you walk into a pit of thorns, and bleed to death. You die. The End ")
print (function_startagain())
break
else:
print("The man greets you with a smile and hugs you- a weird embrace especially since you have never met him. However, during the embrace, you still don’t completely trust him, and feel his pocket. A gun shaped indent. ")
vgun=input ("Do you take the gun (1), or do you run for your life (2)")
if vgun == "2":
print (" You try to run, but realise this was all a dream. The hut had been latched close since you arrived. The man was watching you since you came on the island. "
"He chuckles softly, and whispers like the madman he is. Tears streaming down your face, you see him take a knife, and say something about adding you to his pretty collection. "
"You stare around the room, and realise all the monuments are dead humans. You have a panic attack, and he kills you when you have fainted. The end, you die.")
print (function_startagain())
break
else:
print ("When you take the gun you feel victorious. But as you look around, and see human heads hanging as prizes on the walls, you paralyse. "
"You look around, suddenly forgetting that you just stole a gun from a madman. As you look at the room, you realise that the entire room not only has bloody "
"human heads but also guns. Not just one gun, but many guns. Too many for your liking. But before you know it, the man shoot you five times. You die. The End.")
print (function_startagain())
break
else:
print ("You start to explore the rooms of the house, "
"and notice a lot of guns hung up on the walls. "
"After exploring all the rooms, and notice that the "
"hut is empty, you finally start to relax. You sit in "
"one of the lounge chairs in the main part of the hut, "
"but the wind blares a chilly breath of air, and you shiver. "
"You walk over to the window, and try to close it, but you aren’t "
"tall enough. You reach on your tippy-toes and try to close the "
"latch. Whilst doing it, you fall out the window, into a pit of "
"thorns. The thorns dig deep into your skin, and you bleed to "
"death. You die. The End.")
print (function_startagain())
break
if vBeginning == "2":
print("""You get lost. You are scared, and darkness is falling. Suddenly, you fall into a pit with poisonous vipers. You die. The End.""")
print (function_startagain())
break
elif vBeginning == "3":
print("""You pick up a conch shell on the beach. Suddenly, you hear someone calling for you. """)
v3a = input("""Do you go towards the sound (1), or ignore the call (2)?""")
while v3a != "1" or "2":
if v3a == "1":
print("""You find a chubby boy with thick spectacles stuck in brambles. You help him out, and discover his name is PIggy. He sees that you have a conch shell, and asks if you know how to blow it. You don’t, and he offers to teach you. """)
print(function_v3a1())
break
elif v3a == "2":
print("You try to live alone, but you cannot manage to suffice on your own. You eventually die from starvation. ")
print (function_startagain())
break
break
print (funct_game())
The benefits of functions are endless, and they can help with many different aspects. The first is that it allows you to repeat lists endlessly. They are required to organise, to reuse code, and to perform single, related action. Functions are used to high degree of repeating. Furthermore, it is also possible to create your own functions.
Defining a function: Functions can be defined with the keyword def, followed by the function name and parentheses. This can later be called up to print, or to do other things, and be repeated as well. However, defining a function only gives it a name, but it’s when you put something into the parentheses does the function have a use. This function then can be used to print. By creating functions, you can use it at any time, at any place, and saves time in terms of you don’t have to keep telling the computer what to do over and over again. Functions come either premade, or you can define your own functions. The pre-made functions can then be used by simply “calling” the function.
def f_sum (int1,int2):
"""this function will add numbers"""
return int1 + int2
#main program
vTotal= f_sum (10,15)
print ("the total is: ", vTotal)
The function is useless without being called. But once you call it, you can print it, and define the function as well.
Start of the Chocoltae Machine Challenge.
The chocolate machine challenge was a really interesting task, and enabled us to put into action some of the things we learnt in previous classes, as well as today. It was interesting to see how we could create code that could actually be used in the real world. Although it is simplistic to many people, it feels accomplishing to know that we are actually at a stage of coding where we can make solutions to real life problems. The chocolate machine challenge was where the machine calculates how much change is received by the person paying. We all started off with making a basic code and adding to it as we continued. I faced problems where we tried to make the code understand that when the given amount of money is less than the needed amount, then the code writes something. We are still working on this part.
For our machine, the next steps is trying to make the code have some sort of function included. Since functions are quite new to everybody, we were all skeptical of using it. I think next time, if we continued to work on the chocolate machine,we could definitely try to incorporate more functions into our machine.
Reflection: Overall I really enjoyed today’s class, and think that it was really beneficial. We learned about the uses of functions, and how we can apply it to real situations. It is also interesting to see how all the code we have learnt so far can be used to create simple solutions to problems that may actually occur in real life.
#functions are significant in many ways
# Functions can reduce our program code significantly by putting repeat code into a function
#modules
# Calculations and logical things you have to do--> the better solution is to write a function. You can
# make functions to have infinitely repeats of something.
def f_sum ( int1, int2):
"""This function will add """
#learn how to print on separate lines
# create your own multiple line message here:
print ("""
HI!
""")
def i2P_intro():
print ("""
HI!
""")
print (i2P_intro())
#what a function does #functions must begin with a letter and not contain spaces
def f_sum (int1,int2):
"""this function will add numbers"""
return int1 + int2
#main program
vTotal= f_sum (10,15)
print ("the total is: ", vTotal)
# prints the total amount of the integers given
#the functions are stored at the top. I needs to store the program first, then make the input underneath, and do something with the variable
#Set the variables first
#Why is there a none at the beginning ?
# this is because the function is not yet used.
#returning values
def f_print_largest (int1, int2):
""""This function will print the largest integer"""
if int1 > int2:
print (int1, "is the largest")
if int1 < int2:
print ( int2 ," is the largest")
if int1 == int2 :
print ( "both numbers are" ,int1, "they are equal")
#now it is returning, if it is equal the return, the largest of two integers"
def f_larger (int1, int2 ):
"""This function will return the largest of two integers"""
if int1 >= int2:
return int1
else:
return int2
x=12
y=7
z=79
print(f_larger(f_larger(x,y),z))
#int1 = input (" Choose a number ")
int2 = input ( "Choose a number")
f_print_largest(int1,int2)
print ( f_print_largest)
#main program
#enter the price of the chocolate bar in HKD ( 16.90 = $16.90)
price= 16.90
print ("The price of a chocolate bar $16.90")
vcash= float ( input ("How much are you going to pay?"))
vinput = ("please pay again ")
Cashdue= int(vcash) -price
print ( "You change is ", Cashdue,"dollars ")
while vcash != price:
if vcash > price:
print ( "You change is ", Cashdue,"dollars ")
if vcash < price:
print (" Please pay", price)
In addition: ( this is what we learned in class the next lesson) In this lesson we not only finished our candy machine game,
but also learned more about functions and their different applications.
# def f_ask_yes_no (question):
# """"Ask a Yes or No question"""
# vResponse= None
# while vResponse not in ("yes", "no"):
# vResponse= input (question).lower()
# return vResponse
#
# vQuestion= " Would you like a Mars Bar? "
# vAnswer= f_ask_yes_no(vQuestion )
# if vAnswer =="yes":
# print ( "here is a Mars Bar, I hope you enjoy it")
# if vAnswer== "no":
# print ( "No Mars Bar for you ")
#
#
# def menu (question):
# #
# #
# # def print_menu(): ## Your menu design here
# # print 30 * "-" , "MENU" , 30 * "-"
# # print "1. Menu Option 1"
# # print "2. Menu Option 2"
# # print "3. Menu Option 3"
# # print "4. Menu Option 4"
# # print "5. Exit"
# # print 67 * "-"
# #
# # loop=True
# #
# # while loop: ## While loop which will keep going until loop = False
# # print_menu() ## Displays menu
# # choice = input("Enter your choice [1-5]: ")
# #
# # if choice==1:
# # print "Menu 1 has been selected"
# # ## You can add your code or functions here
# # elif choice==2:
# # print "Menu 2 has been selected"
# # ## You can add your code or functions here
# # elif choice==3:
# # print "Menu 3 has been selected"
# # ## You can add your code or functions here
# # elif choice==4:
# # print "Menu 4 has been selected"
# # ## You can add your code or functions here
# # elif choice==5:
# # print "Menu 5 has been selected"
# # ## You can add your code or functions here
# # loop=False # This will make the while loop to end as not value of loop is set to False
# # else:
# # # Any integer inputs other than values 1-5 we print an error message
# # raw_input("Wrong option selection. Enter any key to try again..")
#
vChoice= None
while vChoice != "0":
print (
"""
Menu Choice
0- Exit
1- Item 1
2- Item 2
3- Item 3
4- Item 4
"""
)
vChoice =input ("Choice:")
print ()
#exit
if vChoice == "0":
print ("Good-bye")
#Choice 1
elif vChoice =="1":
print ( "Choose Item 1 ")
#Choice 2
elif vChoice =="2":
print ( "Choose Item 2 ")
#Choice 3
elif vChoice =="3":
print ( "Choose Item 3 ")
#Choice 4
elif vChoice =="4":
print ( "Choose Item 4 ")
else:
print ("Your choice is invalid")