programming concepts | Reliable Papers

Semester 1, 2021 CSP1150 Assignment 2 Page 1Programming Principles (CSP1150)Assignment 2: Individual programming project (“Would You Rather” Program)Assignment Marks: Marked out of 30, worth 30% of unitDue Date: 31 May 2021, 9:00AMBackground InformationThis assignment tests your understanding of and ability to apply the programming concepts we havecovered throughout the unit. The concepts covered in the second half of the unit build upon thefundamentals covered in the first half of the unit.Assignment OverviewThis assignment is themed around the conversational party game “Would You Rather”, in whichpeople are asked to choose between two options in a hypothetical scenario. The options should besimilar in nature and hard to choose between – either both desirable, both undesirable, or both mixed.Some example questions include “Would you rather be invisible, or be able to fly?”, “Would you ratherbe stuck on a broken ski lift, or in a broken elevator?”, and “Would you rather fight 1 horse-sized duck,or 100 duck-sized horses?”You are required to design and implement two related programs:• “admin.py”, a CLI program that allows the user to manage a list of “Would You Rather”questions which are stored in a text file. This program is referred to as the “Main Program”in the marking rubric. Develop this program before “wyr.py”.• “wyr.py”, a GUI program that uses the data in the text file to pose “Would You Rather”questions to the user and record their responses. This program is referred to as the “GUIProgram” in the marking rubric. Develop this program after “admin.py”.The following pages describe the requirements of both programs in detail.Starter files for both programs are provided along with this assignment brief to help you get startedand to facilitate an appropriate program structure. Please use the starter files.Please read the entire brief carefully, and refer back to it frequently as you work on the assignment.If you do not understand any part of the assignment requirements, contact your tutor.Be sure to visit the Blackboard discussion boards regularly for extra information, tips and examples.Semester 1, 2021 CSP1150 Assignment 2 Page 2PseudocodeAs emphasised by the case study of Module 5, it is important to take the time to properly design asolution before starting to write code. Hence, this assignment requires you to write and submitpseudocode of your program design for “admin.py”, but not “wyr.py” (pseudocode is not very wellsuited to illustrating the design of an event-driven GUI program). Furthermore, while your tutors arehappy to provide help and feedback on your work throughout the semester, they will expect you tobe able to show your pseudocode and explain the design of your code.You will gain a lot more benefit from pseudocode if you actually attempt it before trying to code yourprogram – even if you just start with a rough draft to establish the overall program structure, and thenrevise and refine it as you work on the code. This back-and-forth cycle of designing and coding iscompletely normal and expected, particularly when you are new to programming. The requirementsdetailed on the following pages should give you a good idea of the structure of the program, allowingyou to make a start on designing your solution in pseudocode.See Reading 3.3 and the discussion board for further advice and tips regarding writing pseudocode.Write a separate section of pseudocode for each function you define in your program so that thepseudocode for the main part of your program is not cluttered with function definitions. Ensure thatthe pseudocode for each of your functions clearly describes the parameters that the function receivesand what the function returns back to the program. Pseudocode for functions should be presentedafter the pseudocode for the main part of your program.It may help to think of the pseudocode of your program as the content of a book, and the pseudocodeof functions as its appendices: It should be possible to read and understand a book without necessarilyreading the appendices, however they are there for further reference if needed.The functions required in “admin.py” are detailed later in the assignment brief.The following pages describe the requirements of both programs in detail.Semester 1, 2021 CSP1150 Assignment 2 Page 3Overview of “admin.py”“admin.py” is a program with a Command-Line Interface (CLI) like that of the programs we havecreated throughout the majority of the unit. The program can be implemented in under 200 lines ofcode (although implementing optional additions may result in a longer program). This number is nota limit or a goal – it is simply provided to prompt you to ask your tutor for advice if your programsignificantly exceeds it. Everything you need to know to develop this program is covered in the first 7modules of the unit. This program should be developed before “wyr.py”.This program allows the user to manage a collection of “Would You Rather” questions that are to bestored in a text file named “data.txt”. Use the “json” module to write data to the text file in JSONformat and to read the JSON data from the file back into Python. See Reading 7.1 for details of this.To illustrate the structure of the data, below is an example of the file content in JSON format:This example contains the details of two questions, stored in a list. The details of each question arestored in a dictionary consisting of five key-value pairs. The “option_1” and “option_2” keys containstrings of the two options of the question. The “mature” key contains a boolean value indicatingwhether the question is intended for mature audiences. The “votes_1” and “votes_2” keys containintegers representing the number of times each option has been selected – They are set to 0 when aquestion is added to the list, and are increased when the user chooses an option in “wyr.py”.If this file was to be read into a Python variable named data, then “data[1]” would refer to theentire dictionary containing the question about superpowers, and “data[1][‘option_2’]”would refer to the string of ‘Be able to fly’. “data[0][‘vote_1’]” would refer to theinteger of 3, etc.Understanding the structure of this data and how to interact with it is very important in many aspectsof this assignment – in particular, you will need to understand how to loop through the items of a listand how to refer to items in a dictionary. Revise Module 3 and Module 7 if you are unsure about howto interact with lists and dictionaries, and see the Blackboard discussion board for further help.[{“option_1”: “Fight 1 horse-sized duck”,“option_2”: “Fight 100 duck-sized horses”,“mature”: true,“votes_1”: 3,“votes_2”: 5},{“option_1”: “Be invisible”,“option_2”: “Be able to fly”,“mature”: false,“votes_1”: 0,“votes_2”: 0}]JSONPython and JSON use similar syntax, butboolean values start with a capital letterin Python. You do not need to worryabout this – writing and loading data viathe json module will handle it for you!Semester 1, 2021 CSP1150 Assignment 2 Page 4Output Example of “admin.py”To help you visualise the program, here is a screenshot of it being used:Semester 1, 2021 CSP1150 Assignment 2 Page 5Requirements of “admin.py”In the following information, numbered points describe a requirement of the program, and bulletpoints (in italics) are additional details, notes and hints regarding the requirement. Ask your tutor ifyou do not understand the requirements or would like further information. The requirements are:1. The first thing the program should do is try to open a file named “data.txt” in read mode, thenload the data from the file into a variable named data and then close the file. The data in the file should be in JSON format, so you will need to use the “load()” function from the“json” module to read the data into your program. See the earlier page for details of the structure. If any exceptions occur (e.g. due to the file not existing, or it not containing valid JSON data), thensimply set the data variable to be an empty list. This will occur the first time the program is run, sincethe data file will not exist yet. This ensures that you are always left with a list named data. This is the first and only time that the program should need to read anything from the file. After thispoint, the program uses the data variable, which is written to the file whenever a change is made.2. The program should then print a welcome message and enter an endless loop which starts byprinting a list of options: “Choose [a]dd, [l]ist, [s]earch, [v]iew, [d]elete or [q]uit.” and thenprompts the user to enter their choice. Once a choice has been entered, use an “if/elif”statement to handle each of the different choices (detailed in the following requirements). This requirement has been completed for you in the starter file.3. If the user enters “a” (add), prompt them to enter the two options of their question, then promptthem to enter “Y” or “N” to indicate if the question is intended for mature audiences. Place thedetails into a new dictionary with the structure shown earlier, and append the dictionary to thedata list. Finally, write the entire data list to the text file in JSON format to save the data. Use your “input_something()” function (detailed below) when prompting the user for the optionsand “Y”/“N”, to ensure that they are re-prompted until they enter something other than whitespace. Store the option strings in the dictionary without any question marks at the end – this will help to ensureconsistent output when displaying questions in the “view” section and in the GUI program. If the user enters “Y” when asked if the question is intended for mature audiences, give the “mature”key of the dictionary a boolean value of True. If they enter “N”, give it a value of False. Re-promptthe user for input until they enter “Y” or “N”. This should not be case-sensitive – also allow “y” or “n”. Remember to include the “votes_1” and “votes_2” keys in the dictionary, both set to a value of 0. Once the dictionary for the new question has been appended to the data list, call your“save_data()” function (detailed below) to write the data to the text file in JSON format.4. If the user enters “l” (list), print a list of all the questions (both options with a “/” between them)in the data list, preceded by their index number. If the data list is empty, show a “No questions saved” message instead. Use a “for” loop to iterate through the items in the data list. Remember: each item is a dictionary. You can use the “enumerate()” function to make sure you have a variable containing the indexnumber of each question as you loop through them (see Lecture 3).Semester 1, 2021 CSP1150 Assignment 2 Page 65. If the user enters “s” (search), prompt them for a search term and then list the questions thatcontain the search term in either option. Include the index number of the question next to eachresult. Display search results in the same way that you display questions when listing them. If the data list is empty, show a “No questions saved” message instead of prompting for a search term. Use your “input_something()” function (detailed below) when prompting the user for a searchterm, to ensure that they are re-prompted until they enter something other than whitespace. The code to search will be similar to the code used to list, but this time the loop body needs an “if”statement to only print questions that contain the search term (use the “in” operator – see Lecture 3). Convert the search term and options to lowercase to find matches regardless of case.6. If the user enters “v” (view), prompt them for an index number and then print details of thecorresponding question in full. This should include the options with a “?” on the end, whether thequestion is for mature audiences, and the number of votes that each option has received. If the data list is empty, show a “No questions saved” message instead of prompting for index number. Use your “input_int()” function (detailed below) when prompting for an index number, to ensurethat the user is re-prompted until they enter an integer. Print an “Invalid index number” message if the index number entered does not exist in the data list. If “votes_1” and “votes_2” both contain 0, show a “Nobody has answered this question” message.7. If the user enters “d” (delete), prompt them for an index number and then delete thecorresponding question’s dictionary from the data list, then print a “Question deleted” message. If the data list is empty, show a “No questions saved” message instead of prompting for index number. Use your “input_int()” function (detailed below) when prompting for an index number, to ensurethat the user is re-prompted until they enter an integer. Print an “Invalid index number” message if the index number entered does not exist in the data list. Once the question has been deleted from the data list, call your “save_data()” function (detailedbelow) to write the data to the text file in JSON format..8. If the user enters “q” (quit), print “Goodbye!” and break out of the loop to end the program.9. If the user enters anything else, print an “Invalid choice” message (the user will then be reprompted for a choice on the next iteration of the loop).This concludes the core requirements of “admin.py”. The following pages detail the functionsmentioned above and optional additions and enhancements that can be added to the program.Remember that you are required to submit pseudocode for your design of “admin.py”. Use the starterfile and requirements above as a guide to structure the design of your program.Semester 1, 2021 CSP1150 Assignment 2 Page 7Functions in “admin.py”The requirements above mentioned 3 functions – “input_int()”, “input_something()”, and“save_data()”. As part of “admin.py”, you must define and use these functions.1. The “input_int()” function takes 1 parameter named prompt – a string containing themessage to display before waiting for input. The function should repeatedly re-prompt the user(using the prompt parameter) for input until they enter an integer. It should then return thevalue as an integer. See Workshop 4 for a task involving the creation of a very similar function.2. The “input_something()” function takes 1 parameter named prompt – a string containingthe message to display before waiting for input.. The function should repeatedly re-prompt theuser (using the prompt parameter) for input until they enter a value which consists of at least 1non-whitespace character (i.e. the input cannot be nothing or consist entirely of spaces, tabs, etc.).It should then return the value as a string. Use the “strip()” string method on a string to remove whitespace from the start and end.If a string consists entirely of whitespace, it will have nothing left once you strip the whitespace away. Note that exception handling is not needed in this function.3. The “save_data()” function takes 1 parameter named data_list (the data list from themain program). The function should open “data.txt” in write mode, then write the data_listparameter to the file in JSON format and close the file. This function does not return anything. This is the only part of the program that should be writing to the file, and it always overwrites the entirecontent of the file with the entirety of the current data. See Reading 7.1 for an example of using the “json” module. You can specify an additional indentparameter in the “dump()” function to format the JSON data nicely in the text file.The definitions of these functions should be at the start of the program (as they are in the starter fileprovided), and they should be called where needed in the program. Revise Module 4 if you areuncertain about defining and using functions. Ensure that the functions behave exactly as specified;It is important to adhere to the stated function specifications when working on a programming project.In particular, remember that the “prompt” parameter of the input functions is for the text that youwant to show as a prompt. Here is an example of the function being called and its output:You are welcome to define and use additional functions if you feel they improve your program, but besure to consider the characteristics and ideals of functions as outlined in Lecture 4.Semester 1, 2021 CSP1150 Assignment 2 Page 8Optional Additions and Enhancements for “admin.py”Below are some suggestions for minor additions and enhancements that you can make to the programto further test and demonstrate your programming ability. They are not required and you can earnfull marks in the assignment without implementing them. Add 1 to the index number of questions whenever the list or search results are shown, so thatthe numbers begin at 1 instead of 0. Remember to subtract 1 from the user’s input whenviewing or deleting questions so that you reference the appropriate index of the data list. When adding a question, make sure that the two options are not identical. If they are, promptthe user to enter them again or cancel. If the text of an option is longer than 40 characters, truncate it so that it fits into 40 characterswith “…” added to the end whenever you list questions or show search results. ––The “shorten()” function from the “textwrap” module can help with this.The options should be stored in their entirety, and only truncated when listing or showingsearch results. Display the entire text when viewing a question. When searching for a question, show a “No results found” message if the search term is notfound in the options of any of the questions. When viewing the details of a question, make sure that the pluralisation is correct whenprinting votes, i.e. print “vote” if an option has received 1 vote, otherwise print “votes”. When viewing the details of a question, include the percentage next to the vote numbers,rounded to 1 decimal place. If the split is between 50 and 60%, print “This question is divisive!” Allow users to see how many of the questions are intended for mature audiences, as well asthe ability to toggle the “mature” value between True and False for an existing question. Allow users to use the search, view and delete options more efficiently by allowing input of “s”, “v ” and “d ”. For example, instead ofneeding to type “s” and then “year”, the user could type “s year”, and instead of needing totype “v” then “2”, the user could type “v 2”.– This feature takes a reasonable amount of extra thought and effort to implement efficiently.Semester 1, 2021 CSP1150 Assignment 2 Page 9Overview of “wyr.py”“wyr.py” is a program with a Graphical User Interface (GUI), as covered in Module 9. It should becoded in an Object Oriented style, as covered in Module 8. Everything you need to know in order todevelop this program is covered in the first 9 modules of the unit. This program should be developedafter “admin.py”.The entirety of this program can be implemented in under 115 lines of code (although implementingoptional additions may result in a longer program). This number is not a limit or a goal – it is simplyprovided to prompt you to ask your tutor for advice if your program significantly exceeds it. You mustuse the “tkinter” module and the “tkinter.messagebox” module to create the GUI.This program uses the data from the “data.txt” file. Similar to the admin program, this program shouldload the data from the file once only – when the program begins. When the program begins, it alsoasks the user if they want to see questions intended for mature audiences.Next, it presents the questions loaded from the text file one at a time (skipping mature ones if theuser chose “No” when asked), waiting for the user to choose before moving onto the next question.The user’s choices are recorded by incrementing the “votes_1” or “votes_2” key of the dictionaryof the current question. The data is saved to the text file in JSON format after each question. Afterthe user responds to the final question, the program ends.The following pages detail how to implement the program.The options are presented in buttons – clicking onerecords the choice and proceeds to the next question.Semester 1, 2021 CSP1150 Assignment 2 Page 10Constructor of the GUI Class of “wyr.py”The constructor (the “__init__()” method) of your GUI class must implement the following:1. Create the main window of the program and give it a title of “Would You Rather”. You are welcome to set other main window settings to make the program look/behave as desired.2. Try to open the “data.txt” file in read mode and load the JSON data from the file into an attributenamed “self.data”, and then close the file. If any exceptions occur (due to the file not existing, or it not containing valid JSON data), show an errormessagebox with a “Missing/Invalid file” message and call the “.destroy()” method on the mainwindow to end the program. Include a “return” statement in the exception handler after destroyingthe main window to halt the constructor so that the program ends cleanly.3. Use widgets such as Label and Button from the “tkinter” module to implement the GUIdepicted on the previous page. The layout is up to you as long as it functions as intended. You will save time if you design the GUI and determine exactly which widgets you will need and how tolay them out before you start writing the code. See Reading 9.1 for information regarding various settings that can be applied to widgets to makethem appear with the desired padding, colour, size, etc. Do not set the text for the buttons that will contain the question’s options at this point. They will beset in the “show_question()” method. See the Discussion Board for help. Both of the buttons displaying options will be calling the “record_vote()” method when clicked,but need to pass it a different parameter value – a string of ‘votes_1’ or a string of ‘votes_2’(to make it easy to increment the appropriate key). This can be tricky, so here is some sample code:4. Create a “self.question_num” attribute (set it to 0), and a “self.show_mature”attribute (set it to True or False depending upon whether the user indicates that they want tosee questions intended for a mature audience). The self.question_num attribute keeps track of the current question number and will be used torefer to index numbers of the self.data list to refer to the dictionary of the current question. The “tkinter.messagebox.askyesno()” function displays a message and returns True orFalse depending on whether the user selects Yes or No. Assign the return value to the attribute.5. Lastly, the constructor should end by calling the “show_question()” method to display thefirst question in the GUI, and then call “tkinter.mainloop()” to start the main loop. To call a method of the class, include “self.” at the start, e.g. “self.show_question()”.That is all that the constructor requires. The following pages detail the methods mentioned above,and some optional additions. You are not required to submit pseudocode for “wyr.py”.tkinter.Button(self.main, command=lambda: self.record_vote(‘votes_1’))tkinter.Button(self.main, command=lambda: self.record_vote(‘votes_2’))Semester 1, 2021 CSP1150 Assignment 2 Page 11Methods in the GUI class of “wyr.py”This program requires you to define 2 methods to implement the functionality specified –“show_question()” and “record_vote()”. These should be defined as part of the GUI class.1. The “show_question()” method is responsible for putting the text of the current question’soptions in the GUI. It is called at the end of the constructor to display the first question, by the“record_vote()” method to progress to the next question, and by itself to skip maturequestions if the user has chosen not to see them. The method also handles displaying amessagebox and ending the program after the final question. First, try to refer to the dictionary of the current question using self.question_num and theself.data list. If an IndexError occurs, the end of the question list has been reached – show anappropriate messagebox and end the program (use to “return” to immediately end the method). Next, if the current question is marked as mature and self.show_mature is set to False, add 1to self.question_num and call the “show_question()” method to skip the question.Otherwise, set the text of the buttons to the options of the current question, with “?” added to the end. The “.configure()” method (see Reading 9.1) can be used on a widget to change the text itdisplays. Alternatively, you can use a StringVar to control the text of a widget (see Lecture 9).2. The “record_vote()” method is called when the user clicks a button containing one of theoptions of the current question. It should add 1 to the “votes_1” or “votes_2” key of thecurrent question dictionary, then open “data.txt”, write the self.data list to it in JSON format,and close the file. Then, display a messagebox confirming that the vote has been recorded, add 1to self.question_num, and call “show_question()” to proceed to the next question. This method receives a parameter named “vote” that will contain a string of ‘votes_1’ or a stringof ‘votes_2’ depending on which button was clicked. Use this value to add 1 to the appropriate keyof the current question dictionary (you can use vote to directly refer to the desired dictionary key). Writing data to the file will involve very similar code to the “save_data()” function of admin.py.These methods are all that are required to implement the functionality of the program, but you maywrite/use additional methods if you feel they improve your program.GUIs and OOP are massive topics that we do not explore in depth in the unit. As such, this program islikely to involve more research, experimentation and combining/adapting of examples from the unitcontent than the main program. This is expected, and much of what this program tests is your abilityto rapidly produce a working product despite having limited familiarity or experience.Do not be alarmed/concerned if you find this program confusing or difficult for those reasons, and besure to check the discussion board regularly for tips and examples. The GUI program is worth fewermarks than the main program of this assignment.Semester 1, 2021 CSP1150 Assignment 2 Page 12Optional Additions and Enhancements for “wyr.py”Below are some suggestions for minor additions and enhancements that you can make to the programto further test and demonstrate your programming ability. They are not required and you can earnfull marks in the assignment without implementing them. In the constructor, check that the self.data list contains at least 1 question – It is possiblefor the “data.txt” file to exist but contain an empty list, but this program requires questions.Show an error messagebox and end the program if there are no questions in the list. –For an added challenge, require at least one all ages question (“mature” key set to False) ifthe user specified that they do not want to see questions intended for mature audiences. If a question has no prior votes recorded (i.e. “votes_1” and “votes_2” keys both at 0),include “You are the first person to answer this question!” in the messagebox displayed bythe record_vote() method when the user chooses an option. –You could also mention when a specific option is chosen for the first time, if the other optionhas been chosen before, e.g. “You are the first person to choose that option for this question!” Using the values of the current question’s “votes_1” and “votes_2” keys, include amessage of “You are in the majority!” or “You are in the minority!” in the messageboxdisplayed by the record_vote() method when the user chooses an option. Tweak the layout and settings of your GUI widgets to ensure that it is robust. e.g. If the textof an option is long, it should still all be visible within the button. You could experiment withwrapping the text across multiple lines.– For an added challenge, try to implement this in a layout that shows the options side-by-side. Include a Label that shows the user’s progress through the list of questions in the program’sGUI, e.g. “Question 2 of 5”. Make this label work smoothly even if skipping mature questions. Display the options of each question in a random order, without impacting the ability tocorrectly record votes for the options. Display the questions in a random order, in a way that still allows mature questions to beskipped and without changing the order in which the questions are stored in the text file.Semester 1, 2021 CSP1150 Assignment 2 Page 13Submission of DeliverablesIt is recommended that you send your work to your tutor for feedback at least once prior to submittingit. Once your assignment is complete, submit both the pseudocode for “admin.py” (“.pdf” file) andthe source code for “admin.py” and “wyr.py” code (“.py” files) to the appropriate location in theAssessments area of Blackboard. Zipping the files is not required. An assignment cover sheet is notrequired, but include your name and student number at the top of all files (not just in the filenames).Academic Integrity and MisconductThe entirety of your assignment must be your own work (unless otherwise referenced) and producedfor the current instance of the unit. Any use of unreferenced content you did not create constitutesplagiarism, and is deemed an act of academic misconduct. All assignments will be submitted toplagiarism checking software which includes previous copies of the assignment, and the worksubmitted by all other students in the unit.Remember that this is an individual assignment. Never give anyone any part of your assignment –even after the due date or after results have been released. Do not work together with other studentson individual assignments – you can help someone by explaining a concept or directing them to therelevant resources, but doing any part of the assignment for them or alongside them, or showing themyour work is inappropriate. An unacceptable level of cooperation between students on an assignmentis collusion, and is deemed an act of academic misconduct. If you are uncertain about plagiarism,collusion or referencing, simply contact your tutor, lecturer or unit coordinator.You may be asked to explain and demonstrate your understanding of the work you have submitted.Your submission should accurately reflect your understanding and ability to apply the unit content.Marking Key CriteriaMarksPseudocodeThese marks are awarded for submitting pseudocode which suitably represents the design of youradmin program. Pseudocode will be assessed on the basis of whether it clearly describes the stepsof the program in English, and whether the program is well structured.5FunctionalityThese marks are awarded for submitting source code that implements the requirements specifiedin this brief, in Python 3. Code which is not functional or contains syntax errors will lose marks, aswill failing to implement requirements as specified.15Main Program: 10GUI Program: 5Code QualityThese marks are awarded for submitting well-written source code that is efficient, well-formattedand demonstrates a solid understanding of the concepts involved. This includes appropriate use ofcommenting and adhering to best practise.10Main Program: 5GUI Program: 5Total:30 See the “Rubric and Marking Criteria” document provided with this brief for further details!