├── Week 01 ├── Week 1 Quiz │ ├── Quiz01.md │ └── Quiz01.py ├── Week 1B │ ├── Lecture Quiz │ │ ├── Lecture02.md │ │ ├── Lecture01.md │ │ └── Lecture03.md │ └── Example Codes │ │ ├── Lecture02-02.py │ │ ├── Lecture02-01.py │ │ ├── Lecture01.py │ │ ├── Lecture03-Original.py │ │ └── Lecture03-Corrected.py ├── Week 1A │ ├── Lecture Quiz │ │ ├── Lecture02.md │ │ ├── Lecture03.md │ │ └── Lecture01.md │ └── Example Codes │ │ ├── Lecture01.py │ │ ├── Lecture02.py │ │ └── Lecture03.py └── Week 1 Mini Project Rock-paper-scissors-lizard-Spock │ └── Rock-paper-scissors-lizard-Spock.py ├── Week 08 ├── Week 8 Quiz │ └── Quiz 8B.md ├── Week 8 A │ ├── Lecture Quiz │ │ ├── Lecture 01.md │ │ └── Lecture 02.md │ └── Example Codes │ │ ├── Lecture 01-2.py │ │ └── Lecture 01-1.py └── Week 8 B │ ├── Lecture Quiz │ ├── Lecture 01.md │ └── Lecture 02.md │ └── Example Codes │ ├── Lecture 01-1.py │ └── Lecture 01-2.py ├── README.md ├── Week 03 ├── Week 3 Quiz │ ├── ArcheryTarget.png │ ├── Quiz 3B Code.py │ ├── Quiz 3A.md │ └── Quiz 3B.md ├── Week 3B │ ├── Lecture Quizzes │ │ ├── Lecture03.md │ │ ├── Lecture01.md │ │ └── Lecture02.md │ └── Lecture Codes │ │ ├── Lecture01.py │ │ ├── Lecture03-2.py │ │ └── Lecture03-1.py ├── Week 3A │ ├── Lecture Quizzes │ │ ├── Lecture03.md │ │ ├── Lecture01.md │ │ └── Lecture02.md │ └── Lecture Codes │ │ ├── Lecture01-1.py │ │ ├── Lecture02-2.py │ │ ├── Lecture02-1.py │ │ ├── Lecture02-3.py │ │ ├── Lecture01-2.py │ │ └── Lecture03-1.py └── Week 3 Assignment │ └── Stopwatch - The Game.py ├── Week 02 ├── Week 2B │ ├── Lecture Quiz │ │ ├── Lecture02.md │ │ ├── Lecture01.md │ │ ├── Lecture03.md │ │ └── Lecture04.md │ └── Example Codes │ │ ├── Lecture01.py │ │ ├── Lecture02.py │ │ ├── Lecture04-Original.py │ │ └── Lecture04-Corrected.py ├── Week 2A │ ├── Lecture Quiz │ │ ├── Lecture03.md │ │ ├── Lecture02.md │ │ └── Lecture01.md │ └── Example Codes │ │ ├── Lecture01.py │ │ ├── Lecture03.py │ │ └── Lecture02.py ├── Week 2 Mini Project │ └── Guess a Number.py └── Week 2 Quiz │ ├── Quiz2b.md │ └── Quiz2a.md ├── Week 04 ├── Week 4B │ ├── Lecture Quizzes │ │ ├── Lecture01.md │ │ ├── Lecture03.md │ │ └── Lecture02.md │ └── Lecture Codes │ │ ├── Lecture03.py │ │ ├── Lecture01-1.py │ │ ├── Lecture01-2.py │ │ └── Lecture02.py ├── Week 4A │ ├── Lecture Quizzes │ │ ├── Lecture02.md │ │ ├── Lecture04.md │ │ ├── Lecture01.md │ │ └── Lecture03.md │ └── Lecture Codes │ │ ├── Lecture03.py │ │ ├── Lecture02-1.py │ │ ├── Lecture02-2.py │ │ └── Lecture04.py ├── Week 4 Quiz │ ├── Quiz 4A Codes.py │ ├── Quiz 4B Codes.py │ ├── Quiz 4A.md │ └── Quiz 4B.md └── Week 4 Assignment │ └── Pong.py ├── Week 00 ├── Week 0 Mini Project We want... a shrubbery! │ └── We want... a shrubbery!.py ├── Week 0B │ ├── Lecture Quizzes │ │ ├── Lecture1.md │ │ └── Lecture3.md │ └── Example Codes │ │ └── Lecture1.py ├── Week 0A │ ├── Lecture Quiz │ │ └── Lecture3.md │ └── Example Codes │ │ └── Lecture3.py └── Week 0 Quiz │ └── Quiz 0.md ├── Week 06 ├── Week 6 B │ ├── Lecture Quiz │ │ ├── Lecture 02.md │ │ ├── Lecture 03.md │ │ └── Lecture 01.md │ └── Example Codes │ │ ├── Lecture 01.py │ │ ├── Lecture 03.py │ │ └── Lecture 02.py ├── Week 6 A │ ├── Lecture Quiz │ │ ├── Lecture 01.md │ │ ├── Lecture 03.md │ │ ├── Lecture 04.md │ │ └── Lecture 02.md │ └── Example Codes │ │ ├── Lecture 01.py │ │ ├── Lecture 03-2.py │ │ ├── Lecture 03-1.py │ │ ├── Lecture 02.py │ │ └── Lecture 04.py └── Week 6 Programming Assignment │ ├── Card Class Testing Template.py │ ├── Hand Class Testing Template.py │ ├── Deck Class Testing Template.py │ ├── Hand Class GetValue Method Testing Template.py │ └── Blackjack.py ├── .gitattributes ├── .gitignore ├── Week 05 ├── Week 5 Quiz │ ├── Week 5B Python Codes.py │ ├── Week 5A Python Codes.py │ ├── Quiz 5A.md │ └── Quiz 5B.md └── Week 5 Assignment │ └── Memory.py ├── LICENSE └── Week 07 ├── Week 7 Quiz ├── Quiz 7B.md └── Quiz 7A.md └── Week 7 Programming Assignment └── Spaceship.py /Week 01/Week 1 Quiz/Quiz01.md: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/UtkarshPathrabe/An-Introduction-to-Interactive-Programming-in-Python----Coursera/HEAD/Week 01/Week 1 Quiz/Quiz01.md -------------------------------------------------------------------------------- /Week 08/Week 8 Quiz/Quiz 8B.md: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/UtkarshPathrabe/An-Introduction-to-Interactive-Programming-in-Python----Coursera/HEAD/Week 08/Week 8 Quiz/Quiz 8B.md -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | An-Introduction-to-Interactive-Programming-in-Python----Coursera 2 | ================================================================ 3 | 4 | Study Material for the course 5 | -------------------------------------------------------------------------------- /Week 03/Week 3 Quiz/ArcheryTarget.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/UtkarshPathrabe/An-Introduction-to-Interactive-Programming-in-Python----Coursera/HEAD/Week 03/Week 3 Quiz/ArcheryTarget.png -------------------------------------------------------------------------------- /Week 02/Week 2B/Lecture Quiz/Lecture02.md: -------------------------------------------------------------------------------- 1 | Quiz 2 | ==== 3 | 4 | Question 5 | -------- 6 | 7 | When does the event handler for an input field get called? 8 | 9 | ### Answer 10 | 11 | When you press Enter -------------------------------------------------------------------------------- /Week 04/Week 4B/Lecture Quizzes/Lecture01.md: -------------------------------------------------------------------------------- 1 | Quiz 2 | ==== 3 | 4 | Question 5 | -------- 6 | 7 | In this last example, where is the position of the ball updated? 8 | 9 | ### Answer 10 | 11 | In the draw handler -------------------------------------------------------------------------------- /Week 04/Week 4A/Lecture Quizzes/Lecture02.md: -------------------------------------------------------------------------------- 1 | Quiz 2 | ==== 3 | 4 | Question 1 5 | ---------- 6 | 7 | When do you get a keydown event? 8 | 9 | ### Answer 10 | 11 | Once each time a key is initially pushed. 12 | -------------------------------------------------------------------------------- /Week 00/Week 0 Mini Project We want... a shrubbery!/We want... a shrubbery!.py: -------------------------------------------------------------------------------- 1 | # program template for mini-project 0 2 | 3 | # Modify the print statement according to 4 | # the mini-project instructions 5 | 6 | print "We want... a shrubbery!" -------------------------------------------------------------------------------- /Week 01/Week 1B/Lecture Quiz/Lecture02.md: -------------------------------------------------------------------------------- 1 | Quiz 2 | ==== 3 | 4 | Question 1 5 | ---------- 6 | 7 | Which of the following are valid clauses in an if statement? 8 | 9 | ### Answer 10 | 11 | if clause 12 | elif clause 13 | else clause -------------------------------------------------------------------------------- /Week 02/Week 2A/Lecture Quiz/Lecture03.md: -------------------------------------------------------------------------------- 1 | Program Structure 2 | ================= 3 | 4 | Globals (State) 5 | Helper Functions 6 | Classes 7 | Define event handlers 8 | Create a frame 9 | Register event handlers 10 | Start frame and timers -------------------------------------------------------------------------------- /Week 06/Week 6 B/Lecture Quiz/Lecture 02.md: -------------------------------------------------------------------------------- 1 | Lecture 02 Quiz 2 | =============== 3 | 4 | Question 5 | -------- 6 | Consider the object p = Point1(3, 6). Which Python statement creates a second Point1 object with the same values? 7 | 8 | ### Answer 9 | * q = Point1(3, 6) -------------------------------------------------------------------------------- /Week 02/Week 2B/Lecture Quiz/Lecture01.md: -------------------------------------------------------------------------------- 1 | Quiz 2 | ==== 3 | 4 | Question 5 | -------- 6 | 7 | When a user pushes a button, what argument is passed to the event handler? 8 | 9 | ### Answer 10 | 11 | Nothing (there are no arguments passed to the event handler for a button) -------------------------------------------------------------------------------- /Week 02/Week 2A/Example Codes/Lecture01.py: -------------------------------------------------------------------------------- 1 | # Example of a simple event-driven program 2 | 3 | # CodeSkulptor GUI module 4 | import simplegui 5 | 6 | # Event handler 7 | def tick(): 8 | print "tick!" 9 | 10 | # Register handler 11 | timer = simplegui.create_timer(1000, tick) 12 | 13 | # Start timer 14 | timer.start() -------------------------------------------------------------------------------- /Week 02/Week 2B/Lecture Quiz/Lecture03.md: -------------------------------------------------------------------------------- 1 | Quiz 2 | ==== 3 | 4 | Question 5 | -------- 6 | 7 | What information is displayed in the console (upper right panel) in Viz mode? 8 | 9 | ### Answer 10 | 11 | The output of print statements 12 | Tags corresponding to events that have been previously fired 13 | -------------------------------------------------------------------------------- /Week 03/Week 3B/Lecture Quizzes/Lecture03.md: -------------------------------------------------------------------------------- 1 | Quiz 2 | ==== 3 | 4 | Question 5 | -------- 6 | 7 | If you see a white canvas and nothing works, what does it mean? 8 | 9 | ### Answer 10 | 11 | Your forgot to start the frame. 12 | 13 | ### Explanation 14 | 15 | Always remember to start the frame and any timers in your program. -------------------------------------------------------------------------------- /Week 04/Week 4B/Lecture Codes/Lecture03.py: -------------------------------------------------------------------------------- 1 | ################################### 2 | # Lists (mutable) vs. tuples (immutable) 3 | 4 | print [4, 5, 6] 5 | 6 | print (4, 5, 6) 7 | 8 | print type([4, 5, 6]) 9 | 10 | print type((4, 5, 6)) 11 | 12 | a = [4, 5, 6] 13 | a[1] = 100 14 | print a 15 | 16 | b = (4, 5, 6) 17 | b[1] = 100 18 | print b 19 | -------------------------------------------------------------------------------- /Week 04/Week 4B/Lecture Quizzes/Lecture03.md: -------------------------------------------------------------------------------- 1 | Quiz 2 | ==== 3 | 4 | Question 5 | -------- 6 | 7 | What does running the following code do? 8 | string = "Larch" 9 | string[1] = "u" 10 | print string 11 | 12 | ### Answer 13 | 14 | Throw a TypeError 15 | 16 | ### Explanation 17 | 18 | Remember that strings like tuples are immutable. -------------------------------------------------------------------------------- /Week 04/Week 4B/Lecture Quizzes/Lecture02.md: -------------------------------------------------------------------------------- 1 | Quiz 2 | ==== 3 | 4 | Question 5 | -------- 6 | 7 | Consider the following Python code: 8 | a = b = [1, 2, 3] 9 | b[2] = 4 10 | What is the value of a[2] after running this code? 11 | 12 | ### Answer 13 | 14 | 4 15 | 16 | ### Explanation 17 | 18 | Note that a and b refer to the same list. -------------------------------------------------------------------------------- /Week 03/Week 3A/Lecture Quizzes/Lecture03.md: -------------------------------------------------------------------------------- 1 | Quiz 2 | ==== 3 | 4 | Question 5 | -------- 6 | 7 | What handler should draw text on the canvas? 8 | 9 | ### Answer 10 | 11 | The draw handler. 12 | 13 | ### Explanation 14 | 15 | The canvas should always be drawn exclusively by the draw handler. No other code should try to update the canvas in any way. -------------------------------------------------------------------------------- /Week 03/Week 3B/Lecture Quizzes/Lecture01.md: -------------------------------------------------------------------------------- 1 | Quiz 2 | ==== 3 | 4 | Question 5 | -------- 6 | 7 | How often does a timer event happen? 8 | 9 | ### Answer 10 | 11 | At the interval specified when you call `simplegui.create_timer` 12 | 13 | ### Explanation 14 | 15 | The first argument to simplegui.create_timer is the interval (in milliseconds) between timer events. -------------------------------------------------------------------------------- /Week 08/Week 8 A/Lecture Quiz/Lecture 01.md: -------------------------------------------------------------------------------- 1 | Lecture 01 Quiz 2 | =============== 3 | 4 | Question 5 | -------- 6 | What elements does the set s contain after this code is executed? 7 | 8 | ```python 9 | s = set([1, 2, 4, 2]) 10 | s.add(7) 11 | s.remove(1) 12 | ``` 13 | 14 | ### Answer 15 | * 2, 4, 7 16 | 17 | #### Explanation 18 | Remember that a set cannot have duplicates. -------------------------------------------------------------------------------- /Week 03/Week 3A/Lecture Quizzes/Lecture01.md: -------------------------------------------------------------------------------- 1 | Quiz 2 | ==== 3 | 4 | Question 5 | -------- 6 | 7 | On a SimpleGUI canvas of size 300 by 200 pixels, what is the pixel coordinate of the bottom right pixel? 8 | 9 | ### Answer 10 | 11 | 299, 199 12 | 13 | ### Explanation 14 | 15 | On a 300 by 200 pixel canvas, the pixel coordinates range from 0, 0 in the top left to 299, 199 in the bottom right. -------------------------------------------------------------------------------- /Week 03/Week 3B/Lecture Quizzes/Lecture02.md: -------------------------------------------------------------------------------- 1 | Quiz 2 | ==== 3 | 4 | Question 5 | -------- 6 | 7 | In Viz mode, when are new draw events added to the event log? 8 | 9 | ### Answer 10 | 11 | Each time you click the "Draw" button 12 | 13 | ### Explanation 14 | 15 | Remember that in Viz mode, draw events are fired manually to allowed precise control over the execution of your interactive program. -------------------------------------------------------------------------------- /Week 03/Week 3A/Lecture Quizzes/Lecture02.md: -------------------------------------------------------------------------------- 1 | Quiz 2 | ==== 3 | 4 | Question 5 | -------- 6 | 7 | If s1 is the string "Python is great!", which of the following expressions would be the string "Python"? 8 | 9 | ### Answer 10 | 11 | * s1[:6] 12 | * s1[0:6] 13 | 14 | ### Explanation 15 | 16 | String indices begin at 0. String slices start from the first index and go up to, but not including, the last index. -------------------------------------------------------------------------------- /Week 04/Week 4A/Lecture Quizzes/Lecture04.md: -------------------------------------------------------------------------------- 1 | Quiz 2 | ==== 3 | 4 | Question 1 5 | ---------- 6 | 7 | What Python expression would you use to determine if the ball is colliding with the bottom of the canvas? 8 | 9 | ### Answer 10 | 11 | p[1] >= (height - 1) - r 12 | 13 | ### Explanation 14 | 15 | Remember that the canvas coordinates start with 0. You must also account for the radius of the ball. 16 | -------------------------------------------------------------------------------- /Week 02/Week 2A/Lecture Quiz/Lecture02.md: -------------------------------------------------------------------------------- 1 | Quiz 2 | ==== 3 | 4 | Question 1 5 | ---------- 6 | 7 | What numbers does the following program print: 8 | x = 3 9 | def f(): 10 |     x = 4 11 |     print x 12 | f() 13 | print x 14 | 15 | ### Answer 16 | 17 | 4, 3 18 | 19 | ### Explanation 20 | 21 | The x inside the function f is a local variable and does not affect the global x. -------------------------------------------------------------------------------- /Week 01/Week 1A/Lecture Quiz/Lecture02.md: -------------------------------------------------------------------------------- 1 | Quiz 2 | ==== 3 | 4 | Question 1 5 | ---------- 6 | 7 | Viz mode records a trace (sequence of statements) of the execution of your program. 8 | When a particular statement is highlighted in this trace using the navigation buttons, which of the following are true? 9 | 10 | ### Answer 11 | 12 | The lower right pane displays the state of the program prior to execution of the highlighted statement. -------------------------------------------------------------------------------- /Week 08/Week 8 A/Example Codes/Lecture 01-2.py: -------------------------------------------------------------------------------- 1 | # Examples of Sets 2 2 | 3 | instructors = set(['Rixner', 'Warren', 'Greiner', 'Wong']) 4 | print instructors 5 | 6 | def get_rid_of(inst_set, starting_letter): 7 | remove_set = set([]) 8 | for inst in inst_set: 9 | if inst[0] == starting_letter: 10 | remove_set.add(inst) 11 | inst_set.difference_update(remove_set) 12 | 13 | get_rid_of(instructors, 'W') 14 | print instructors -------------------------------------------------------------------------------- /Week 08/Week 8 A/Lecture Quiz/Lecture 02.md: -------------------------------------------------------------------------------- 1 | Lecture 02 Quiz 2 | =============== 3 | 4 | Question 5 | -------- 6 | What do we suggest group_collide(rocks, ship) should return? 7 | 8 | ### Answer 9 | * True if the ship's bounding circle overlaps with one of the rocks and False otherwise. 10 | 11 | #### Explanation 12 | There are many ways of getting your game to work. The suggestions we are making are intended to help you simplify your code. -------------------------------------------------------------------------------- /Week 03/Week 3A/Lecture Codes/Lecture01-1.py: -------------------------------------------------------------------------------- 1 | # first example of drawing on the canvas 2 | 3 | import simplegui 4 | 5 | # define draw handler 6 | def draw(canvas): 7 | canvas.draw_text("Hello!",[100, 100], 24, "White") 8 | canvas.draw_circle([100, 100], 2, 2, "Red") 9 | 10 | # create frame 11 | frame = simplegui.create_frame("Text drawing", 300, 200) 12 | 13 | # register draw handler 14 | frame.set_draw_handler(draw) 15 | 16 | # start frame 17 | frame.start() -------------------------------------------------------------------------------- /Week 08/Week 8 B/Lecture Quiz/Lecture 01.md: -------------------------------------------------------------------------------- 1 | Lecture 01 Quiz 2 | =============== 3 | 4 | Question 5 | -------- 6 | In a tiled image with 25 images (organized in a 5x5 grid) what is the center position of the 8th image? The size of each sub-image is 30x30 pixels. Assume the same image ordering as the explosion, left to right, then top to bottom. 7 | 8 | ### Answer 9 | * 75, 45 10 | 11 | #### Explanation 12 | The 8th image is the third image in the second row. -------------------------------------------------------------------------------- /Week 06/Week 6 B/Lecture Quiz/Lecture 03.md: -------------------------------------------------------------------------------- 1 | Lecture 03 Quiz 2 | =============== 3 | 4 | Question 1 5 | ---------- 6 | In building a class definition for a widget object, which of the following names obeys Python's naming convention for classes? 7 | 8 | ### Answer 9 | * Widget 10 | 11 | Question 2 12 | ---------- 13 | What does the following code print? 14 | ```python 15 | i = 1 16 | while i < 16: 17 | print i 18 | i *= 2 19 | ``` 20 | 21 | ### Answer 22 | 1 2 4 8 -------------------------------------------------------------------------------- /Week 00/Week 0B/Lecture Quizzes/Lecture1.md: -------------------------------------------------------------------------------- 1 | Quiz 2 | ==== 3 | 4 | Question 1 5 | ---------- 6 | 7 | Which of these expressions can be used to increment the value of a variable x by 1? 8 | 9 | ### Answer 10 | 11 | x = x + 1 12 | x += 1 13 | 14 | ### Explanation 15 | 16 | Remember that the += operator retrieves the value of the variable on left-hand side of the assignment, adds the value of the expression on the right-hand side, and then stores the resulting sum back in the left-hand variable. -------------------------------------------------------------------------------- /Week 00/Week 0B/Lecture Quizzes/Lecture3.md: -------------------------------------------------------------------------------- 1 | Quiz 2 | ==== 3 | 4 | Question 1 5 | ---------- 6 | 7 | What is the most common error made by students during mini-project submission and peer evaluation? 8 | 9 | ### Answer 10 | 11 | Forgetting to hit the "Submit" button for your mini-project. 12 | 13 | ### Explanation 14 | 15 | Remember to hit the "Submit" button to submit your mini-project. Multiple submissions before the deadline are fine. To activate the "Submit" button, check the Honor Code checkbox. -------------------------------------------------------------------------------- /Week 03/Week 3A/Lecture Codes/Lecture02-2.py: -------------------------------------------------------------------------------- 1 | # convert xx.yy to xx dollars and yy cents 2 | def convert(val): 3 | dollars = int(val) 4 | cents = int(100 * (val - dollars)) 5 | return str(dollars) + " dollars and " + str(cents) + " cents" 6 | 7 | # Tests 8 | print convert(11.23) 9 | print convert(11.20) 10 | print convert(1.12) 11 | print convert(12.01) 12 | print convert(1.01) 13 | print convert(0.01) 14 | print convert(1.00) 15 | print convert(0) 16 | print convert(-1.40) 17 | print convert(12.55555) -------------------------------------------------------------------------------- /Week 01/Week 1A/Lecture Quiz/Lecture03.md: -------------------------------------------------------------------------------- 1 | Quiz 2 | ==== 3 | 4 | Question 1 5 | ---------- 6 | 7 | In Python, what operator computes the remainder of one number with respect to another? 8 | 9 | ### Answer 10 | 11 | % 12 | 13 | Question 2 14 | ---------- 15 | 16 | In the expression 6 + 7 % 5, which operator is evaluated first (i.e., which has higher precedence)? 17 | 18 | ### Answer 19 | 20 | % 21 | 22 | Question 3 23 | ---------- 24 | 25 | In Python, what statement is used to load a module? 26 | 27 | ### Answer 28 | 29 | import -------------------------------------------------------------------------------- /Week 01/Week 1A/Lecture Quiz/Lecture01.md: -------------------------------------------------------------------------------- 1 | Quiz 2 | ==== 3 | 4 | Question 1 5 | ---------- 6 | 7 | In Python, what character indicates that an indented block of code is about to begin? 8 | 9 | ### Answer 10 | 11 | : 12 | 13 | Question 2 14 | ---------- 15 | 16 | In Python, what statement causes a function to return a value? 17 | 18 | ### Answer 19 | 20 | return 21 | 22 | Question 3 23 | ---------- 24 | 25 | If a Python function contains no return statements, what value does the function return? 26 | 27 | ### Answer 28 | 29 | None -------------------------------------------------------------------------------- /Week 01/Week 1B/Example Codes/Lecture02-02.py: -------------------------------------------------------------------------------- 1 | # Conditionals Examples 2 | 3 | # Return True if year is a leap year, false otherwise 4 | def is_leap_year(year): 5 | if (year % 400) == 0: 6 | return True 7 | elif (year % 100) == 0: 8 | return False 9 | elif (year % 4) == 0: 10 | return True 11 | else: 12 | return False 13 | 14 | 15 | year = 2012 16 | leap_year = is_leap_year(year) 17 | 18 | if leap_year: 19 | print year, "is a leap year" 20 | else: 21 | print year, "is not a leap year" -------------------------------------------------------------------------------- /Week 04/Week 4A/Lecture Quizzes/Lecture01.md: -------------------------------------------------------------------------------- 1 | Quiz 2 | ==== 3 | 4 | Question 5 | -------- 6 | 7 | Which of the following lists have a length of 3? 8 | 9 | ### Answer 10 | 11 | ['a', 'b', 'c'] 12 | [['a', 'b'], 'abc', []] 13 | 14 | ### Explanation 15 | 16 | The length of the list is the number of items in the list. Note that each item can itself be a list (with 0 or more elements of its own). Also, notice that some of the answer lists in this question have different types of elements. While this is legal in Python, you should avoid doing this. -------------------------------------------------------------------------------- /Week 01/Week 1B/Example Codes/Lecture02-01.py: -------------------------------------------------------------------------------- 1 | def greet(friend, money): 2 | if friend and (money > 20): 3 | print "Hi!" 4 | money = money - 20 5 | elif friend: 6 | print "Hello" 7 | else: 8 | print "Ha ha" 9 | money = money + 10 10 | return money 11 | 12 | 13 | money = 15 14 | 15 | money = greet(True, money) 16 | print "Money:", money 17 | print "" 18 | 19 | money = greet(False, money) 20 | print "Money:", money 21 | print "" 22 | 23 | money = greet(True, money) 24 | print "Money:", money 25 | print "" -------------------------------------------------------------------------------- /Week 03/Week 3A/Lecture Codes/Lecture02-1.py: -------------------------------------------------------------------------------- 1 | ### String Processing 2 | 3 | # String literals 4 | s1 = "Rixner's funny" 5 | s2 = 'Warren wears nice ties!' 6 | s3 = " t-shirts!" 7 | #print s1, s2 8 | #print s3 9 | 10 | # Combining strings 11 | a = ' and ' 12 | s4 = "Warren" + a + "Rixner" + ' are nuts!' 13 | print s4 14 | 15 | # Characters and slices 16 | print s1[3] 17 | print len(s1) 18 | print s1[0:6] + s2[6:] 19 | print s2[:13] + s1[9:] + s3 20 | 21 | # Converting strings 22 | s5 = str(375) 23 | print s5[1:] 24 | i1 = int(s5[1:]) 25 | print i1 + 38 26 | -------------------------------------------------------------------------------- /Week 08/Week 8 B/Lecture Quiz/Lecture 02.md: -------------------------------------------------------------------------------- 1 | Lecture 02 Quiz 2 | =============== 3 | 4 | Question 5 | -------- 6 | What does the following code print? 7 | 8 | ```python 9 | s = set([1, 2, 3]) 10 | t = set([2, 3, 4]) 11 | r = s 12 | s.intersection_update(t) 13 | q = s.union(r) 14 | print q 15 | ``` 16 | 17 | ### Answer 18 | * `set([2, 3])` 19 | 20 | #### Explanation 21 | Remember that r = s results in r and s referring to the same set. Also, remember that intersection_update mutates the set and union leaves the set unchanged while returning a new set. -------------------------------------------------------------------------------- /Week 01/Week 1B/Lecture Quiz/Lecture01.md: -------------------------------------------------------------------------------- 1 | Quiz 2 | ==== 3 | 4 | Question 1 5 | ---------- 6 | 7 | Which of the following expressions evaluate to True? 8 | 9 | ### Answer 10 | 11 | not False 12 | True or False 13 | False or (not False) 14 | 15 | Question 2 16 | ---------- 17 | 18 | Let x have the value 3. What gets printed as a result of running the following Python code? 19 | print x = 3 20 | 21 | ### Answer 22 | 23 | CodeSkulptor throws an error 24 | 25 | ### Explanation 26 | 27 | Note that x = 3 is an assignment, not a comparison. Use x == 3 instead. -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | # Auto detect text files and perform LF normalization 2 | * text=auto 3 | 4 | # Custom for Visual Studio 5 | *.cs diff=csharp 6 | *.sln merge=union 7 | *.csproj merge=union 8 | *.vbproj merge=union 9 | *.fsproj merge=union 10 | *.dbproj merge=union 11 | 12 | # Standard to msysgit 13 | *.doc diff=astextplain 14 | *.DOC diff=astextplain 15 | *.docx diff=astextplain 16 | *.DOCX diff=astextplain 17 | *.dot diff=astextplain 18 | *.DOT diff=astextplain 19 | *.pdf diff=astextplain 20 | *.PDF diff=astextplain 21 | *.rtf diff=astextplain 22 | *.RTF diff=astextplain 23 | -------------------------------------------------------------------------------- /Week 04/Week 4 Quiz/Quiz 4A Codes.py: -------------------------------------------------------------------------------- 1 | import math 2 | 3 | # Question 1 4 | list1 = [0, 1, 2, 3, 4, 5] 5 | print sum(list1) 6 | 7 | # Question 2, 3, 4 8 | my_list = ["This", "course", "is", "great"] 9 | print len(my_list) 10 | print my_list[3] 11 | print my_list[1:3] 12 | print my_list[0 : len(my_list) // 2] 13 | print my_list[len(my_list) // 2 : len(my_list)] 14 | print my_list[: len(my_list) // 2] 15 | print my_list[len(my_list) // 2 :] 16 | 17 | # Question 5 18 | point1 = [4, 7] 19 | point2 = [2, 9] 20 | distance = math.sqrt(((point2[0]-point1[0])**2) + ((point2[1]-point1[1])**2)) 21 | print distance -------------------------------------------------------------------------------- /Week 01/Week 1B/Example Codes/Lecture01.py: -------------------------------------------------------------------------------- 1 | a = True 2 | b = False 3 | c = True 4 | d = False 5 | 6 | print a 7 | print b 8 | 9 | print "-----------------------" 10 | 11 | print not a 12 | print a and b 13 | print a or b 14 | 15 | print "-----------------------" 16 | 17 | print (a and b) or (c and (not d)) 18 | 19 | # Comparison Operators 20 | # > 21 | # < 22 | # >= 23 | # <= 24 | # == 25 | # != 26 | 27 | a = 7 > 3 28 | print a 29 | 30 | x = 5 31 | y = 5 32 | b = x > y 33 | print b 34 | 35 | c = "Hello" == 'Hello' 36 | print c 37 | 38 | d = 20.6 <= 18.3 39 | print d 40 | 41 | print (a and b) or (c and (not d)) -------------------------------------------------------------------------------- /Week 08/Week 8 A/Example Codes/Lecture 01-1.py: -------------------------------------------------------------------------------- 1 | # Examples of Sets 2 | 3 | instructors = set(['Rixner', 'Warren', 'Greiner', 'Wong']) 4 | print instructors 5 | 6 | inst2 = set(['Rixner', 'Rixner', 'Warren', 'Warren', 'Greiner', 'Wong']) 7 | print inst2 8 | 9 | print instructors == inst2 10 | 11 | for inst in instructors: 12 | print inst 13 | 14 | instructors.add('Colbert') 15 | print instructors 16 | instructors.add('Rixner') 17 | print instructors 18 | 19 | instructors.remove('Wong') 20 | print instructors 21 | #instructors.remove('Wong') 22 | #print instructors 23 | 24 | print 'Rixner' in instructors 25 | print 'Wong' in instructors -------------------------------------------------------------------------------- /Week 06/Week 6 A/Lecture Quiz/Lecture 01.md: -------------------------------------------------------------------------------- 1 | Lecture 01 Quiz 2 | =============== 3 | 4 | Question 5 | -------- 6 | Which of the following statements will correctly create an object of type `Rice` and assign it to the variable `owls`? The `__init__` method of the class `Rice` takes two arguments: `self` and `greeting`. 7 | 8 | ### Answer 9 | * `owls = Rice("hoot")` 10 | 11 | #### Explanation 12 | The class name (`Rice`) acts like a function to create objects of that type. You do not pass the first argument (`self`) to this function, as Python does that for you. The initializer (`__init__`) always returns the new object, which you can then assign to a variable. -------------------------------------------------------------------------------- /Week 06/Week 6 B/Lecture Quiz/Lecture 01.md: -------------------------------------------------------------------------------- 1 | Lecture 01 Quiz 2 | =============== 3 | 4 | Question 5 | -------- 6 | What information do you need to draw a single image from a tiled image? 7 | 8 | ### Answer 9 | * The size (width and height) of each image and how the images are arranged in the tiled image. 10 | 11 | #### Explanation 12 | Note that given the size of each image, you can compute the center of the upper left image easily. If you knew the center of every image within the tiled image, you could use that, but you can also compute that information given the size of a single image and the layout of the tiled image (assuming all images are the same size). -------------------------------------------------------------------------------- /Week 06/Week 6 A/Lecture Quiz/Lecture 03.md: -------------------------------------------------------------------------------- 1 | Lecture 03 Quiz 2 | =============== 3 | 4 | Question 5 | -------- 6 | If particle is a Python list, what will happen if you execute the following line of Python in the draw handler: 7 | `particle.draw(canvas)` 8 | 9 | ### Answer 10 | * You will get an AttributeError because list does not have a draw method. 11 | 12 | #### Explanation 13 | Remember that if you try to call a method and get an AttributeError you should check the type of the object (using type()) to make sure it is the type of object you think it is. Unfortunately, Python cannot read your mind and convert objects from one type to the type you want them to have. -------------------------------------------------------------------------------- /Week 06/Week 6 A/Lecture Quiz/Lecture 04.md: -------------------------------------------------------------------------------- 1 | Lecture 04 Quiz 2 | =============== 3 | 4 | Question 5 | -------- 6 | Why should a blackjack hand and a deck of cards be implemented as two different classes? 7 | 8 | ### Answer 9 | * They each have different behaviors. 10 | * You might reuse the deck class in a different card game. The hand is specific to blackjack. 11 | 12 | #### Explanation 13 | There are no hard and fast rules about what should and should not be implemented as a class. You need to think about how you are going to use (and reuse) the code that you are writing. When designing a class, you need to think about both the data and the behaviors (methods) the class will have. -------------------------------------------------------------------------------- /Week 04/Week 4A/Lecture Quizzes/Lecture03.md: -------------------------------------------------------------------------------- 1 | Quiz 2 | ==== 3 | 4 | Question 5 | -------- 6 | 7 | Which of the following are valid operations on points and vectors? 8 | 9 | ### Answer 10 | 11 | Adding a vector to a point to get a new point. 12 | Subtracting two points to get a vector. 13 | 14 | ### Explanation 15 | 16 | The primary operation we will use on vectors and points is to add a vector to a point to get a new point. This is how we will move objects on the canvas from one point to another. Note that if you can add a vector to a point to get another point, then if you subtract two points, you should get a vector. You should never add two points together, this results in a meaningless value. -------------------------------------------------------------------------------- /Week 00/Week 0A/Lecture Quiz/Lecture3.md: -------------------------------------------------------------------------------- 1 | Quiz 2 | ==== 3 | 4 | Question 1 5 | ---------- 6 | 7 | In Python, what function converts a number (or string) into an integer? 8 | 9 | ### Answer 10 | 11 | The function int() 12 | 13 | ### Explanation 14 | 15 | The function int() converts to an integer, the function float() converts to a floating point number and the function str() converts to string. 16 | 17 | Question 2 18 | ---------- 19 | 20 | In Python 2 (the version of Python that we are learning), what is the value of -9 / 4? 21 | 22 | ### Answer 23 | 24 | -3 25 | 26 | ### Explanation 27 | 28 | Remember that in Python 2, the result of dividing two integers is another integer. (The exact answer rounded down to the nearest integer.) -------------------------------------------------------------------------------- /Week 02/Week 2A/Example Codes/Lecture03.py: -------------------------------------------------------------------------------- 1 | # SimpleGUI program template 2 | 3 | # Import the module 4 | import simplegui 5 | 6 | # Define global variables (program state) 7 | counter = 0; 8 | 9 | # Define "helper" functions 10 | def increment(): 11 | global counter 12 | counter = counter + 1 13 | 14 | # Define event handler functions 15 | def tick(): 16 | increment() 17 | print counter 18 | 19 | def buttonpress(): 20 | global counter 21 | counter = 0 22 | 23 | # Create a frame 24 | frame = simplegui.create_frame("Simple GUI Test", 100, 100) 25 | 26 | # Register event handlers 27 | timer = simplegui.create_timer(1000, tick) 28 | frame.add_button("Click Me to Reset the Timer!!!", buttonpress) 29 | 30 | # Start frame and timers 31 | frame.start() 32 | timer.start() -------------------------------------------------------------------------------- /Week 06/Week 6 A/Example Codes/Lecture 01.py: -------------------------------------------------------------------------------- 1 | class Character: 2 | def __init__(self, name, initial_health): 3 | self.name = name 4 | self.health = initial_health 5 | self.inventory = [] 6 | 7 | def __str__(self): 8 | s = "Name: " + self.name 9 | s += " Health: " + str(self.health) 10 | s += " Inventory: " + str(self.inventory) 11 | return s 12 | 13 | def grab(self, item): 14 | self.inventory.append(item) 15 | 16 | def get_health(self): 17 | return self.health 18 | 19 | def example(): 20 | me = Character("Bob", 20) 21 | print str(me) 22 | me.grab("pencil") 23 | me.grab("paper") 24 | print str(me) 25 | print "Health:", me.get_health() 26 | 27 | example() 28 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Windows image file caches 2 | Thumbs.db 3 | ehthumbs.db 4 | 5 | # Folder config file 6 | Desktop.ini 7 | 8 | # Recycle Bin used on file shares 9 | $RECYCLE.BIN/ 10 | 11 | # Windows Installer files 12 | *.cab 13 | *.msi 14 | *.msm 15 | *.msp 16 | 17 | # ========================= 18 | # Operating System Files 19 | # ========================= 20 | 21 | # OSX 22 | # ========================= 23 | 24 | .DS_Store 25 | .AppleDouble 26 | .LSOverride 27 | 28 | # Icon must end with two \r 29 | Icon 30 | 31 | # Thumbnails 32 | ._* 33 | 34 | # Files that might appear on external disk 35 | .Spotlight-V100 36 | .Trashes 37 | 38 | # Directories potentially created on remote AFP share 39 | .AppleDB 40 | .AppleDesktop 41 | Network Trash Folder 42 | Temporary Items 43 | .apdisk 44 | -------------------------------------------------------------------------------- /Week 05/Week 5 Quiz/Week 5B Python Codes.py: -------------------------------------------------------------------------------- 1 | # Question 7 2 | def is_even(number): 3 | """Returns whether the number is even.""" 4 | return number % 2 == 0 5 | def even_numbers(my_list): 6 | return [n for n in my_list if is_even(n)] 7 | print even_numbers([1, 3, 4, 5, 8, 9, 10, 11, 13, 12, 78]) 8 | 9 | # Question 9 10 | import simplegui 11 | image = simplegui.load_image("http://commondatastorage.googleapis.com/codeskulptor-assets/alphatest.png") 12 | frame_size = [300, 300] 13 | image_size = [380, 287] 14 | def draw(canvas): 15 | canvas.draw_image(image, [220, 100], [100, 100], 16 | [frame_size[0] / 2, frame_size[1] / 2], 17 | frame_size) 18 | frame = simplegui.create_frame("test", frame_size[0], frame_size[1]) 19 | frame.set_draw_handler(draw) 20 | frame.start() -------------------------------------------------------------------------------- /Week 06/Week 6 A/Lecture Quiz/Lecture 02.md: -------------------------------------------------------------------------------- 1 | Lecture 02 Quiz 2 | =============== 3 | 4 | Question 5 | -------- 6 | What code would you need to write in order to extend the example of this lecture so that the ball would bounce around inside an oval? 7 | 8 | ### Answer 9 | * You would need to write a class `OvalDomain` with the same methods as `RectangularDomain` and create an object of type `OvalDomain` to pass to the ball as its domain. 10 | 11 | #### Explanation 12 | Remember that one of the key benefits of object-oriented programming is that you can encapsulate behaviors. The ball doesn't need to know how the domain works. And the domain doesn't need to know how the ball works. So, you can write new domain types (or ball types) without having to change (or know about) any of the code in the other class' methods. -------------------------------------------------------------------------------- /Week 02/Week 2B/Lecture Quiz/Lecture04.md: -------------------------------------------------------------------------------- 1 | Quiz 2 | ==== 3 | 4 | Question 1 5 | ---------- 6 | 7 | What does this program print? 8 | 9 | a = 42 10 | def f(): 11 |     a = 27 12 |     return a 13 | b = f() 14 | print a 15 | 16 | ### Answer 17 | 18 | 42 19 | 20 | ### Explanation 21 | 22 | The variable a is not declared global in f, so it does not affect the global a. 23 | 24 | Question 2 25 | ---------- 26 | 27 | What does this program print? 28 | 29 | def f(x): 30 |     y = x + 3 31 | y = f(4) 32 | print y 33 | 34 | ### Answer 35 | 36 | None 37 | 38 | ### Explanation 39 | 40 | There is no return statement, so f returns None. 41 | 42 | Question 3 43 | ---------- 44 | 45 | Which expressions are the same as: 46 | 47 | a or b and c 48 | 49 | ### Answer 50 | 51 | a or (b and c) 52 | b and c or a -------------------------------------------------------------------------------- /Week 02/Week 2A/Lecture Quiz/Lecture01.md: -------------------------------------------------------------------------------- 1 | Types of Events 2 | =============== 3 | 4 | ## Input 5 |         Button 6 |         Textbox 7 | ## Keyboard 8 |         Key Up 9 |         Key Down 10 | ## Mouse 11 |         Click 12 |         Drag 13 | ## Timer 14 | 15 | Quiz 16 | ==== 17 | 18 | Question 1 19 | ---------- 20 | 21 | What happens if you press a key and click the mouse at exactly the same time? 22 | 23 | ### Answer 24 | 25 | One of the event handlers executes and the other waits in the event queue until the first handler finishes. 26 | 27 | ### Explanation 28 | 29 | You can't control the order that the system inserts events into the event queue and only one event handler executes at a time. -------------------------------------------------------------------------------- /Week 04/Week 4A/Lecture Codes/Lecture03.py: -------------------------------------------------------------------------------- 1 | # Ball motion with an explicit timer 2 | 3 | import simplegui 4 | 5 | # Initialize globals 6 | WIDTH = 600 7 | HEIGHT = 400 8 | BALL_RADIUS = 20 9 | 10 | init_pos = [WIDTH / 2, HEIGHT / 2] 11 | vel = [0, 3] # pixels per tick 12 | time = 0 13 | 14 | # define event handlers 15 | def tick(): 16 | global time 17 | time = time + 1 18 | 19 | def draw(canvas): 20 | # create a list to hold ball position 21 | ball_pos = [0, 0] 22 | 23 | # calculate ball position 24 | ball_pos[0] = init_pos[0] + time * vel[0] 25 | ball_pos[1] = init_pos[1] + time * vel[1] 26 | 27 | # draw ball 28 | canvas.draw_circle(ball_pos, BALL_RADIUS, 2, "Red", "White") 29 | 30 | # create frame 31 | frame = simplegui.create_frame("Motion", WIDTH, HEIGHT) 32 | 33 | # register event handlers 34 | frame.set_draw_handler(draw) 35 | 36 | timer = simplegui.create_timer(100, tick) 37 | 38 | # start frame 39 | frame.start() 40 | timer.start() 41 | -------------------------------------------------------------------------------- /Week 04/Week 4A/Lecture Codes/Lecture02-1.py: -------------------------------------------------------------------------------- 1 | # Keyboard echo 2 | 3 | import simplegui 4 | 5 | # initialize state 6 | current_key = ' ' 7 | 8 | # event handlers 9 | def keydown(key): 10 | global current_key 11 | current_key = chr(key) 12 | 13 | def keyup(key): 14 | global current_key 15 | current_key = ' ' 16 | 17 | def draw(c): 18 | # NOTE draw_text now throws an error on some non-printable characters 19 | # Since keydown event key codes do not all map directly to 20 | # the printable character via ord(), this example now restricts 21 | # keys to alphanumerics 22 | 23 | if current_key in "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789": 24 | c.draw_text(current_key, [10, 25], 20, "Red") 25 | 26 | # create frame 27 | f = simplegui.create_frame("Echo", 35, 35) 28 | 29 | # register event handlers 30 | f.set_keydown_handler(keydown) 31 | f.set_keyup_handler(keyup) 32 | f.set_draw_handler(draw) 33 | 34 | # start frame 35 | f.start() -------------------------------------------------------------------------------- /Week 04/Week 4A/Lecture Codes/Lecture02-2.py: -------------------------------------------------------------------------------- 1 | # control the position of a ball using the arrow keys 2 | 3 | import simplegui 4 | 5 | # Initialize globals 6 | WIDTH = 600 7 | HEIGHT = 400 8 | BALL_RADIUS = 20 9 | 10 | ball_pos = [WIDTH / 2, HEIGHT / 2] 11 | 12 | # define event handlers 13 | def draw(canvas): 14 | canvas.draw_circle(ball_pos, BALL_RADIUS, 2, "Red", "White") 15 | 16 | def keydown(key): 17 | vel = 4 18 | if key == simplegui.KEY_MAP["left"]: 19 | ball_pos[0] -= vel 20 | elif key == simplegui.KEY_MAP["right"]: 21 | ball_pos[0] += vel 22 | elif key == simplegui.KEY_MAP["down"]: 23 | ball_pos[1] += vel 24 | elif key == simplegui.KEY_MAP["up"]: 25 | ball_pos[1] -= vel 26 | 27 | # create frame 28 | frame = simplegui.create_frame("Positional ball control", WIDTH, HEIGHT) 29 | 30 | # register event handlers 31 | frame.set_draw_handler(draw) 32 | frame.set_keydown_handler(keydown) 33 | 34 | # start frame 35 | frame.start() 36 | -------------------------------------------------------------------------------- /Week 04/Week 4B/Lecture Codes/Lecture01-1.py: -------------------------------------------------------------------------------- 1 | # control the position of a ball using the arrow keys 2 | 3 | import simplegui 4 | 5 | # Initialize globals 6 | WIDTH = 600 7 | HEIGHT = 400 8 | BALL_RADIUS = 20 9 | 10 | ball_pos = [WIDTH / 2, HEIGHT / 2] 11 | 12 | # define event handlers 13 | def draw(canvas): 14 | canvas.draw_circle(ball_pos, BALL_RADIUS, 2, "Red", "White") 15 | 16 | def keydown(key): 17 | vel = 4 18 | if key == simplegui.KEY_MAP["left"]: 19 | ball_pos[0] -= vel 20 | elif key == simplegui.KEY_MAP["right"]: 21 | ball_pos[0] += vel 22 | elif key == simplegui.KEY_MAP["down"]: 23 | ball_pos[1] += vel 24 | elif key == simplegui.KEY_MAP["up"]: 25 | ball_pos[1] -= vel 26 | 27 | # create frame 28 | frame = simplegui.create_frame("Positional ball control", WIDTH, HEIGHT) 29 | 30 | # register event handlers 31 | frame.set_draw_handler(draw) 32 | frame.set_keydown_handler(keydown) 33 | 34 | # start frame 35 | frame.start() 36 | -------------------------------------------------------------------------------- /Week 03/Week 3B/Lecture Codes/Lecture01.py: -------------------------------------------------------------------------------- 1 | # Simple "screensaver" program. 2 | 3 | # Import modules 4 | import simplegui 5 | import random 6 | 7 | # Global state 8 | message = "Python is Fun!" 9 | position = [50, 50] 10 | width = 500 11 | height = 500 12 | interval = 2000 13 | 14 | # Handler for text box 15 | def update(text): 16 | global message 17 | message = text 18 | 19 | # Handler for timer 20 | def tick(): 21 | x = random.randrange(0, width) 22 | y = random.randrange(0, height) 23 | position[0] = x 24 | position[1] = y 25 | 26 | # Handler to draw on canvas 27 | def draw(canvas): 28 | canvas.draw_text(message, position, 36, "Red") 29 | 30 | # Create a frame 31 | frame = simplegui.create_frame("Home", width, height) 32 | 33 | # Register event handlers 34 | text = frame.add_input("Message:", update, 150) 35 | frame.set_draw_handler(draw) 36 | timer = simplegui.create_timer(interval, tick) 37 | 38 | # Start the frame animation 39 | frame.start() 40 | timer.start() 41 | -------------------------------------------------------------------------------- /Week 06/Week 6 A/Example Codes/Lecture 03-2.py: -------------------------------------------------------------------------------- 1 | # Testing template for Particle class 2 | 3 | 4 | ################################################### 5 | # Student should add code for the Particle class here 6 | 7 | 8 | 9 | ################################################### 10 | # Test code for the Particle class 11 | 12 | 13 | p = Particle([20, 20], "Red") 14 | print p 15 | print type(p) 16 | p.move([10, 20]) 17 | print p 18 | p.move([-15, -25]) 19 | print p 20 | print 21 | q = Particle([15, 30], "Green") 22 | print q 23 | print type(q) 24 | q.move([0, 0]) 25 | print q 26 | 27 | 28 | ################################################### 29 | # Output from test 30 | 31 | #Particle with position = [20, 20] and color = Red 32 | # 33 | #Particle with position = [30, 40] and color = Red 34 | #Particle with position = [15, 15] and color = Red 35 | # 36 | #Particle with position = [15, 30] and color = Green 37 | # 38 | #Particle with position = [15, 30] and color = Green 39 | -------------------------------------------------------------------------------- /Week 04/Week 4A/Lecture Codes/Lecture04.py: -------------------------------------------------------------------------------- 1 | import simplegui 2 | 3 | # Initialize globals 4 | WIDTH = 600 5 | HEIGHT = 400 6 | BALL_RADIUS = 20 7 | 8 | ball_pos = [WIDTH / 2, HEIGHT / 2] 9 | vel = [-4.0, 5.0] 10 | 11 | # define event handlers 12 | def draw(canvas): 13 | # Update ball position 14 | ball_pos[0] += vel[0] 15 | ball_pos[1] += vel[1] 16 | 17 | # collide and reflect off of all sides of canvas 18 | if ball_pos[0] <= BALL_RADIUS: 19 | vel[0] = - vel[0] 20 | if ball_pos[0] >= (WIDTH - 1) - BALL_RADIUS: 21 | vel[0] = - vel[0] 22 | if ball_pos[1] <= BALL_RADIUS: 23 | vel[1] = - vel[1] 24 | if ball_pos[1] >= (HEIGHT - 1) - BALL_RADIUS: 25 | vel[1] = - vel[1] 26 | 27 | 28 | # Draw ball 29 | canvas.draw_circle(ball_pos, BALL_RADIUS, 2, "Red", "White") 30 | 31 | # create frame 32 | frame = simplegui.create_frame("Ball physics", WIDTH, HEIGHT) 33 | 34 | # register event handlers 35 | frame.set_draw_handler(draw) 36 | 37 | # start frame 38 | frame.start() 39 | -------------------------------------------------------------------------------- /Week 03/Week 3B/Lecture Codes/Lecture03-2.py: -------------------------------------------------------------------------------- 1 | import simplegui 2 | 3 | ##################### 4 | # Buggy code -- doesn't start frame 5 | 6 | message = "Welcome!" 7 | 8 | def click(): 9 | """Change message on mouse click.""" 10 | global message 11 | message = "Good job!" 12 | 13 | def draw(canvas): 14 | """Draw message.""" 15 | canvas.draw_text(message, [50,112], 36, "Red") 16 | 17 | # Create a frame and assign callbacks to event handlers 18 | 19 | frame = simplegui.create_frame("Home", 300, 200) 20 | frame.add_button("Click me", click) 21 | frame.set_draw_handler(draw) 22 | 23 | # Don't forget to start the frame 24 | frame.start() 25 | 26 | 27 | ##################### 28 | # Buggy code -- doesn't start timers 29 | 30 | def timer1_handler(): 31 | print "1" 32 | 33 | def timer2_handler(): 34 | print "2" 35 | 36 | timer1 = simplegui.create_timer(100, timer1_handler) 37 | timer2 = simplegui.create_timer(300, timer2_handler) 38 | 39 | # Always remember to start the timers 40 | timer1.start() 41 | timer2.start() 42 | -------------------------------------------------------------------------------- /Week 03/Week 3A/Lecture Codes/Lecture02-3.py: -------------------------------------------------------------------------------- 1 | # Handle single quantity 2 | def convert_units(val, name): 3 | result = str(val) + " " + name 4 | if val > 1: 5 | result = result + "s" 6 | return result 7 | 8 | # convert xx.yy to xx dollars and yy cents 9 | def convert(val): 10 | # Split into dollars and cents 11 | dollars = int(val) 12 | cents = int(round(100 * (val - dollars))) 13 | 14 | # Convert to strings 15 | dollars_string = convert_units(dollars, "dollar") 16 | cents_string = convert_units(cents, "cent") 17 | 18 | # return composite string 19 | if dollars == 0 and cents == 0: 20 | return "Broke!" 21 | elif dollars == 0: 22 | return cents_string 23 | elif cents == 0: 24 | return dollars_string 25 | else: 26 | return dollars_string + " and " + cents_string 27 | 28 | 29 | # Tests 30 | print convert(11.23) 31 | print convert(11.20) 32 | print convert(1.12) 33 | print convert(12.01) 34 | print convert(1.01) 35 | print convert(0.01) 36 | print convert(1.00) 37 | print convert(0) -------------------------------------------------------------------------------- /Week 03/Week 3A/Lecture Codes/Lecture01-2.py: -------------------------------------------------------------------------------- 1 | # example of drawing operations in simplegui 2 | # standard HMTL color such as "Red" and "Green" 3 | # note later drawing operations overwrite earlier drawing operations 4 | 5 | import simplegui 6 | 7 | 8 | # Handler to draw on canvas 9 | def draw(canvas): 10 | canvas.draw_circle([100, 100], 50, 2, "Red", "Pink") 11 | canvas.draw_circle([300, 300], 50, 2, "Red", "Pink") 12 | canvas.draw_line([100, 100],[300, 300], 2, "Black") 13 | canvas.draw_circle([100, 300], 50, 2, "Green", "Lime") 14 | canvas.draw_circle([300, 100], 50, 2, "Green", "Lime") 15 | canvas.draw_line([100, 300],[300, 100], 2, "Black") 16 | canvas.draw_polygon([[150, 150], [250, 150], [250, 250], [150, 250]], 2, 17 | "Blue", "Aqua") 18 | canvas.draw_text("An example of drawing", [60, 385], 24, "Black") 19 | 20 | 21 | # Create a frame and assign callbacks to event handlers 22 | frame = simplegui.create_frame("Home", 400, 400) 23 | frame.set_draw_handler(draw) 24 | frame.set_canvas_background("Yellow") 25 | 26 | 27 | # Start the frame animation 28 | frame.start() 29 | -------------------------------------------------------------------------------- /Week 04/Week 4B/Lecture Codes/Lecture01-2.py: -------------------------------------------------------------------------------- 1 | # control the velocity of a ball using the arrow keys 2 | 3 | import simplegui 4 | 5 | # Initialize globals 6 | WIDTH = 600 7 | HEIGHT = 400 8 | BALL_RADIUS = 20 9 | 10 | ball_pos = [WIDTH / 2, HEIGHT / 2] 11 | vel = [0, 0] 12 | 13 | # define event handlers 14 | def draw(canvas): 15 | # Update ball position 16 | ball_pos[0] += vel[0] 17 | ball_pos[1] += vel[1] 18 | 19 | # Draw ball 20 | canvas.draw_circle(ball_pos, BALL_RADIUS, 2, "Red", "White") 21 | 22 | def keydown(key): 23 | acc = 1 24 | if key==simplegui.KEY_MAP["left"]: 25 | vel[0] -= acc 26 | elif key==simplegui.KEY_MAP["right"]: 27 | vel[0] += acc 28 | elif key==simplegui.KEY_MAP["down"]: 29 | vel[1] += acc 30 | elif key==simplegui.KEY_MAP["up"]: 31 | vel[1] -= acc 32 | 33 | print ball_pos 34 | 35 | # create frame 36 | frame = simplegui.create_frame("Velocity ball control", WIDTH, HEIGHT) 37 | 38 | # register event handlers 39 | frame.set_draw_handler(draw) 40 | frame.set_keydown_handler(keydown) 41 | 42 | # start frame 43 | frame.start() 44 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2024 Utkarsh Ashok Pathrabe 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /Week 08/Week 8 B/Example Codes/Lecture 01-1.py: -------------------------------------------------------------------------------- 1 | # demo of animation using asteroid sprite sheet 2 | 3 | import simplegui 4 | 5 | # load 64 frame sprite sheer for asteroid - image source is opengameart, artist is warspawn 6 | ROCK_CENTER = [64, 64] 7 | ROCK_SIZE = [128, 128] 8 | ROCK_DIM = 64 9 | rock_image = simplegui.load_image("http://commondatastorage.googleapis.com/codeskulptor-assets/asteroid1.opengameart.warspawn.png") 10 | 11 | # global time for animation 12 | time = 0 13 | 14 | # draw handler 15 | def draw(canvas): 16 | global time 17 | current_rock_index = (time % ROCK_DIM) // 1 18 | current_rock_center = [ROCK_CENTER[0] + current_rock_index * ROCK_SIZE[0], ROCK_CENTER[1]] 19 | canvas.draw_image(rock_image, current_rock_center, ROCK_SIZE, ROCK_CENTER, ROCK_SIZE) 20 | time += 0.2 21 | 22 | # create frame and size frame based on 128x128 pixel sprite 23 | frame = simplegui.create_frame("Asteroid sprite", ROCK_SIZE[0], ROCK_SIZE[1]) 24 | 25 | # set draw handler and canvas background using custom HTML color 26 | frame.set_draw_handler(draw) 27 | frame.set_canvas_background("Blue") 28 | 29 | # start animation 30 | frame.start() -------------------------------------------------------------------------------- /Week 04/Week 4B/Lecture Codes/Lecture02.py: -------------------------------------------------------------------------------- 1 | ################################### 2 | # Mutation vs. assignment 3 | 4 | 5 | ################ 6 | # Look alike, but different 7 | 8 | a = [4, 5, 6] 9 | b = [4, 5, 6] 10 | print "Original a and b:", a, b 11 | print "Are they same thing?", a is b 12 | 13 | a[1] = 20 14 | print "New a and b:", a, b 15 | print 16 | 17 | ################ 18 | # Aliased 19 | 20 | c = [4, 5, 6] 21 | d = c 22 | print "Original c and d:", c, d 23 | print "Are they same thing?", c is d 24 | 25 | c[1] = 20 26 | print "New c and d:", c, d 27 | print 28 | 29 | ################ 30 | # Copied 31 | 32 | e = [4, 5, 6] 33 | f = list(e) 34 | print "Original e and f:", e, f 35 | print "Are they same thing?", e is f 36 | 37 | e[1] = 20 38 | print "New e and f:", e, f 39 | print 40 | 41 | 42 | ################################### 43 | # Interaction with globals 44 | 45 | 46 | a = [4, 5, 6] 47 | 48 | def mutate_part(x): 49 | a[1] = x 50 | 51 | def assign_whole(x): 52 | a = x 53 | 54 | def assign_whole_global(x): 55 | global a 56 | a = x 57 | 58 | mutate_part(100) 59 | print a 60 | 61 | assign_whole(200) 62 | print a 63 | 64 | assign_whole_global(300) 65 | print a -------------------------------------------------------------------------------- /Week 01/Week 1A/Example Codes/Lecture01.py: -------------------------------------------------------------------------------- 1 | # computes the area of a triangle 2 | def triangle_area(base, height): # header - ends in colon 3 | area = (1.0 / 2) * base * height # body - all of body is indented 4 | return area # body - return outputs value 5 | 6 | a1 = triangle_area(3, 8) 7 | print a1 8 | a2 = triangle_area(14, 2) 9 | print a2 10 | 11 | # converts fahrenheit to celsius 12 | def fahrenheit2celsius(fahrenheit): 13 | celsius = (5.0 / 9) * (fahrenheit - 32) 14 | return celsius 15 | 16 | # test!!! 17 | c1 = fahrenheit2celsius(32) 18 | c2 = fahrenheit2celsius(212) 19 | print c1, c2 20 | 21 | # converts fahrenheit to kelvin 22 | def fahrenheit2kelvin(fahrenheit): 23 | celsius = fahrenheit2celsius(fahrenheit) 24 | kelvin = celsius + 273.15 25 | return kelvin 26 | 27 | # test!!! 28 | k1 = fahrenheit2kelvin(32) 29 | k2 = fahrenheit2kelvin(212) 30 | print k1, k2 31 | 32 | # prints hello, world! 33 | def hello(): 34 | print "Hello, world!" 35 | 36 | # test!!! 37 | hello() # call to hello prints "Hello, world!" 38 | h = hello() # call to hello prints "Hello, world!" a second time 39 | print h # prints None since there was no return value -------------------------------------------------------------------------------- /Week 01/Week 1A/Example Codes/Lecture02.py: -------------------------------------------------------------------------------- 1 | # computes the area of a triangle 2 | def triangle_area(base, height): # header - ends in colon 3 | area = (1.0 / 2) * base * height # body - all of body is indented 4 | return area # body - return outputs value 5 | 6 | a1 = triangle_area(3, 8) 7 | print a1 8 | a2 = triangle_area(14, 2) 9 | print a2 10 | 11 | # converts fahrenheit to celsius 12 | def fahrenheit2celsius(fahrenheit): 13 | celsius = (5.0 / 9) * (fahrenheit - 32) 14 | return celsius 15 | 16 | # test!!! 17 | c1 = fahrenheit2celsius(32) 18 | c2 = fahrenheit2celsius(212) 19 | print c1, c2 20 | 21 | # converts fahrenheit to kelvin 22 | def fahrenheit2kelvin(fahrenheit): 23 | celsius = fahrenheit2celsius(fahrenheit) 24 | kelvin = celsius + 273.15 25 | return kelvin 26 | 27 | # test!!! 28 | k1 = fahrenheit2kelvin(32) 29 | k2 = fahrenheit2kelvin(212) 30 | print k1, k2 31 | 32 | # prints hello, world! 33 | def hello(): 34 | print "Hello, world!" 35 | 36 | # test!!! 37 | hello() # call to hello prints "Hello, world!" 38 | h = hello() # call to hello prints "Hello, world!" a second time 39 | print h # prints None since there was no return value -------------------------------------------------------------------------------- /Week 06/Week 6 B/Example Codes/Lecture 01.py: -------------------------------------------------------------------------------- 1 | # demo for drawing using tiled images 2 | 3 | import simplegui 4 | 5 | # define globals for cards 6 | RANKS = ('A', '2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K') 7 | SUITS = ('C', 'S', 'H', 'D') 8 | 9 | # card sprite - 950x392 10 | CARD_CENTER = (36.5, 49) 11 | CARD_SIZE = (73, 98) 12 | card_image = simplegui.load_image("http://commondatastorage.googleapis.com/codeskulptor-assets/cards.jfitz.png") 13 | 14 | 15 | 16 | # define card class 17 | class Card: 18 | def __init__(self, suit, rank): 19 | self.rank = rank 20 | self.suit = suit 21 | 22 | def draw(self, canvas, loc): 23 | i = RANKS.index(self.rank) 24 | j = SUITS.index(self.suit) 25 | card_pos = [CARD_CENTER[0] + i * CARD_SIZE[0], 26 | CARD_CENTER[1] + j * CARD_SIZE[1]] 27 | canvas.draw_image(card_image, card_pos, CARD_SIZE, loc, CARD_SIZE) 28 | 29 | # define draw handler 30 | def draw(canvas): 31 | one_card.draw(canvas, (155, 90)) 32 | 33 | # define frame and register draw handler 34 | frame = simplegui.create_frame("Card draw", 300, 200) 35 | frame.set_draw_handler(draw) 36 | 37 | # createa card 38 | one_card = Card('S', '6') 39 | 40 | frame.start() 41 | -------------------------------------------------------------------------------- /Week 06/Week 6 B/Example Codes/Lecture 03.py: -------------------------------------------------------------------------------- 1 | ################### 2 | # Broken code 3 | 4 | class ball: 5 | def ball(pos, rad): 6 | position = pos 7 | radius = rad 8 | return ball 9 | 10 | def get_position(): 11 | return position 12 | 13 | b = ball([0,0], 10) 14 | 15 | print get_position(b) 16 | 17 | 18 | 19 | ################### 20 | # Fixed code 21 | 22 | class Ball: 23 | def __init__(self, pos, rad): 24 | self.position = pos 25 | self.radius = rad 26 | 27 | def get_position(self): 28 | return self.position 29 | 30 | b = Ball([0,0], 10) 31 | 32 | print b.get_position() 33 | 34 | 35 | ################## 36 | # Example while 37 | 38 | def countdown(n): 39 | """Print the values from n to 0.""" 40 | 41 | i = n 42 | while i >= 0: 43 | print i 44 | i -= 1 45 | 46 | countdown(5) 47 | 48 | 49 | ################## 50 | # Collatz 51 | 52 | def collatz(n): 53 | """Prints the values in the Collatz sequence for n.""" 54 | 55 | i = n 56 | while i > 1: 57 | print i 58 | 59 | if i % 2 == 0: 60 | i = i / 2 61 | else: 62 | i = 3 * i + 1 63 | 64 | colnatz(1000) 65 | 66 | 67 | ################# 68 | # Timeout 69 | 70 | i = 1 71 | while i > 0: 72 | i += 1 73 | 74 | print "Done!" 75 | -------------------------------------------------------------------------------- /Week 08/Week 8 B/Example Codes/Lecture 01-2.py: -------------------------------------------------------------------------------- 1 | # animation of explosion using 2D sprite sheet 2 | 3 | import simplegui 4 | 5 | # load 81 frame sprite sheer for explosion - image generated by phaedy explosion generator, source is hasgraphics.com 6 | EXPLOSION_CENTER = [50, 50] 7 | EXPLOSION_SIZE = [100, 100] 8 | EXPLOSION_DIM = [9, 9] 9 | explosion_image = simplegui.load_image("http://commondatastorage.googleapis.com/codeskulptor-assets/explosion.hasgraphics.png") 10 | 11 | # create timer that iterates current_sprite_center through sprite 12 | time = 0 13 | 14 | # define draw handler 15 | def draw(canvas): 16 | global time 17 | explosion_index = [time % EXPLOSION_DIM[0], (time // EXPLOSION_DIM[0]) % EXPLOSION_DIM[1]] 18 | canvas.draw_image(explosion_image, 19 | [EXPLOSION_CENTER[0] + explosion_index[0] * EXPLOSION_SIZE[0], 20 | EXPLOSION_CENTER[1] + explosion_index[1] * EXPLOSION_SIZE[1]], 21 | EXPLOSION_SIZE, EXPLOSION_CENTER, EXPLOSION_SIZE) 22 | time += 1 23 | 24 | 25 | # create frame and size frame based on 100x100 pixel sprite 26 | f = simplegui.create_frame("Asteroid sprite", EXPLOSION_SIZE[0], EXPLOSION_SIZE[1]) 27 | 28 | # set draw handler and canvas background using custom HTML color 29 | f.set_draw_handler(draw) 30 | f.set_canvas_background("Blue") 31 | 32 | # start animation 33 | f.start() -------------------------------------------------------------------------------- /Week 05/Week 5 Quiz/Week 5A Python Codes.py: -------------------------------------------------------------------------------- 1 | import random 2 | 3 | # Question 2 4 | my_list = [1, 2, 3, 4, 5] 5 | #my_list.extend([10, 20]) 6 | #my_list.reverse() 7 | #my_list + [10, 20] 8 | my_list.append(10) 9 | print my_list 10 | 11 | # Question 3 12 | fruits = ["apple", "pear", "blueberry"] 13 | fruit = fruits.pop(0) 14 | print fruit, fruits 15 | 16 | # Question 4 17 | print range(2, 15, 3) 18 | print range(14, 1, -3) 19 | print range(2, 15)*3 20 | 21 | # Question 6 22 | def reverse_string(s): 23 | result = "" 24 | for char in s: 25 | result = char + result 26 | return result 27 | print reverse_string("hello") 28 | 29 | # Question 7 30 | def random_point(): 31 | return (random.randrange(100), random.randrange(100)) 32 | def starting_points(players): 33 | points = [] 34 | for player in players: 35 | point = random_point() 36 | points.append(point) 37 | return points 38 | print starting_points(['abhay', 'devashish', 'tina', 'walt']) 39 | 40 | # Question 8 41 | def is_ascending(numbers): 42 | for i in range(len(numbers) - 1): 43 | if numbers[i+1] < numbers[i]: 44 | return False 45 | return True 46 | print is_ascending([2, 6, 9, 12, 400]) 47 | print is_ascending([4, 8, 2, 13]) 48 | 49 | # Question 9 50 | list = [0, 1] 51 | i = 40 52 | while i > 0: 53 | list.append(list[-1]+list[-2]) 54 | i -= 1 55 | print list.pop() -------------------------------------------------------------------------------- /Week 02/Week 2B/Example Codes/Lecture01.py: -------------------------------------------------------------------------------- 1 | # calculator with all buttons 2 | 3 | import simplegui 4 | 5 | # intialize globals 6 | store = 12 7 | operand = 3 8 | 9 | 10 | # event handlers for calculator with a store and operand 11 | 12 | def output(): 13 | """prints contents of store and operand""" 14 | print "Store = ", store 15 | print "Operand = ", operand 16 | print "" 17 | 18 | def swap(): 19 | """ swap contents of store and operand""" 20 | global store, operand 21 | store, operand = operand, store 22 | output() 23 | 24 | def add(): 25 | """ add operand to store""" 26 | global store 27 | store = store + operand 28 | output() 29 | 30 | def sub(): 31 | """ subtract operand from store""" 32 | global store 33 | store = store - operand 34 | output() 35 | 36 | def mult(): 37 | """ multiply store by operand""" 38 | global store 39 | store = store * operand 40 | output() 41 | 42 | def div(): 43 | """ divide store by operand""" 44 | global store 45 | store = store / operand 46 | output() 47 | 48 | 49 | # create frame 50 | f = simplegui.create_frame("Calculator",300,300) 51 | 52 | # register event handlers 53 | f.add_button("Print", output, 100) 54 | f.add_button("Swap", swap, 100) 55 | f.add_button("Add", add, 100) 56 | f.add_button("Sub", sub, 100) 57 | f.add_button("Mult", mult, 100) 58 | f.add_button("Div", div, 100) 59 | 60 | 61 | # get frame rolling 62 | f.start() -------------------------------------------------------------------------------- /Week 03/Week 3A/Lecture Codes/Lecture03-1.py: -------------------------------------------------------------------------------- 1 | # interactive application to convert a float in dollars and cents 2 | 3 | import simplegui 4 | 5 | # define global value 6 | 7 | value = 3.12 8 | 9 | # Handle single quantity 10 | def convert_units(val, name): 11 | result = str(val) + " " + name 12 | if val > 1: 13 | result = result + "s" 14 | return result 15 | 16 | # convert xx.yy to xx dollars and yy cents 17 | def convert(val): 18 | # Split into dollars and cents 19 | dollars = int(val) 20 | cents = int(round(100 * (val - dollars))) 21 | 22 | # Convert to strings 23 | dollars_string = convert_units(dollars, "dollar") 24 | cents_string = convert_units(cents, "cent") 25 | 26 | # return composite string 27 | if dollars == 0 and cents == 0: 28 | return "Broke!" 29 | elif dollars == 0: 30 | return cents_string 31 | elif cents == 0: 32 | return dollars_string 33 | else: 34 | return dollars_string + " and " + cents_string 35 | 36 | 37 | # define draw handler 38 | def draw(canvas): 39 | canvas.draw_text(convert(value), [60, 110], 24, "White") 40 | 41 | 42 | # define an input field handler 43 | def input_handler(text): 44 | global value 45 | value = float(text) 46 | 47 | 48 | # create frame 49 | frame = simplegui.create_frame("Converter", 400, 200) 50 | 51 | # register event handlers 52 | frame.set_draw_handler(draw) 53 | frame.add_input("Enter value", input_handler, 100) 54 | 55 | 56 | # start frame 57 | frame.start() -------------------------------------------------------------------------------- /Week 03/Week 3B/Lecture Codes/Lecture03-1.py: -------------------------------------------------------------------------------- 1 | ##################### 2 | # Example of event-driven code, buggy version 3 | 4 | import simplegui 5 | 6 | size = 10 7 | radius = 10 8 | 9 | # Define event handlers. 10 | 11 | def incr_button_handler(): 12 | """Increment the size.""" 13 | global size 14 | size += 1 15 | label.set_text("Value: " + str(size)) 16 | 17 | def decr_button_handler(): 18 | """Decrement the size.""" 19 | global size 20 | # Insert check that size > 1, to make sure it stays positive 21 | # NOTE that this restriction has changed from the video 22 | # since draw_circle now throws an error if radius is zero 23 | if size > 1: 24 | size -= 1 25 | label.set_text("Value: " + str(size)) 26 | 27 | def change_circle_handler(): 28 | """Change the circle radius.""" 29 | global radius 30 | radius = size 31 | # Insert code to make radius label change. 32 | radius_label.set_text("Radius: " + str(radius)) 33 | 34 | def draw_handler(canvas): 35 | """Draw the circle.""" 36 | canvas.draw_circle((100, 100), radius, 5, "Red") 37 | 38 | # Create a frame and assign callbacks to event handlers. 39 | 40 | frame = simplegui.create_frame("Home", 200, 200) 41 | label = frame.add_label("Value: " + str(size)) 42 | frame.add_button("Increase", incr_button_handler) 43 | frame.add_button("Decrease", decr_button_handler) 44 | radius_label = frame.add_label("Radius: " + str(radius)) 45 | frame.add_button("Change circle", change_circle_handler) 46 | frame.set_draw_handler(draw_handler) 47 | 48 | # Start the frame animation 49 | 50 | frame.start() 51 | -------------------------------------------------------------------------------- /Week 01/Week 1A/Example Codes/Lecture03.py: -------------------------------------------------------------------------------- 1 | # Remainder - modular arithmetic 2 | 3 | # systematically restrict computation to a range 4 | # long division - divide by a number, we get a quotient plus a remainder 5 | # quotient is integer division //, the remainder is % (Docs) 6 | 7 | 8 | # problem - get the ones digit of a number 9 | num = 49 10 | tens = num // 10 11 | ones = num % 10 12 | print tens, ones 13 | print 10 * tens + ones, num 14 | 15 | 16 | 17 | 18 | 19 | # application - 24 hour clock 20 | # http://en.wikipedia.org/wiki/24-hour_clock 21 | 22 | hour = 20 23 | shift = 8 24 | print (hour + shift) % 24 25 | 26 | 27 | 28 | 29 | # application - screen wraparound 30 | # Spaceship from week seven 31 | 32 | width = 800 33 | position = 797 34 | move = 5 35 | position = (position + move) % width 36 | print position 37 | 38 | 39 | 40 | 41 | # Data conversion operations 42 | 43 | # convert an integer into string - str 44 | # convert an hour into 24-hour format "03:00", always print leading zero 45 | 46 | hour = 3 47 | ones = hour % 10 48 | tens = hour // 10 49 | print tens, ones, ":00" 50 | print str(tens), str(ones), ":00" 51 | print str(tens) + str(ones) + ":00" 52 | 53 | # convert a string into numbers using int and float 54 | 55 | 56 | 57 | # Python modules - extra functions implemented outside basic Python 58 | 59 | import simplegui # access to drawing operations for interactive applications 60 | 61 | import math # access to standard math functions, e.g; trig 62 | 63 | import random # functions to generate random numbers 64 | 65 | 66 | # look in Docs for useful functions 67 | 68 | print math.pi 69 | -------------------------------------------------------------------------------- /Week 06/Week 6 B/Example Codes/Lecture 02.py: -------------------------------------------------------------------------------- 1 | ################## 2 | # Object creation and use 3 | # Mutation with Aliasing 4 | 5 | class Point1: 6 | def __init__(self, x, y): 7 | self.x = x 8 | self.y = y 9 | 10 | def set_x(self, newx): 11 | self.x = newx 12 | 13 | def get_x(self): 14 | return self.x 15 | 16 | p = Point1(4, 5) 17 | q = Point1(4, 5) 18 | r = p 19 | 20 | p.set_x(10) 21 | 22 | print p.get_x() 23 | print q.get_x() 24 | print r.get_x() 25 | 26 | 27 | ################## 28 | # Object shared state 29 | # Mutation of shared state 30 | 31 | class Point2: 32 | def __init__(self, coordinates): 33 | self.coords = coordinates 34 | 35 | def set_coord(self, index, value): 36 | self.coords[index] = value 37 | 38 | def get_coord(self, index): 39 | return self.coords[index] 40 | 41 | coordinates = [4, 5] 42 | p = Point2(coordinates) 43 | q = Point2(coordinates) 44 | r = Point2([4, 5]) 45 | 46 | p.set_coord(0, 10) 47 | 48 | print p.get_coord(0) 49 | print q.get_coord(0) 50 | print r.get_coord(0) 51 | 52 | 53 | ################## 54 | # Objects not sharing state 55 | 56 | class Point3: 57 | def __init__(self, coordinates): 58 | self.coords = list(coordinates) 59 | 60 | def set_coord(self, index, value): 61 | self.coords[index] = value 62 | 63 | def get_coord(self, index): 64 | return self.coords[index] 65 | 66 | coordinates = [4, 5] 67 | p = Point3(coordinates) 68 | q = Point3(coordinates) 69 | r = Point3([4, 5]) 70 | 71 | p.set_coord(0, 10) 72 | 73 | print p.get_coord(0) 74 | print q.get_coord(0) 75 | print r.get_coord(0) -------------------------------------------------------------------------------- /Week 02/Week 2B/Example Codes/Lecture02.py: -------------------------------------------------------------------------------- 1 | # calculator with all buttons 2 | 3 | import simplegui 4 | 5 | # intialize globals 6 | store = 0 7 | operand = 0 8 | 9 | 10 | # event handlers for calculator with a store and operand 11 | 12 | def output(): 13 | """prints contents of store and operand""" 14 | print "Store = ", store 15 | print "Operand = ", operand 16 | print "" 17 | 18 | def swap(): 19 | """ swap contents of store and operand""" 20 | global store, operand 21 | store, operand = operand, store 22 | output() 23 | 24 | def add(): 25 | """ add operand to store""" 26 | global store 27 | store = store + operand 28 | output() 29 | 30 | def sub(): 31 | """ subtract operand from store""" 32 | global store 33 | store = store - operand 34 | output() 35 | 36 | def mult(): 37 | """ multiply store by operand""" 38 | global store 39 | store = store * operand 40 | output() 41 | 42 | def div(): 43 | """ divide store by operand""" 44 | global store 45 | store = store / operand 46 | output() 47 | 48 | def enter(t): 49 | """ enter a new operand""" 50 | global operand 51 | operand = float(t) 52 | output() 53 | 54 | # create frame 55 | f = simplegui.create_frame("Calculator",300,300) 56 | 57 | # register event handlers and create control elements 58 | f.add_button("Print", output, 100) 59 | f.add_button("Swap", swap, 100) 60 | f.add_button("Add", add, 100) 61 | f.add_button("Subtract", sub, 100) 62 | f.add_button("Multiply", mult, 100) 63 | f.add_button("Divide", div, 100) 64 | f.add_input("Enter an Operand:", enter, 100) 65 | 66 | 67 | # get frame rolling 68 | f.start() -------------------------------------------------------------------------------- /Week 00/Week 0B/Example Codes/Lecture1.py: -------------------------------------------------------------------------------- 1 | # variables - placeholders for important values 2 | # used to avoid recomputing values and to 3 | # give values names that help reader understand code 4 | 5 | 6 | # valid variable names - consists of letters, numbers, underscore (_) 7 | # starts with letter or underscore 8 | # case sensitive (capitalization matters) 9 | 10 | # legal names - ninja, Ninja, n_i_n_j_a 11 | # illegal names - 1337, 1337ninja 12 | 13 | # Python convention - multiple words joined by _ 14 | # legal names - elite_ninja, leet_ninja, ninja_1337 15 | # illegal name 1337_ninja 16 | 17 | 18 | 19 | # assign to variable name using single equal sign = 20 | # (remember that double equals == is used to test equality) 21 | 22 | # examples 23 | 24 | my_name = "Joe Warren" 25 | print my_name 26 | 27 | my_age = 51 28 | print my_age 29 | 30 | # birthday - add one 31 | 32 | #my_age += 1 33 | print my_age 34 | 35 | 36 | # the story of the magic pill 37 | 38 | magic_pill = 30 39 | print my_age - magic_pill 40 | 41 | my_grand_dad = 74 42 | 43 | print my_grand_dad - 2 * magic_pill 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | # Temperature examples 54 | 55 | # convert from Fahrenheit to Celsuis 56 | # c = 5 / 9 * (f - 32) 57 | # use explanatory names 58 | 59 | temp_Fahrenheit = 212 60 | 61 | temp_Celsius = 5.0 / 9.0 * (temp_Fahrenheit - 32) 62 | 63 | print temp_Celsius 64 | 65 | # test it! 32 Fahrenheit is 0 Celsius, 212 Fahrenheit is 100 Celsius 66 | 67 | 68 | # convert from Celsius to Fahrenheit 69 | # f = 9 / 5 * c + 32 70 | 71 | temp_Celsius = 100 72 | 73 | temp_Fahrenheit = 9.0 / 5.0 * temp_Celsius + 32 74 | 75 | print temp_Fahrenheit 76 | 77 | 78 | # test it! 79 | -------------------------------------------------------------------------------- /Week 06/Week 6 A/Example Codes/Lecture 03-1.py: -------------------------------------------------------------------------------- 1 | # Particle class example used to simulate diffusion of molecules 2 | 3 | import simplegui 4 | import random 5 | 6 | # global constants 7 | WIDTH = 600 8 | HEIGHT = 400 9 | PARTICLE_RADIUS = 5 10 | COLOR_LIST = ["Red", "Green", "Blue", "White"] 11 | DIRECTION_LIST = [[1,0], [0, 1], [-1, 0], [0, -1]] 12 | 13 | 14 | # definition of Particle class 15 | class Particle: 16 | 17 | # initializer for particles 18 | def __init__(self, position, color): 19 | self.position = position 20 | self.color = color 21 | 22 | # method that updates position of a particle 23 | def move(self, offset): 24 | self.position[0] += offset[0] 25 | self.position[1] += offset[1] 26 | 27 | # draw method for particles 28 | def draw(self, canvas): 29 | canvas.draw_circle(self.position, PARTICLE_RADIUS, 1, self.color, self.color) 30 | 31 | # string method for particles 32 | def __str__(self): 33 | return "Particle with position = " + str(self.position) + " and color = " + self.color 34 | 35 | 36 | # draw handler 37 | def draw(canvas): 38 | for p in particle_list: 39 | p.move(random.choice(DIRECTION_LIST)) 40 | 41 | for p in particle_list: 42 | p.draw(canvas) 43 | 44 | 45 | # create frame and register draw handler 46 | frame = simplegui.create_frame("Particle simulator", WIDTH, HEIGHT) 47 | frame.set_draw_handler(draw) 48 | 49 | # create a list of particles 50 | particle_list = [] 51 | for i in range(100): 52 | p = Particle([WIDTH / 2, HEIGHT / 2], random.choice(COLOR_LIST)) 53 | particle_list.append(p) 54 | 55 | # start frame 56 | frame.start() 57 | -------------------------------------------------------------------------------- /Week 02/Week 2A/Example Codes/Lecture02.py: -------------------------------------------------------------------------------- 1 | # global vs local examples 2 | 3 | # num1 is a global variable 4 | 5 | num1 = 1 6 | print num1 7 | 8 | # num2 is a local variable 9 | 10 | def fun(): 11 | num1 = 2 12 | num2 = num1 + 1 13 | print num2 14 | 15 | fun() 16 | 17 | 18 | # the scope of global num1 is the whole program, num 1 remains defined 19 | print num1 20 | 21 | # the scope of the variable num2 is fun(), num2 is now undefined 22 | # print num2 23 | 24 | 25 | # why use local variables? 26 | # give a descriptive name to a quantity 27 | # avoid computing something multiple times 28 | 29 | def fahren_to_kelvin(fahren): 30 | celsius = 5.0 / 9 * (fahren - 32) 31 | zero_celsius_in_kelvin = 273.15 32 | return celsius + zero_celsius_in_kelvin 33 | 34 | print fahren_to_kelvin(212) 35 | 36 | 37 | 38 | 39 | 40 | # the risk/reward of using global variables 41 | 42 | # risk - consider the software system for an airliner 43 | # critical piece - flight control system 44 | # non-critical piece - in-flight entertainment system 45 | 46 | # both systems might use a variable called "dial" 47 | # we don't want possibility that change the volume on your audio 48 | # causes the plane's flaps to change! 49 | 50 | 51 | 52 | # example 53 | num = 4 54 | 55 | def fun1(): 56 | global num 57 | num = 5 58 | 59 | def fun2(): 60 | global num 61 | num = 6 62 | 63 | # note that num changes after each call with no obvious explanation 64 | print num 65 | fun1() 66 | print num 67 | fun2() 68 | print num 69 | 70 | # global variables are an easy way for event handlers 71 | # to communicate game information. 72 | 73 | # safer method - but they required more sophisticated 74 | # object-programming techniques -------------------------------------------------------------------------------- /Week 03/Week 3 Assignment/Stopwatch - The Game.py: -------------------------------------------------------------------------------- 1 | # @ Author : Utkarsh Ashok Pathrabe 2 | 3 | # Implementation of "Stopwatch: The Game" 4 | import simplegui 5 | 6 | # define global variables 7 | IsRunning = False 8 | Counter, GoodStop, TotalStop = 0, 0, 0 9 | 10 | # define helper function format that converts time 11 | # in tenths of seconds into formatted string A:BC.D 12 | def format(t): 13 | D, t = t % 10, t / 10 14 | C, t = t % 10, t / 10 15 | B, A = t % 6, t / 6 16 | return str(A) + ":" + str(B) + str(C) + "." + str(D) 17 | 18 | # define helper function score that returns current score 19 | def score(): 20 | return str(GoodStop) + "/" + str(TotalStop) 21 | 22 | # define event handlers for buttons; "Start", "Stop", "Reset" 23 | def start(): 24 | global IsRunning 25 | timer.start() 26 | IsRunning = True 27 | 28 | def stop(): 29 | global IsRunning, GoodStop, TotalStop 30 | timer.stop() 31 | if IsRunning: 32 | TotalStop += 1 33 | if Counter % 10 == 0: 34 | GoodStop += 1 35 | IsRunning = False 36 | 37 | def reset(): 38 | global IsRunning, GoodStop, TotalStop, Counter 39 | timer.stop() 40 | IsRunning = False 41 | Counter, GoodStop, TotalStop = 0, 0, 0 42 | 43 | # define event handler for timer with 0.1 sec interval 44 | def tick(): 45 | global Counter 46 | Counter += 1 47 | 48 | # define draw handler 49 | def draw(canvas): 50 | canvas.draw_text(format(Counter), [60, 85], 36, "White") 51 | canvas.draw_text(score(), [155, 25], 26, "Green") 52 | 53 | # create frame 54 | frame = simplegui.create_frame("Stopwatch", 200, 150) 55 | 56 | # register event handlers 57 | frame.add_button("Start", start, 120) 58 | frame.add_button("Stop", stop, 120) 59 | frame.add_button("Reset", reset, 120) 60 | frame.set_draw_handler(draw) 61 | timer = simplegui.create_timer(100, tick) 62 | 63 | # start frame 64 | frame.start() -------------------------------------------------------------------------------- /Week 06/Week 6 Programming Assignment/Card Class Testing Template.py: -------------------------------------------------------------------------------- 1 | # Testing template for the Card class 2 | 3 | import random 4 | 5 | # define globals for cards 6 | SUITS = ['C', 'S', 'H', 'D'] 7 | RANKS = ['A', '2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K'] 8 | VALUES = {'A':1, '2':2, '3':3, '4':4, '5':5, '6':6, '7':7, '8':8, '9':9, 'T':10, 'J':10, 'Q':10, 'K':10} 9 | 10 | 11 | ################################################# 12 | # Student should insert the implementation of the Card class here 13 | class Card: 14 | def __init__(self, suit, rank): 15 | if (suit in SUITS) and (rank in RANKS): 16 | self.suit = suit 17 | self.rank = rank 18 | else: 19 | self.suit = None 20 | self.rank = None 21 | print "Invalid card: ", suit, rank 22 | 23 | def __str__(self): 24 | return self.suit + self.rank 25 | 26 | def get_suit(self): 27 | return self.suit 28 | 29 | def get_rank(self): 30 | return self.rank 31 | 32 | def draw(self, canvas, pos): 33 | card_loc = (CARD_CENTER[0] + CARD_SIZE[0] * RANKS.index(self.rank), 34 | CARD_CENTER[1] + CARD_SIZE[1] * SUITS.index(self.suit)) 35 | canvas.draw_image(card_images, card_loc, CARD_SIZE, [pos[0] + CARD_CENTER[0], pos[1] + CARD_CENTER[1]], CARD_SIZE) 36 | 37 | ################################################### 38 | # Test code 39 | 40 | c1 = Card("S", "A") 41 | print c1 42 | print c1.get_suit(), c1.get_rank() 43 | print type(c1) 44 | 45 | c2 = Card("C", "2") 46 | print c2 47 | print c2.get_suit(), c2.get_rank() 48 | print type(c2) 49 | 50 | c3 = Card("D", "T") 51 | print c3 52 | print c3.get_suit(), c3.get_rank() 53 | print type(c3) 54 | 55 | 56 | ################################################### 57 | # Output to console 58 | 59 | #SA 60 | #S A 61 | # 62 | #C2 63 | #C 2 64 | # 65 | #DT 66 | #D T 67 | # -------------------------------------------------------------------------------- /Week 01/Week 1B/Lecture Quiz/Lecture03.md: -------------------------------------------------------------------------------- 1 | Quiz 2 | ==== 3 | 4 | Question 1 5 | ---------- 6 | 7 | Which of the following can result in a NameError? 8 | 9 | ### Answer 10 | 11 | Misspelled variable name 12 | Misspelled function name 13 | Missing import statement 14 | 15 | ### Explanation 16 | 17 | Python doesn't check the spelling of a text string. However, disagreement between the definition and use of a variable or function name will cause a NameError. Failing to import a module will leave the functions in the module undefined and cause a NameError. 18 | 19 | Question 2 20 | ---------- 21 | 22 | Which of the following can result in a AttributeError? 23 | 24 | ### Answer 25 | 26 | Misspelled a constant or a call to a function in a module (the part after the period) 27 | 28 | ### Explanation 29 | 30 | For example, misspelling a constant or a call to a function in random or math will cause an AttributeError. 31 | 32 | Question 3 33 | ---------- 34 | 35 | Which of the following can result in a AttributeError? 36 | 37 | ### Answer 38 | 39 | Misspelled a constant or a call to a function in a module (the part after the period) 40 | 41 | ### Explanation 42 | 43 | For example, misspelling a constant or a call to a function in random or math will cause an AttributeError. 44 | 45 | Question 4 46 | ---------- 47 | 48 | Which of the following is the result of evaluating "5 - 2"? 49 | 50 | ### Answer 51 | 52 | "5 - 2" 53 | 54 | ### Explanation 55 | 56 | Remember that "5 - 2" is string since it is contained in double quotes. Evaluating a string just yields the string itself. Also, strings and numbers are different in Python. 57 | 58 | Question 5 59 | ---------- 60 | 61 | Which of the following results in a SyntaxError? 62 | 63 | ### Answer 64 | 65 | print 5 + / 2 66 | print x = y 67 | 68 | Question 6 69 | ---------- 70 | 71 | Where is the standard location to put a function's documentation string? 72 | 73 | ### Answer 74 | 75 | Immediately after the function's def, i.e., the first line of the function body 76 | 77 | ### Explanation 78 | 79 | While syntactically legal elsewhere, convention places it at the beginning of the function. -------------------------------------------------------------------------------- /Week 00/Week 0A/Example Codes/Lecture3.py: -------------------------------------------------------------------------------- 1 | # Arithmetic expressions - numbers, operators, expressions 2 | 3 | print 3, -1, 3.14159, -2.8 4 | 5 | # numbers - two types, an integer or a decimal number 6 | # two corresponding data types int() and float() 7 | 8 | print type(3), type(3.14159) 9 | print type(3.0) 10 | 11 | 12 | # we can convert between data types using int() and float() 13 | # note that int() takes the "whole" part of a decimal number and doesn't round 14 | # float() applied to integers is boring 15 | 16 | print int(3.14159), int(-2.8) 17 | print float(3), float(-1) 18 | 19 | 20 | # floating point number have around 15 decimal digits of accuracy 21 | # pi is 3.1415926535897932384626433832795028841971... 22 | # square root of two is 1.4142135623730950488016887242096980785696... 23 | 24 | # approximation of pi, Python displays 12 decimal digits 25 | 26 | print 3.1415926535897932384626433832795028841971 27 | 28 | # appoximation of square root of two, Python displays 12 decimal digits 29 | 30 | print 1.4142135623730950488016887242096980785696 31 | 32 | # arithmetic operators 33 | # + plus addition 34 | # - minus subtraction 35 | # * times multiplication 36 | # / divided by division 37 | # ** power exponentiation 38 | 39 | print 1 + 2, 3 - 4, 5 * 6, 2 ** 5 40 | 41 | # Division in Python 2 42 | # If one operand is a decimal (float), the answer is decimal 43 | 44 | print 1.0 / 3, 5.0 / 2.0, -7 / 3.0 45 | 46 | # If both operands are ints, the answer is an int (rounded down) 47 | 48 | print 1 / 3, 5 / 2, -7 / 3 49 | 50 | 51 | # expressions - number or a binary operator applied to two expressions 52 | # minus is also a unary operator and can be applied to a single expression 53 | 54 | print 1 + 2 * 3, 4.0 - 5.0 / 6.0, 7 * 8 + 9 * 10 55 | 56 | # expressions are entered as sequence of numbers and operations 57 | # how are the number and operators grouped to form expressions? 58 | # operator precedence - "please excuse my dear aunt sallie" = (), **, *, /, +,- 59 | 60 | print 1 * 2 + 3 * 4 61 | print 2 + 12 62 | 63 | 64 | # always manually group using parentheses when in doubt 65 | 66 | 67 | print 1 * (2 + 3) * 4 68 | print 1 * 5 * 4 -------------------------------------------------------------------------------- /Week 01/Week 1 Quiz/Quiz01.py: -------------------------------------------------------------------------------- 1 | # Question No 3 2 | def do_stuff(): 3 | print "Hello world" 4 | return "Is it over yet?" 5 | print "Goodbye cruel world!" 6 | 7 | print do_stuff() 8 | 9 | print "--------------------------------------------------" 10 | 11 | # Question No 4 12 | n = 123 13 | print (n % 100 - n % 10) / 10 14 | print ((n - n % 10) / 10) % 10 15 | print (n - n % 10) / 10 16 | 17 | print "--------------------------------------------------" 18 | 19 | # Question No 6 20 | import math 21 | 22 | def f(x): 23 | return (-5 * math.pow(x, 5)) + (69 * math.pow(x, 2)) - 47 24 | 25 | print f(0) 26 | print f(1) 27 | print f(2) 28 | print f(3) 29 | print max(f(0), f(1), f(2), f(3)) 30 | 31 | print "--------------------------------------------------" 32 | 33 | # Question No 7 34 | def future_value(present_value, annual_rate, periods_per_year, years): 35 | rate_per_period = annual_rate / periods_per_year 36 | periods = periods_per_year * years 37 | return present_value * math.pow(1 + rate_per_period, periods) 38 | 39 | print "$500 at 4% compounded daily for 10 years yields $", future_value(500, .04, 10, 10) 40 | print "$1000 at 2% compounded daily for 3 years yields $", future_value(1000, .02, 365, 3) 41 | 42 | print "--------------------------------------------------" 43 | 44 | # Question No 8 45 | def area_regular_polygon(no_of_sides, length_of_each_side): 46 | a = math.tan(math.pi / no_of_sides) 47 | b = (no_of_sides) * math.pow(length_of_each_side, 2) 48 | c = b / a 49 | return c / 4 50 | 51 | print area_regular_polygon(5, 7) 52 | print area_regular_polygon(7, 3) 53 | 54 | print "--------------------------------------------------" 55 | 56 | # Question No 9 57 | def max_of_2(a, b): 58 | if a > b: 59 | return a 60 | else: 61 | return b 62 | 63 | def max_of_3(a, b, c): 64 | return max_of_2(a, max_of_2(b, c)) 65 | 66 | print "--------------------------------------------------" 67 | 68 | # Question No 10 69 | def project_to_distance(point_x, point_y, distance): 70 | dist_to_origin = math.sqrt(point_x ** 2 + point_y ** 2) 71 | scale = distance / dist_to_origin 72 | print point_x * scale, point_y * scale 73 | 74 | project_to_distance(2, 7, 4) 75 | -------------------------------------------------------------------------------- /Week 02/Week 2 Mini Project/Guess a Number.py: -------------------------------------------------------------------------------- 1 | # template for "Guess the number" mini-project 2 | # input will come from buttons and an input field 3 | # all output for the game will be printed in the console 4 | 5 | # write import statements 6 | import math 7 | import random 8 | import simplegui 9 | 10 | # define global variables 11 | num_range = 100 12 | guesses_remaining = 0 13 | secret_number = 0 14 | 15 | # helper function to start and restart the game 16 | def new_game(): 17 | # initialize global variables used in your code here 18 | global num_range, guesses_remaining, secret_number 19 | guesses_remaining = int(math.ceil(math.log((num_range - 0), 2))) 20 | secret_number = random.randrange(0, num_range) 21 | print "\nNew game. Range is from 0 to", num_range 22 | print "Number of remaining guesses is", guesses_remaining 23 | 24 | # define event handlers for control panel 25 | def range100(): 26 | # button that changes the range to [0,100) and starts a new game 27 | global num_range 28 | num_range = 100 29 | new_game() 30 | 31 | def range1000(): 32 | # button that changes the range to [0,1000) and starts a new game 33 | global num_range 34 | num_range = 1000 35 | new_game() 36 | 37 | def input_guess(guess): 38 | global guesses_remaining 39 | print "\nGuess was", guess 40 | guess = int(guess) 41 | guesses_remaining -= 1 42 | print "Number of remaining guesses is", guesses_remaining 43 | # main game logic goes here 44 | if guesses_remaining > 0: 45 | if guess > secret_number: 46 | print "Lower" 47 | elif guess < secret_number: 48 | print "Higher" 49 | else: 50 | print "Correct" 51 | new_game() 52 | else: 53 | if guess == secret_number: 54 | print "Correct" 55 | else: 56 | print "You ran out of guesses. The number was", secret_number 57 | new_game() 58 | 59 | # create frame 60 | frame = simplegui.create_frame("Guess the number", 200, 200) 61 | 62 | # register event handlers for control elements and start frame 63 | frame.add_button("Range is [0, 100)", range100, 200) 64 | frame.add_button("Range is [0, 1000)", range1000, 200) 65 | frame.add_input("Enter a guess:", input_guess, 200) 66 | 67 | # call new_game 68 | new_game() -------------------------------------------------------------------------------- /Week 05/Week 5 Assignment/Memory.py: -------------------------------------------------------------------------------- 1 | # implementation of card game - Memory 2 | 3 | import simplegui 4 | import random 5 | 6 | # helper function to initialize globals 7 | def new_game(): 8 | global deck, exposed, state, cIndex1, cIndex2, nScore, nMoves 9 | state, nScore, nMoves, cIndex1, cIndex2 = 0, 0, 0, -1, -1 10 | deck = [x for x in range(8)]*2 11 | random.shuffle(deck) 12 | exposed = [False]*16 13 | 14 | # define event handlers 15 | def mouseclick(pos): 16 | # add game state logic here 17 | global state, nScore, cIndex1, cIndex2, nMoves 18 | cardIndex = list(pos)[0]//50 19 | if not exposed[cardIndex]: 20 | if state == 0: #just started 21 | cIndex1 = cardIndex 22 | exposed[cardIndex] = True 23 | state = 1 24 | elif state == 1: #one card flipped 25 | cIndex2 = cardIndex 26 | exposed[cardIndex] = True 27 | if deck[cIndex1] == deck[cIndex2]: 28 | nScore += 1 29 | state = 2 30 | nMoves += 1 31 | label.set_text("Turns = " + str(nMoves)) 32 | else: #two cards flipped 33 | if deck[cIndex1] != deck[cIndex2]: 34 | exposed[cIndex1], exposed[cIndex2] = False, False 35 | cIndex1, cIndex2 = -1, -1 36 | cIndex1 = cardIndex 37 | exposed[cardIndex] = True 38 | state = 1 39 | 40 | # cards are logically 50x100 pixels in size 41 | def draw(canvas): 42 | for i in range(16): 43 | if exposed[i]: 44 | canvas.draw_polygon([[i*50, 0], [(i+1)*50, 0], [(i+1)*50, 100], [i*50, 100]], 1, "Black", "White") 45 | canvas.draw_text(str(deck[i]), (i*50+11, 69), 55, "Black") 46 | else: 47 | canvas.draw_polygon([[i*50, 0], [(i+1)*50, 0], [(i+1)*50, 100], [i*50, 100]], 1, "Black", "Green") 48 | label.set_text("Turns = " + str(nMoves)) 49 | 50 | 51 | # create frame and add a button and labels 52 | frame = simplegui.create_frame("Memory", 800, 100) 53 | frame.add_button("Reset", new_game) 54 | label = frame.add_label("Turns = 0") 55 | 56 | # register event handlers 57 | frame.set_mouseclick_handler(mouseclick) 58 | frame.set_draw_handler(draw) 59 | 60 | # get things rolling 61 | new_game() 62 | frame.start() 63 | 64 | # Always remember to review the grading rubric -------------------------------------------------------------------------------- /Week 02/Week 2B/Example Codes/Lecture04-Original.py: -------------------------------------------------------------------------------- 1 | ############## 2 | # Example of missing "global" 3 | 4 | n1 = 0 5 | 6 | def increment(): 7 | n1 = n1 + 1 8 | 9 | increment() 10 | increment() 11 | increment() 12 | 13 | print n1 14 | 15 | 16 | ############## 17 | # Example of missing "global" 18 | 19 | n2 = 0 20 | 21 | def assign(x): 22 | n2 = x 23 | 24 | assign(2) 25 | assign(15) 26 | assign(7) 27 | 28 | print n2 29 | 30 | 31 | ############## 32 | # Example of missing "return" 33 | 34 | n3 = 0 35 | 36 | def decrement(): 37 | global n3 38 | n3 = n3 - 1 39 | 40 | x = decrement() 41 | 42 | print "x = ", x 43 | print "n = ", n 44 | 45 | 46 | ############## 47 | # Example of print debugging 48 | 49 | import simplegui 50 | 51 | x = 0 52 | 53 | def f(n): 54 | print "f: n,x = ", n, x 55 | result = n ** x 56 | print "f: result = ",result 57 | return result 58 | 59 | def button_handler(): 60 | global x 61 | print "bh : x = ", x 62 | x += 1 63 | print "bh : x = ", x 64 | 65 | def input_handler(text): 66 | print "ih : text = ", text 67 | print f(float(text)) 68 | 69 | frame = simplegui.create_frame("Example", 200, 200) 70 | frame.add_button("Increment", button_handler) 71 | frame.add_input("Number:", input_handler, 100) 72 | 73 | frame.start() 74 | 75 | 76 | ############## 77 | # Examples of simplifying conditionals 78 | 79 | def f1(a, b): 80 | """Returns True exactly when a is False and b is True.""" 81 | if a == False and b == True: 82 | return True 83 | else: 84 | return False 85 | 86 | def f2(a, b): 87 | """Returns True exactly when a is False and b is True.""" 88 | if not a and b: 89 | return True 90 | else: 91 | return False 92 | 93 | def f3(a, b): 94 | """Returns True exactly when a is False and b is True.""" 95 | return not a and b 96 | 97 | def g1(a, b): 98 | """Returns False eactly when a and b are both True.""" 99 | if a == True and b == True: 100 | return False 101 | else: 102 | return True 103 | 104 | def g2(a, b): 105 | """Returns False eactly when a and b are both True.""" 106 | if a and b: 107 | return False 108 | else: 109 | return True 110 | 111 | def g3(a, b): 112 | """Returns False eactly when a and b are both True.""" 113 | return not (a and b) 114 | -------------------------------------------------------------------------------- /Week 02/Week 2B/Example Codes/Lecture04-Corrected.py: -------------------------------------------------------------------------------- 1 | ############## 2 | # Example of missing "global" 3 | 4 | n1 = 0 5 | 6 | def increment(): 7 | global n1 8 | n1 = n1 + 1 9 | 10 | increment() 11 | increment() 12 | increment() 13 | 14 | print n1 15 | 16 | 17 | ############## 18 | # Example of missing "global" 19 | 20 | n2 = 0 21 | 22 | def assign(x): 23 | global n2 24 | n2 = x 25 | 26 | assign(2) 27 | assign(15) 28 | assign(7) 29 | 30 | print n2 31 | 32 | 33 | ############## 34 | # Example of missing "return" 35 | 36 | n3 = 0 37 | 38 | def decrement(): 39 | global n3 40 | n3 = n3 - 1 41 | return n3 42 | 43 | x = decrement() 44 | 45 | print "x = ", x 46 | print "n = ", n3 47 | 48 | 49 | ############## 50 | # Example of print debugging 51 | 52 | import simplegui 53 | 54 | x = 0 55 | 56 | def f(n): 57 | print "f: n,x = ", n, x 58 | result = n ** x 59 | print "f: result = ",result 60 | return result 61 | 62 | def button_handler(): 63 | global x 64 | print "bh : x = ", x 65 | x += 1 66 | print "bh : x = ", x 67 | 68 | def input_handler(text): 69 | print "ih : text = ", text 70 | print f(float(text)) 71 | 72 | frame = simplegui.create_frame("Example", 200, 200) 73 | frame.add_button("Increment", button_handler) 74 | frame.add_input("Number:", input_handler, 100) 75 | 76 | frame.start() 77 | 78 | 79 | ############## 80 | # Examples of simplifying conditionals 81 | 82 | def f1(a, b): 83 | """Returns True exactly when a is False and b is True.""" 84 | if a == False and b == True: 85 | return True 86 | else: 87 | return False 88 | 89 | def f2(a, b): 90 | """Returns True exactly when a is False and b is True.""" 91 | if not a and b: 92 | return True 93 | else: 94 | return False 95 | 96 | def f3(a, b): 97 | """Returns True exactly when a is False and b is True.""" 98 | return not a and b 99 | 100 | def g1(a, b): 101 | """Returns False eactly when a and b are both True.""" 102 | if a == True and b == True: 103 | return False 104 | else: 105 | return True 106 | 107 | def g2(a, b): 108 | """Returns False eactly when a and b are both True.""" 109 | if a and b: 110 | return False 111 | else: 112 | return True 113 | 114 | def g3(a, b): 115 | """Returns False eactly when a and b are both True.""" 116 | return not (a and b) -------------------------------------------------------------------------------- /Week 01/Week 1 Mini Project Rock-paper-scissors-lizard-Spock/Rock-paper-scissors-lizard-Spock.py: -------------------------------------------------------------------------------- 1 | # Rock-paper-scissors-lizard-Spock program 2 | 3 | import math 4 | import random 5 | 6 | # The key idea of this program is to equate the strings 7 | # "rock", "paper", "scissors", "lizard", "Spock" to numbers 8 | # as follows: 9 | # 10 | # 0 - rock 11 | # 1 - Spock 12 | # 2 - paper 13 | # 3 - lizard 14 | # 4 - scissors 15 | 16 | # helper functions 17 | 18 | #assign name to given number 19 | def name_to_number(name): 20 | if name == "rock": 21 | number = 0 22 | elif name == "Spock": 23 | number = 1 24 | elif name == "paper": 25 | number = 2 26 | elif name == "lizard": 27 | number = 3 28 | else: 29 | number = 4 30 | return number 31 | 32 | #assign number to given name 33 | def number_to_name(number): 34 | if number == 0: 35 | name = "rock" 36 | elif number == 1: 37 | name = "Spock" 38 | elif number == 2: 39 | name = "paper" 40 | elif number == 3: 41 | name = "lizard" 42 | else: 43 | name = "scissors" 44 | return name 45 | 46 | 47 | def rpsls(player_choice): 48 | # print a blank line to separate consecutive games 49 | print "" 50 | 51 | # print out the message for the player's choice 52 | print "Player chooses " + player_choice 53 | 54 | # convert the player's choice to player_number using the function name_to_number() 55 | player_number = name_to_number(player_choice) 56 | 57 | # compute random guess for comp_number using random.randrange() 58 | computer_number = random.randrange(0, 5) 59 | 60 | # convert comp_number to comp_choice using the function number_to_name() 61 | computer_choice = number_to_name(computer_number) 62 | 63 | # print out the message for computer's choice 64 | print "Computer chooses " + computer_choice 65 | 66 | # compute difference of comp_number and player_number modulo five 67 | difference = ((player_number - computer_number) % 5) 68 | 69 | # use if/elif/else to determine winner, print winner message 70 | if difference == 1 or difference == 2: 71 | print "Player wins!" 72 | elif difference == 3 or difference == 4: 73 | print "Computer wins!" 74 | else: 75 | print "Player and computer tie!" 76 | return "" 77 | 78 | 79 | # test your code - THESE CALLS MUST BE PRESENT IN YOUR SUBMITTED CODE 80 | rpsls("rock") 81 | rpsls("Spock") 82 | rpsls("paper") 83 | rpsls("lizard") 84 | rpsls("scissors") 85 | 86 | # always remember to check your completed program against the grading rubric -------------------------------------------------------------------------------- /Week 01/Week 1B/Example Codes/Lecture03-Original.py: -------------------------------------------------------------------------------- 1 | ############ 2 | # This is a compilation of the examples from Week 1's Programming Tips. 3 | # Many of these functions have errors, so this file won't run as is. 4 | ############ 5 | 6 | 7 | import math 8 | 9 | 10 | ############ 11 | # Has multiple NameErrors 12 | def volume_cube(side): 13 | return sidde ** 3 14 | 15 | s = 2 16 | print "Volume of cube with side", s, "is", volume(s), "." 17 | 18 | 19 | ############ 20 | # Has a NameError 21 | def random_dice(): 22 | die1 = random.randrange(1, 7) 23 | die2 = random.randrange(1, 7) 24 | return die1 + die2 25 | 26 | print "Sum of two random dice, rolled once:", random_dice() 27 | print "Sum of two random dice, rolled again:", random_dice() 28 | print "Sum of two random dice, rolled again:", random_dice() 29 | 30 | 31 | ############ 32 | # Has an AttributeError 33 | def volume_sphere(radius): 34 | return 4.0/3.0 * math.Pi * (radius ** 3) 35 | 36 | r = 2 37 | print "Volume of sphere of radius", r, "is", volume_sphere(r), "." 38 | 39 | 40 | ############ 41 | # Has multiple TypeErrors 42 | def area_triangle(base, height): 43 | return 0.5 * base * height 44 | 45 | b = "5" 46 | h = "2 + 2" 47 | print "Area of triangle with base", b, "and height", h, "is", area_triangle(b), "." 48 | 49 | 50 | ############ 51 | # Has multiple SyntaxErrors 52 | def is_mary(x) 53 | if x = "Mary": 54 | print "Found Mary!" 55 | else: 56 | print "No Mary." 57 | 58 | is_mary(Mary) 59 | is_mary(Fred) 60 | 61 | 62 | ############ 63 | # Poor readability 64 | def area(a,b,c): 65 | s = (a+b+c)/2.0 66 | return math.sqrt(s*(s-a)*(s-b)*(s-c)) 67 | 68 | 69 | ############ 70 | # Improved readability 71 | def area_triangle_sss(side1, side2, side3): 72 | """ 73 | Returns the area of a triangle, given the lengths of 74 | its three sides. 75 | """ 76 | 77 | # Use Heron's formula 78 | semiperim = (side1 + side2 + side3) / 2.0 79 | return math.sqrt(semiperim * 80 | (semiperim - side1) * 81 | (semiperim - side2) * 82 | (semiperim - side3)) 83 | 84 | base = 3 85 | height = 4 86 | hyp = 5 87 | print "Area of triangle with sides", base, height, hyp, "is", area_triangle_sss(base, height, hyp), "." 88 | 89 | 90 | ############ 91 | # Could use error-checking of input value 92 | def favorites(instructor): 93 | """Return the favorite thing of the given instructor.""" 94 | 95 | if instructor == "Joe": 96 | return "games" 97 | elif instructor == "Scott": 98 | return "ties" 99 | elif instructor == "John": 100 | return "outdoors" 101 | 102 | print favorites("John") 103 | print favorites("Jeannie") 104 | -------------------------------------------------------------------------------- /Week 01/Week 1B/Example Codes/Lecture03-Corrected.py: -------------------------------------------------------------------------------- 1 | ############ 2 | # This is a compilation of the examples from Week 1's Programming Tips. 3 | # Many of these functions have errors which have been corrected, so this file will run as is. 4 | ############ 5 | 6 | 7 | import math 8 | 9 | 10 | ############ 11 | # Had multiple NameErrors 12 | def volume_cube(side): 13 | return side ** 3 14 | 15 | s = 2 16 | print "Volume of cube with side", s, "is", volume_cube(s), "." 17 | 18 | 19 | ############ 20 | # Had a NameError 21 | import random 22 | def random_dice(): 23 | die1 = random.randrange(1, 7) 24 | die2 = random.randrange(1, 7) 25 | return die1 + die2 26 | 27 | print "Sum of two random dice, rolled once:", random_dice() 28 | print "Sum of two random dice, rolled again:", random_dice() 29 | print "Sum of two random dice, rolled again:", random_dice() 30 | 31 | 32 | ############ 33 | # Had an AttributeError 34 | def volume_sphere(radius): 35 | return 4.0/3.0 * math.pi * (radius ** 3) 36 | 37 | r = 2 38 | print "Volume of sphere of radius", r, "is", volume_sphere(r), "." 39 | 40 | 41 | ############ 42 | # Had multiple TypeErrors 43 | def area_triangle(base, height): 44 | return 0.5 * base * height 45 | 46 | b = 5 47 | h = 2 + 2 48 | print "Area of triangle with base", b, "and height", h, "is", area_triangle(b, h), "." 49 | 50 | 51 | ############ 52 | # Had multiple SyntaxErrors 53 | def is_mary(x): 54 | if x == "Mary": 55 | print "Found Mary!" 56 | else: 57 | print "No Mary." 58 | 59 | is_mary("Mary") 60 | is_mary('Fred') 61 | 62 | 63 | ############ 64 | # Poor readability 65 | def area(a,b,c): 66 | s = (a+b+c)/2.0 67 | return math.sqrt(s*(s-a)*(s-b)*(s-c)) 68 | 69 | 70 | ############ 71 | # Improved readability 72 | def area_triangle_sss(side1, side2, side3): 73 | """ 74 | Returns the area of a triangle, given the lengths of 75 | its three sides. 76 | """ 77 | 78 | # Use Heron's formula 79 | semiperim = (side1 + side2 + side3) / 2.0 80 | return math.sqrt(semiperim * 81 | (semiperim - side1) * 82 | (semiperim - side2) * 83 | (semiperim - side3)) 84 | 85 | base = 3 86 | height = 4 87 | hyp = 5 88 | print "Area of triangle with sides", base, height, hyp, "is", area_triangle_sss(base, height, hyp), "." 89 | 90 | 91 | ############ 92 | # Using error-checking of input value 93 | def favorites(instructor): 94 | """Return the favorite thing of the given instructor.""" 95 | 96 | if instructor == "Joe": 97 | return "games" 98 | elif instructor == "Scott": 99 | return "ties" 100 | elif instructor == "John": 101 | return "outdoors" 102 | else: 103 | print "favorites saw invalid instructor: ", instructor 104 | 105 | print favorites("John") 106 | print favorites("Jeannie") -------------------------------------------------------------------------------- /Week 04/Week 4 Quiz/Quiz 4B Codes.py: -------------------------------------------------------------------------------- 1 | # Question 3 2 | point = [0, 0] 3 | def function1(): 4 | point[0] += 1 5 | point[1] += 2 6 | function1() 7 | print point 8 | def function2(): 9 | point = [50, 50] 10 | function2() 11 | print point 12 | 13 | # Question 4 14 | x1 = range(5) 15 | y1 = x1 16 | x1 = [0, 1, 10, 3, 4] 17 | print x1, y1 18 | x2 = range(5) 19 | y2 = x2 20 | x2[2] = 10 21 | print x2, y2 22 | x3 = range(5) 23 | y3 = x3 24 | y3 = [0, 1, 10, 3, 4] 25 | print x3, y3 26 | x4 = range(5) 27 | x4 = y4 28 | x4[2] = 10 29 | print x4, y4 30 | x5 = range(5) 31 | y5 = x5 32 | y5[-3] = 10 33 | print x5, y5 34 | x6 = range(5) 35 | y6[-3] = 10 36 | x6 = y6 37 | print x6, y6 38 | 39 | # Question 5 40 | position = [50, 50] 41 | delta = [1, -2] 42 | position = position + delta 43 | print position 44 | 45 | # Question 6 :- Run the code in viz mode 46 | a = ["green", "blue", "white", "black"] 47 | b = a 48 | c = list(a) 49 | d = c 50 | a[3] = "red" 51 | c[2] = a[1] 52 | b = a[1 : 3] 53 | b[1] = c[2] 54 | print a 55 | print b 56 | print c 57 | print d 58 | 59 | # Question 7 60 | import simplegui 61 | # Initialize globals 62 | WIDTH = 400 63 | HEIGHT = 300 64 | pos = [10, 20] 65 | vel = [3, 0.7] 66 | # define event handlers 67 | def draw(canvas): 68 | # Update point position 69 | pos[0] += vel[0] 70 | pos[1] += vel[1] 71 | # Draw point 72 | canvas.draw_point(pos, 'White') 73 | canvas.draw_polygon([[50, 50], [180, 50], [180, 140], [50, 140]], 1, 'Yellow', 'Orange') 74 | # create frame 75 | frame = simplegui.create_frame("Point physics", WIDTH, HEIGHT) 76 | # register event handlers 77 | frame.set_draw_handler(draw) 78 | # start frame 79 | frame.start() 80 | 81 | # Question 8 82 | import simplegui 83 | # Initialize globals 84 | WIDTH = 600 85 | HEIGHT = 400 86 | pos = [0, 0] 87 | vel = [0.1, 0.07] 88 | acc = [0, 0.01] 89 | # define event handlers 90 | def draw(canvas): 91 | # Update point position 92 | pos[0] += vel[0] 93 | pos[1] += vel[1] 94 | # Update point velocity 95 | vel[0] += acc[0] 96 | vel[1] += acc[1] 97 | # Draw ball 98 | canvas.draw_circle(pos, 10, 5, 'Yellow', 'Orange') 99 | def key_handler(key): 100 | if key == simplegui.KEY_MAP["a"]: 101 | acc[0] += 0.01 102 | acc[1] += 0.02 103 | # create frame 104 | frame = simplegui.create_frame("Point physics", WIDTH, HEIGHT) 105 | # register event handlers 106 | frame.set_draw_handler(draw) 107 | frame.set_keydown_handler(key_handler) 108 | # start frame 109 | frame.start() 110 | 111 | # Question 9 112 | import simplegui 113 | # initialize state variables 114 | count = 0 115 | value = 5 116 | # event handlers 117 | def keydown(key): 118 | global count, value 119 | count += 1 120 | value *= 2 121 | def keyup(key): 122 | global value 123 | value -= 3 124 | def draw(c): 125 | c.draw_text(str(value), [10, 25], 20, "Red") 126 | c.draw_text(str(count), [100, 25], 20, "Yellow") 127 | # create frame 128 | f = simplegui.create_frame("Output", 130, 35) 129 | # register event handlers 130 | f.set_keydown_handler(keydown) 131 | f.set_keyup_handler(keyup) 132 | f.set_draw_handler(draw) 133 | # start frame 134 | f.start() -------------------------------------------------------------------------------- /Week 06/Week 6 Programming Assignment/Hand Class Testing Template.py: -------------------------------------------------------------------------------- 1 | # Testing template for the Hand class 2 | 3 | import random 4 | 5 | # define globals for cards 6 | SUITS = ['C', 'S', 'H', 'D'] 7 | RANKS = ['A', '2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K'] 8 | VALUES = {'A':1, '2':2, '3':3, '4':4, '5':5, '6':6, '7':7, '8':8, '9':9, 'T':10, 'J':10, 'Q':10, 'K':10} 9 | 10 | 11 | # define card class 12 | class Card: 13 | def __init__(self, suit, rank): 14 | if (suit in SUITS) and (rank in RANKS): 15 | self.suit = suit 16 | self.rank = rank 17 | else: 18 | print "Invalid card: ", suit, rank 19 | 20 | def __str__(self): 21 | return self.suit + self.rank 22 | 23 | def get_suit(self): 24 | return self.suit 25 | 26 | def get_rank(self): 27 | return self.rank 28 | 29 | def draw(self, canvas, pos): 30 | card_loc = (card_size[0] * (0.5 + RANKS.index(self.rank)), card_size[1] * (0.5 + SUITS.index(self.suit))) 31 | canvas.draw_image(card_images, card_loc, card_size, [pos[0] + card_size[0] / 2, pos[1] + card_size[1] / 2], card_size) 32 | 33 | 34 | ##################################################### 35 | # Student should insert code for Hand class here 36 | 37 | class Hand: 38 | def __init__(self): 39 | """ Creates Hand object """ 40 | self.cards = [] 41 | 42 | def __str__(self): 43 | """ Returns a string representation of a hand """ 44 | handCards = "" 45 | for card in self.cards: 46 | handCards = handCards + str(card) + " " 47 | if len(handCards) == 0: 48 | return "Hand contains nothing." 49 | else: 50 | return "Hand contains " + handCards.strip() + "." 51 | 52 | def add_card(self, card): 53 | """ Adds a card object to a hand """ 54 | self.cards.append(card) 55 | 56 | def get_value(self): 57 | """ Computes the value of the hand """ 58 | """ Counts aces as 1, if the hand has an ace, then add 10 to hand value if it doesn't bust """ 59 | currentValue = 0 60 | isAcePresent = False 61 | for card in self.cards: 62 | rank = card.get_rank() 63 | currentValue += Values[rank] 64 | if rank == 'A': 65 | isAcePresent = True 66 | if isAcePresent and currentValue < 12: 67 | currentValue += 10 68 | return currentValue 69 | 70 | def draw(self, canvas, pos): 71 | """ Draws a hand on the canvas, uses the draw method for cards """ 72 | for card in self.cards: 73 | pos[0] = pos[0] + CARD_SIZE[0] + 25 74 | card.draw(canvas, pos) 75 | 76 | ################################################### 77 | # Test code 78 | 79 | c1 = Card("S", "A") 80 | c2 = Card("C", "2") 81 | c3 = Card("D", "T") 82 | print c1, c2, c3 83 | print type(c1), type(c2), type(c3) 84 | 85 | test_hand = Hand() 86 | print test_hand 87 | 88 | test_hand.add_card(c1) 89 | print test_hand 90 | 91 | test_hand.add_card(c2) 92 | print test_hand 93 | 94 | test_hand.add_card(c3) 95 | print test_hand 96 | 97 | print type(test_hand) 98 | 99 | 100 | ################################################### 101 | # Output to console 102 | # note that the string representation of a hand will 103 | # vary based on how you implemented the __str__ method 104 | 105 | #SA C2 DT 106 | # 107 | #Hand contains 108 | #Hand contains SA 109 | #Hand contains SA C2 110 | #Hand contains SA C2 DT 111 | # -------------------------------------------------------------------------------- /Week 06/Week 6 Programming Assignment/Deck Class Testing Template.py: -------------------------------------------------------------------------------- 1 | # Testing template for the Deck class 2 | 3 | import random 4 | 5 | # define globals for cards 6 | SUITS = ['C', 'S', 'H', 'D'] 7 | RANKS = ['A', '2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K'] 8 | VALUES = {'A':1, '2':2, '3':3, '4':4, '5':5, '6':6, '7':7, '8':8, '9':9, 'T':10, 'J':10, 'Q':10, 'K':10} 9 | 10 | 11 | # define card class 12 | class Card: 13 | def __init__(self, suit, rank): 14 | if (suit in SUITS) and (rank in RANKS): 15 | self.suit = suit 16 | self.rank = rank 17 | else: 18 | print "Invalid card: ", suit, rank 19 | 20 | def __str__(self): 21 | return self.suit + self.rank 22 | 23 | def get_suit(self): 24 | return self.suit 25 | 26 | def get_rank(self): 27 | return self.rank 28 | 29 | def draw(self, canvas, pos): 30 | card_loc = (card_size[0] * (0.5 + RANKS.index(self.rank)), card_size[1] * (0.5 + SUITS.index(self.suit))) 31 | canvas.draw_image(card_images, card_loc, card_size, [pos[0] + card_size[0] / 2, pos[1] + card_size[1] / 2], card_size) 32 | 33 | 34 | ##################################################### 35 | # Student should insert code for Deck class here 36 | 37 | class Deck: 38 | def __init__(self): 39 | """ Creates a Deck object """ 40 | self.cards = [] 41 | for suit in SUITS: 42 | for rank in RANKS: 43 | self.cards.append(Card(suit, rank)) 44 | 45 | def shuffle(self): 46 | """ Shuffles the deck, using random.shuffle() """ 47 | random.shuffle(self.cards) 48 | 49 | def deal_card(self): 50 | """ Deals a card object from the deck """ 51 | return self.cards.pop() 52 | 53 | def __str__(self): 54 | """ Returns a string representing the deck """ 55 | deckCards = "" 56 | for card in self.cards: 57 | deckCards = deckCards + str(card) + " " 58 | if len(deckCards) == 0: 59 | return "Deck contains nothing." 60 | else: 61 | return "Deck contains " + deckCards.strip() + "." 62 | 63 | 64 | ################################################### 65 | # Test code 66 | 67 | test_deck = Deck() 68 | print test_deck 69 | print type(test_deck) 70 | 71 | c1 = test_deck.deal_card() 72 | print c1 73 | print type(c1) 74 | print test_deck 75 | 76 | c2 = test_deck.deal_card() 77 | print c2 78 | print type(c2) 79 | print test_deck 80 | 81 | test_deck = Deck() 82 | print test_deck 83 | test_deck.shuffle() 84 | print test_deck 85 | print type(test_deck) 86 | 87 | c3 = test_deck.deal_card() 88 | print c3 89 | print type(c3) 90 | print test_deck 91 | 92 | 93 | 94 | 95 | ################################################### 96 | # Output to console 97 | # output of string method for decks depends on your implementation of __str__ 98 | # note the output of shuffling is randomized so the exact order of cards 99 | # need not match 100 | 101 | #Deck contains CA C2 C3 C4 C5 C6 C7 C8 C9 CT CJ CQ CK SA S2 S3 S4 S5 S6 S7 S8 S9 ST SJ SQ SK HA H2 H3 H4 H5 H6 H7 H8 H9 HT HJ HQ HK DA D2 D3 D4 D5 D6 D7 D8 D9 DT DJ DQ DK 102 | # 103 | #DK 104 | # 105 | #Deck contains CA C2 C3 C4 C5 C6 C7 C8 C9 CT CJ CQ CK SA S2 S3 S4 S5 S6 S7 S8 S9 ST SJ SQ SK HA H2 H3 H4 H5 H6 H7 H8 H9 HT HJ HQ HK DA D2 D3 D4 D5 D6 D7 D8 D9 DT DJ DQ 106 | #DQ 107 | # 108 | #Deck contains CA C2 C3 C4 C5 C6 C7 C8 C9 CT CJ CQ CK SA S2 S3 S4 S5 S6 S7 S8 S9 ST SJ SQ SK HA H2 H3 H4 H5 H6 H7 H8 H9 HT HJ HQ HK DA D2 D3 D4 D5 D6 D7 D8 D9 DT DJ 109 | #Deck contains CA C2 C3 C4 C5 C6 C7 C8 C9 CT CJ CQ CK SA S2 S3 S4 S5 S6 S7 S8 S9 ST SJ SQ SK HA H2 H3 H4 H5 H6 H7 H8 H9 HT HJ HQ HK DA D2 D3 D4 D5 D6 D7 D8 D9 DT DJ DQ DK 110 | #Deck contains CT H6 C4 H9 D6 HJ D2 S5 D8 H2 ST H4 HQ HK S8 D3 CJ D5 DK DQ DA S9 S6 S2 DJ C8 SJ C9 D4 C7 SK CK S3 CA SA S4 CQ S7 HA H3 C5 D9 DT H7 HT C2 SQ H8 C6 D7 C3 H5 111 | # 112 | #H5 113 | # 114 | #Deck contains CT H6 C4 H9 D6 HJ D2 S5 D8 H2 ST H4 HQ HK S8 D3 CJ D5 DK DQ DA S9 S6 S2 DJ C8 SJ C9 D4 C7 SK CK S3 CA SA S4 CQ S7 HA H3 C5 D9 DT H7 HT C2 SQ H8 C6 D7 C3 115 | -------------------------------------------------------------------------------- /Week 03/Week 3 Quiz/Quiz 3B Code.py: -------------------------------------------------------------------------------- 1 | import simplegui 2 | import time; # This is required to include time module. 3 | 4 | ### Code for question 1-4(For checking 4 just uncomment timer2) 5 | Count = 0 6 | def timer_handler(): 7 | global Count, timer 8 | Count += 1 9 | print Count 10 | if Count == 10: 11 | timer.stop() 12 | timer = simplegui.create_timer(1000, timer_handler) 13 | timer.start() 14 | 15 | timer = simplegui.create_timer(10, timer_handler) 16 | #timer2 = simplegui.create_timer(100, timer_handler) 17 | timer.start() 18 | #timer2.start() 19 | 20 | ### Code for question 5-6 21 | ticks = time.time() 22 | print "Number of ticks since 12:00am, January 1, 1970:", ticks 23 | # time.time( ) :- Returns the current time instant, a floating-point number of seconds since the epoch(12:00am, January 1, 1970). 24 | 25 | ### Code for question 7 26 | # Mystery computation in Python 27 | # Takes input n and computes output named result 28 | # import simplegui 29 | # global state 30 | result = 1 31 | iteration = 0 32 | max_iterations = 10 33 | # helper functions 34 | def init(start): 35 | """Initializes n.""" 36 | global n 37 | n = start 38 | print "Input is", n 39 | def get_next(current): 40 | """??? Part of mystery computation.""" 41 | return 0.5 * (current + n / current) 42 | # timer callback 43 | def update(): 44 | """??? Part of mystery computation.""" 45 | global iteration, result 46 | iteration += 1 47 | # Stop iterating after max_iterations 48 | if iteration >= max_iterations: 49 | timer.stop() 50 | print "Output is", result 51 | else: 52 | result = get_next(result) 53 | # register event handlers 54 | timer = simplegui.create_timer(1, update) 55 | # start program 56 | init(13) 57 | timer.start() 58 | 59 | ### Code for Question 8 60 | # Takes input n and computes the sequence of numbers generated by repeatedly following the rule: 61 | # 1. divide by two if the number is even or 62 | # 2. multiply by 3 and add 1 if the number is odd. 63 | #import simplegui 64 | # define global variables 65 | maximum, n = 0, 0 66 | # helper functions 67 | def init(start): 68 | """Initializes n.""" 69 | global n 70 | n = start 71 | print "Input is", n 72 | def get_next(current): 73 | """??? Part of mystery computation.""" 74 | if current % 2 == 0: 75 | return current / 2 76 | else: 77 | return current * 3 + 1 78 | # timer callback 79 | def update(): 80 | """??? Part of mystery computation.""" 81 | global n, maximum 82 | maximum = max(n, maximum) 83 | print n 84 | # Stop iterating if n is 1 85 | if n == 1: 86 | timer.stop() 87 | print "Maximum number was ", maximum 88 | else: 89 | n = get_next(n) 90 | # register event handlers 91 | timer = simplegui.create_timer(1, update) 92 | # start program 93 | init(217) 94 | timer.start() 95 | 96 | ### Code for Question 9 97 | # animation of explosion using 2D sprite sheet 98 | #import simplegui 99 | # load 81 frame sprite sheer for explosion - image generated by phaedy explosion generator, source is hasgraphics.com 100 | EXPLOSION_CENTER = [50, 50] 101 | EXPLOSION_SIZE = [100, 100] 102 | EXPLOSION_DIM = [9, 9] 103 | explosion_image = simplegui.load_image("http://commondatastorage.googleapis.com/codeskulptor-assets/explosion.hasgraphics.png") 104 | # create timer that iterates current_sprite_center through sprite 105 | time = 0 106 | # define draw handler 107 | def draw(canvas): 108 | global time 109 | explosion_index = [time % EXPLOSION_DIM[0], (time // EXPLOSION_DIM[0]) % EXPLOSION_DIM[1]] 110 | canvas.draw_image(explosion_image, 111 | [EXPLOSION_CENTER[0] + explosion_index[0] * EXPLOSION_SIZE[0], 112 | EXPLOSION_CENTER[1] + explosion_index[1] * EXPLOSION_SIZE[1]], 113 | EXPLOSION_SIZE, EXPLOSION_CENTER, EXPLOSION_SIZE) 114 | time += 1 115 | # create frame and size frame based on 100x100 pixel sprite 116 | f = simplegui.create_frame("Asteroid sprite", EXPLOSION_SIZE[0], EXPLOSION_SIZE[1]) 117 | # set draw handler and canvas background using custom HTML color 118 | f.set_draw_handler(draw) 119 | f.set_canvas_background("Blue") 120 | # start animation 121 | f.start() -------------------------------------------------------------------------------- /Week 03/Week 3 Quiz/Quiz 3A.md: -------------------------------------------------------------------------------- 1 | Quiz 3A 2 | ======= 3 | 4 | Question 1 5 | ---------- 6 | 7 | What Python operator takes two strings (e.g., "sun" and "rise") and forms the combination of these two strings, one followed by the other (e.g., "sunrise")? 8 | 9 | ### Answer 10 | 11 | `+` 12 | 13 | Question 2 14 | ---------- 15 | 16 | What does the draw handler parameter represent? 17 | If you've forgotten, refer to the documentation. 18 | 19 | ### Answer 20 | 21 | The canvas 22 | 23 | Question 3 24 | ---------- 25 | 26 | What happens if you draw text outside the canvas coordinates? 27 | 28 | ### Answer 29 | 30 | Some or none of the text is shown. Conceptually, the text is drawn at whatever coordinates are given, but only whatever text fits within the canvas coordinates is shown. 31 | 32 | Question 4 33 | ---------- 34 | 35 | Assume we have a canvas that is 200 pixels wide and 300 pixels high. We want to draw a green line between the upper left corner and the lower right corner. Which of the following calls will accomplish this? 36 | 37 | ### Answer 38 | 39 | `canvas.draw_line((199, 299), (0, 0), 10, "Green")` 40 | 41 | ### Explanation 42 | 43 | A common mistake on this problem is to use a frame that is the same size as the default CodeSkuptor demo (300 pixels wide and 200 pixels high). 44 | 45 | Question 5 46 | ---------- 47 | 48 | Consider the following function definition. 49 | ``` 50 | def date(month, day): 51 | """ 52 | Given numbers month and day, returns a string of the form '2/12', 53 | with the month followed by the day. 54 | """ 55 | return month + "/" + day 56 | 57 | print date(2, 12) 58 | ``` 59 | This definition leads to an error. To fix it, what Python expression should replace the question marks below? 60 | ``` 61 | def date(month, day): 62 | """ 63 | Given numbers month and day, returns a string of the form '2/12', 64 | with the month followed by the day. 65 | """ 66 | return ??? 67 | 68 | print date(2, 12) 69 | ``` 70 | 71 | ### Answer 72 | 73 | `str(month) + "/" + str(day)` 74 | 75 | Question 6 76 | ---------- 77 | 78 | Assume we have a variable `word` that contains a string, such as `"Mississippi"` or `"indivisible"`. We would like to determine how many `"i"`'s are in the string `word`. What code should replace the question marks in the following function definition? 79 | ``` 80 | def number_of_i(word): 81 | """Returns the number of lower-case i's in the word.""" 82 | return ??? 83 | ``` 84 | There is a built-in function or method that will do this. Look in the CodeSkulptor documentation for the appropriate one. 85 | 86 | ### Answer 87 | 88 | `word.count("i")` 89 | 90 | Question 7 91 | ---------- 92 | 93 | Where should your `draw_text`, `draw_line`, and similar drawing calls be? 94 | 95 | ### Answer 96 | 97 | In a draw handler, or a helper function called from it. 98 | 99 | Question 8 100 | ---------- 101 | 102 | Which of the following function calls are valid, i.e., don't lead to an error? 103 | 104 | ### Answer 105 | 106 | * `int("5")` 107 | * `float("5")` 108 | 109 | Question 9 110 | ----------- 111 | 112 | Turn the following description into a CodeSkulptor program, and run it. 113 | 1. Create a 300-by-300 canvas. 114 | 2. Draw two circles with radius 20 and white lines of width 10. One is centered at (90,200) and one at (210,200). 115 | 3. Draw a red line of width 40 from (50,180) to (250,180). 116 | 4. Draw two red lines of width 5 from (55,170) to (90,120) and from (90,120) to (130,120). 117 | 5. Draw a red line of width 140 from (180,108) to (180,160). 118 | 119 | The resulting picture is a simple diagram of what? 120 | 121 | ### Answer 122 | 123 | An automobile 124 | 125 | Question 10 126 | ----------- 127 | 128 | The following is a diagram of an archery target. 129 | ![Archery FITA Official Target Image](https://github.com/UtkarshPathrabe/An-Introduction-to-Interactive-Programming-in-Python----Coursera/blob/master/Week%2003/Week%203%20Quiz/ArcheryTarget.png "Archery FITA Official Target Image") 130 | To draw this in CodeSkulptor, we can put a small yellow circle with a black border on top of a slightly bigger yellow circle with a black border, . on top of a big white circle with a black border. In what order should your code draw these circles? 131 | 132 | ### Answer 133 | Largest first 134 | 135 | ### Explanation 136 | Whatever you draw last appears to be on top. -------------------------------------------------------------------------------- /Week 04/Week 4 Quiz/Quiz 4A.md: -------------------------------------------------------------------------------- 1 | Quiz 2 | ==== 3 | 4 | Question 1 5 | ---------- 6 | 7 | What built-in function will add all the numbers in a list of numbers? Just give the function name, without any parentheses or argument. 8 | 9 | ### Answer 10 | 11 | sum 12 | 13 | ### Explanation 14 | 15 | See details in the python code file along with this document. 16 | 17 | Question 2 18 | ---------- 19 | 20 | Let `my_list` be the list `["This", "course", "is", "great"]`. 21 | 22 | What is `len(my_list)`? 23 | What non-negative number is the index of `"great"`? I.e., how would you replace the question marks in `my_list[???]` so that the result is `"great"`? 24 | Submit two numbers, one for each of these two questions, separated by spaces. 25 | 26 | ### Answer 27 | 28 | 4 3 29 | 30 | ### Explanation 31 | 32 | See details in the python code file along with this document. 33 | 34 | Question 3 35 | ---------- 36 | 37 | Let `my_list` be the list `["This", "course", "is", "great"]`. 38 | 39 | We can use Python's slice notation to get part of this list. What non-negative numbers can be used to get the slice `["course", "is"]`? I.e., what two non-negative numbers should we put in `my_list[??? : ???]` to get that result? 40 | 41 | Submit the two numbers in order, separated only by spaces. 42 | 43 | ### Answer 44 | 45 | 1 3 46 | 47 | ### Explanation 48 | 49 | See details in the python code file along with this document. 50 | 51 | Question 4 52 | ---------- 53 | 54 | If we want to split a list `my_list` into two halves, which of the following uses slices to do so correctly? 55 | 56 | More precisely, if the length of `my_list` is 2n, i.e., even, then the two parts should each have length n. If its length is 2n+1, i.e., odd, then the two parts should have lengths n and n+1. 57 | 58 | ### Answer 59 | 60 | `my_list[0 : len(my_list) // 2]` and `my_list[len(my_list) // 2 : len(my_list)]` 61 | `my_list[: len(my_list) // 2]` and `my_list[len(my_list) // 2 :]` 62 | 63 | ### Explanation 64 | 65 | `my_list[0 : len(my_list) // 2]` and `my_list[len(my_list) // 2 + 1 : len(my_list)]` 66 |     :The list element at index `len(my_list) // 2` is not in either part. 67 | `my_list[: len(my_list) // 2 - 1]` and `my_list[len(my_list) // 2 :]` 68 |     :The list element at index `len(my_list) // 2 - 1` is not in either part. 69 | See details in the python code file along with this document. 70 | 71 | Question 5 72 | ---------- 73 | 74 | What is the distance between point `[4, 7]` and the nearest point on the circle centered at `[2, 9]` with radius 2? Provide at least 4 digits of accuracy. 75 | 76 | Hint: The distance between a point and a circle is the distance between the point and the center of the circle minus the radius of the circle. You can use the point-to-point distance code described in this week's videos. 77 | 78 | ### Answer 79 | 80 | 0.82842712475 81 | 82 | ### Explanation 83 | 84 | See details in the python code file along with this document. 85 | 86 | Question 6 87 | ---------- 88 | 89 | A ball with velocity `[4, 2]` reflects off a vertical wall. What is its new velocity? 90 | 91 | ### Answer 92 | 93 | `[-4, 2]` 94 | 95 | ### Explanation 96 | 97 | On collision with a vertical wall only the X component of velocity changes, i.e. it becomes negative. 98 | 99 | Question 7 100 | ---------- 101 | 102 | Which of the following illustrate how to properly structure a keydown or keyup event handler? (For more advanced Python programmers, assume that you have just imported simplegui and haven't used `from`.) 103 | 104 | ### Answer 105 | 106 | def keydown_handler(key): 107 |     if key == simplegui.KEY_MAP["left"]: 108 |         ... 109 | 110 | Question 8 111 | ---------- 112 | 113 | Assume you have a program with a keydown handler. You run it, and press a single key and hold it down continuously. How many times does the keydown handler get called? 114 | 115 | ### Answer 116 | 117 | 1 118 | 119 | Question 9 120 | ----------- 121 | 122 | Several keys on the keyboard, such as Shift, CapsLock, and Ctrl, typically act to modify what happens when you press other keys, rather than doing anything on their own. When using the SimpleGUI keydown handler, how are such keys treated? 123 | 124 | ### Answer 125 | 126 | Independent key press events - e.g., pressing Shift by itself creates an event. 127 | 128 | ### Explanation 129 | 130 | Yes, for example Shift gives the value 16, Control key gives the value of 17 etc. -------------------------------------------------------------------------------- /Week 04/Week 4 Assignment/Pong.py: -------------------------------------------------------------------------------- 1 | # @ Author: UTKARSH PATHRABE 2 | 3 | # Implementation of classic arcade game Pong 4 | 5 | import simplegui 6 | import random 7 | 8 | # initialize globals - pos and vel encode vertical info for paddles 9 | WIDTH = 600 10 | HEIGHT = 400 11 | BALL_RADIUS = 20 12 | PAD_WIDTH = 8 13 | PAD_HEIGHT = 80 14 | HALF_PAD_WIDTH = PAD_WIDTH / 2 15 | HALF_PAD_HEIGHT = PAD_HEIGHT / 2 16 | LEFT = False 17 | RIGHT = True 18 | SIDE = LEFT 19 | 20 | # initialize ball_pos and ball_vel for new bal in middle of table 21 | # if direction is RIGHT, the ball's velocity is upper right, else upper left 22 | def spawn_ball(direction): 23 | global ball_pos, ball_vel # these are vectors stored as lists 24 | ball_pos = [WIDTH / 2, HEIGHT / 2] # position the ball at the centre of the canvas 25 | if direction == RIGHT: 26 | ball_vel = [random.randrange(120, 240) / 60, -(random.randrange(60, 180) /60)] 27 | else: 28 | ball_vel = [-(random.randrange(120, 240) / 60), -(random.randrange(60, 180) / 60)] 29 | 30 | 31 | # define event handlers 32 | def new_game(): 33 | global paddle1_pos, paddle2_pos, paddle1_vel, paddle2_vel # these are numbers 34 | global score1, score2 # these are ints 35 | global SIDE #this is a boolean 36 | paddle1_pos, paddle2_pos = (HEIGHT - PAD_HEIGHT)/2, (HEIGHT - PAD_HEIGHT)/2 37 | paddle1_vel = paddle2_vel = 0 38 | score1, score2 = 0, 0 39 | SIDE = not SIDE 40 | spawn_ball(SIDE) 41 | 42 | def draw(canvas): 43 | global score1, score2, paddle1_pos, paddle2_pos, ball_pos, ball_vel 44 | 45 | # draw mid line and gutters 46 | canvas.draw_line([WIDTH / 2, 0],[WIDTH / 2, HEIGHT], 1, "White") 47 | canvas.draw_line([PAD_WIDTH, 0],[PAD_WIDTH, HEIGHT], 1, "White") 48 | canvas.draw_line([WIDTH - PAD_WIDTH, 0],[WIDTH - PAD_WIDTH, HEIGHT], 1, "White") 49 | 50 | # update ball 51 | if ball_pos[0] <= BALL_RADIUS + PAD_WIDTH: 52 | if paddle1_pos <= ball_pos[1] <= (paddle1_pos+PAD_HEIGHT): 53 | ball_vel[0] = - 1.1 * ball_vel[0] 54 | else: 55 | spawn_ball(RIGHT) 56 | score2 += 1 57 | if ball_pos[0] >= (WIDTH - BALL_RADIUS - PAD_WIDTH): 58 | if paddle2_pos <= ball_pos[1] <= (paddle2_pos+PAD_HEIGHT): 59 | ball_vel[0] = - 1.1 * ball_vel[0] 60 | else: 61 | spawn_ball(LEFT) 62 | score1 += 1 63 | if ball_pos[1] <= BALL_RADIUS: 64 | ball_vel[1] = - ball_vel[1] 65 | if ball_pos[1] >= (HEIGHT - BALL_RADIUS): 66 | ball_vel[1] = - ball_vel[1] 67 | ball_pos[0] += ball_vel[0] 68 | ball_pos[1] += ball_vel[1] 69 | 70 | # draw ball 71 | canvas.draw_circle(ball_pos, BALL_RADIUS, 0.1, "White", "White") 72 | 73 | # update paddle's vertical position, keep paddle on the screen 74 | if 0 <= (paddle1_pos + paddle1_vel) <= HEIGHT - PAD_HEIGHT: 75 | paddle1_pos += paddle1_vel 76 | if 0 <= (paddle2_pos + paddle2_vel) <= HEIGHT - PAD_HEIGHT: 77 | paddle2_pos += paddle2_vel 78 | 79 | # draw paddles 80 | canvas.draw_line([PAD_WIDTH / 2, paddle1_pos],[PAD_WIDTH / 2, paddle1_pos + PAD_HEIGHT], PAD_WIDTH, "White") 81 | canvas.draw_line([WIDTH - PAD_WIDTH / 2, paddle2_pos],[WIDTH- PAD_WIDTH / 2, paddle2_pos + PAD_HEIGHT], PAD_WIDTH, "White") 82 | 83 | # draw scores 84 | canvas.draw_text(str(score1), (185, 40), 40, "White") 85 | canvas.draw_text(str(score2), (400, 40), 40, "White") 86 | 87 | def keydown(key): 88 | global paddle1_vel, paddle2_vel 89 | vel = 3 90 | if key == simplegui.KEY_MAP["s"]: 91 | paddle1_vel = vel 92 | if key == simplegui.KEY_MAP["w"]: 93 | paddle1_vel = -vel 94 | if key == simplegui.KEY_MAP["down"]: 95 | paddle2_vel = vel 96 | if key == simplegui.KEY_MAP["up"]: 97 | paddle2_vel = -vel 98 | 99 | def keyup(key): 100 | global paddle1_vel, paddle2_vel 101 | if key == simplegui.KEY_MAP["s"]: 102 | paddle1_vel = 0 103 | if key == simplegui.KEY_MAP["w"]: 104 | paddle1_vel = 0 105 | if key == simplegui.KEY_MAP["down"]: 106 | paddle2_vel = 0 107 | if key == simplegui.KEY_MAP["up"]: 108 | paddle2_vel = 0 109 | 110 | def game_restart(): 111 | new_game() 112 | 113 | # create frame 114 | frame = simplegui.create_frame("Pong", WIDTH, HEIGHT) 115 | frame.set_draw_handler(draw) 116 | frame.set_keydown_handler(keydown) 117 | frame.set_keyup_handler(keyup) 118 | frame.add_button("Restart", game_restart, 100) 119 | 120 | # start frame 121 | new_game() 122 | frame.start() 123 | -------------------------------------------------------------------------------- /Week 06/Week 6 Programming Assignment/Hand Class GetValue Method Testing Template.py: -------------------------------------------------------------------------------- 1 | # Testing template for the get_value method for Hands 2 | 3 | import random 4 | 5 | # define globals for cards 6 | SUITS = ['C', 'S', 'H', 'D'] 7 | RANKS = ['A', '2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K'] 8 | VALUES = {'A':1, '2':2, '3':3, '4':4, '5':5, '6':6, '7':7, '8':8, '9':9, 'T':10, 'J':10, 'Q':10, 'K':10} 9 | 10 | 11 | # define card class 12 | class Card: 13 | def __init__(self, suit, rank): 14 | if (suit in SUITS) and (rank in RANKS): 15 | self.suit = suit 16 | self.rank = rank 17 | else: 18 | print "Invalid card: ", suit, rank 19 | 20 | def __str__(self): 21 | return self.suit + self.rank 22 | 23 | def get_suit(self): 24 | return self.suit 25 | 26 | def get_rank(self): 27 | return self.rank 28 | 29 | def draw(self, canvas, pos): 30 | card_loc = (card_size[0] * (0.5 + RANKS.index(self.rank)), card_size[1] * (0.5 + SUITS.index(self.suit))) 31 | canvas.draw_image(card_images, card_loc, card_size, [pos[0] + card_size[0] / 2, pos[1] + card_size[1] / 2], card_size) 32 | 33 | 34 | ##################################################### 35 | # Student should insert code for Hand class here 36 | 37 | class Hand: 38 | def __init__(self): 39 | """ Creates Hand object """ 40 | self.cards = [] 41 | 42 | def __str__(self): 43 | """ Returns a string representation of a hand """ 44 | handCards = "" 45 | for card in self.cards: 46 | handCards = handCards + str(card) + " " 47 | if len(handCards) == 0: 48 | return "Hand contains nothing." 49 | else: 50 | return "Hand contains " + handCards.strip() + "." 51 | 52 | def add_card(self, card): 53 | """ Adds a card object to a hand """ 54 | self.cards.append(card) 55 | 56 | def get_value(self): 57 | """ Computes the value of the hand """ 58 | """ Counts aces as 1, if the hand has an ace, then add 10 to hand value if it doesn't bust """ 59 | currentValue = 0 60 | isAcePresent = False 61 | for card in self.cards: 62 | rank = card.get_rank() 63 | currentValue += VALUES[rank] 64 | if rank == 'A': 65 | isAcePresent = True 66 | if isAcePresent and currentValue < 12: 67 | currentValue += 10 68 | return currentValue 69 | 70 | def draw(self, canvas, pos): 71 | """ Draws a hand on the canvas, uses the draw method for cards """ 72 | for card in self.cards: 73 | pos[0] = pos[0] + CARD_SIZE[0] + 25 74 | card.draw(canvas, pos) 75 | 76 | 77 | ################################################### 78 | # Test code 79 | 80 | c1 = Card("S", "A") 81 | c2 = Card("C", "2") 82 | c3 = Card("D", "T") 83 | c4 = Card("S", "K") 84 | c5 = Card("C", "7") 85 | c6 = Card("D", "A") 86 | 87 | test_hand = Hand() 88 | print test_hand 89 | print test_hand.get_value() 90 | 91 | test_hand.add_card(c2) 92 | print test_hand 93 | print test_hand.get_value() 94 | 95 | test_hand.add_card(c5) 96 | print test_hand 97 | print test_hand.get_value() 98 | 99 | test_hand.add_card(c3) 100 | print test_hand 101 | print test_hand.get_value() 102 | 103 | test_hand.add_card(c4) 104 | print test_hand 105 | print test_hand.get_value() 106 | 107 | 108 | 109 | test_hand = Hand() 110 | print test_hand 111 | print test_hand.get_value() 112 | 113 | test_hand.add_card(c1) 114 | print test_hand 115 | print test_hand.get_value() 116 | 117 | test_hand.add_card(c6) 118 | print test_hand 119 | print test_hand.get_value() 120 | 121 | test_hand.add_card(c4) 122 | print test_hand 123 | print test_hand.get_value() 124 | 125 | test_hand.add_card(c5) 126 | print test_hand 127 | print test_hand.get_value() 128 | 129 | test_hand.add_card(c3) 130 | print test_hand 131 | print test_hand.get_value() 132 | 133 | 134 | 135 | ################################################### 136 | # Output to console 137 | # note that the string representation of a hand may vary 138 | # based on your implementation of the __str__ method 139 | 140 | #Hand contains 141 | #0 142 | #Hand contains C2 143 | #2 144 | #Hand contains C2 C7 145 | #9 146 | #Hand contains C2 C7 DT 147 | #19 148 | #Hand contains C2 C7 DT SK 149 | #29 150 | #Hand contains 151 | #0 152 | #Hand contains SA 153 | #11 154 | #Hand contains SA DA 155 | #12 156 | #Hand contains SA DA SK 157 | #12 158 | #Hand contains SA DA SK C7 159 | #19 160 | #Hand contains SA DA SK C7 DT 161 | #29 -------------------------------------------------------------------------------- /Week 00/Week 0 Quiz/Quiz 0.md: -------------------------------------------------------------------------------- 1 | Quiz 0 2 | ====== 3 | 4 | |Attempts|Score| 5 | |:------:|:---:| 6 | | 1/20 |100/100| 7 | 8 | Question 01 9 | ----------- 10 | Which of the following are syntactically correct strings? 11 | 12 | ### Answer and Explanation 13 | * `'Hello'` : This is a string. You can use single-quotes. 14 | * `[Hello]` : This is not a string. A string must use quotation marks. 15 | * `Hello` : This is not a string. A string must have quotation marks. 16 | * `'She shouted "Hello!" very loudly.'` : This is a string. A double-quote can appear inside single-quotes. 17 | * `"Hello"` : This is a string. You can use double-quotes. 18 | * `"Goodbye'` : This is not a string. You can't mix-and-match single- and double-quotes. 19 | * `"Hello, world."` : This is a string. You can use double-quotes. 20 | * `'This course is great!'` : This is a string. You can use single-quotes. 21 | * `"Hello` : This is not a string. It is missing a closing double-quote. 22 | 23 | Question 02 24 | ----------- 25 | To display a value in the console, what Python keyword do you use? 26 | 27 | ### Answer 28 | print 29 | 30 | Question 03 31 | ----------- 32 | In the following code, the one line starting with # is highlighted in red. What does this line mean to Python? 33 | 34 | `tax_rate = 0.15` 35 | `income = 40000` 36 | `deduction = 10000` 37 | 38 | `# Calculate income taxes` 39 | `tax = (income - deduction) * tax_rate` 40 | 41 | `print tax` 42 | 43 | ### Answer 44 | This is a comment aimed at the human reader. Python ignores such comments. 45 | 46 | Question 04 47 | ----------- 48 | Which of the following arithmetic expressions are syntactically correct? 49 | 50 | ### Answer and Explanation 51 | - `9 + * 4` : This example has incorrect syntax. The two operators + * together like this are meaningless. 52 | - `(8 + (1 + (2 * 4) - 3))` : This example has correct syntax. 53 | - `(7 - 2) / (3 ** 2)` : This example has correct syntax. 54 | - `5 * 3 (7 - 2)` : This example has incorrect syntax. This is missing an operator between 3 and (7-2). 55 | - `8 / -2` : This example has correct syntax. You can put a negative sign in front of a number like this. 56 | - `9 - (2 - (4 * 3)` : This example has incorrect syntax. This is missing closing parenthesis. 57 | - `5 - 1 - 3 - 7 - 0` : This example has correct syntax. 58 | 59 | Question 05 60 | ----------- 61 | You would like to make it so that the variable ounces has the value 16, thus representing one pound. What simple Python statement will accomplish this? 62 | 63 | ### Answer and Explanation 64 | * `ounces = 16` : Correct 65 | * `ounces == 16` : Means something different 66 | * `16 = ounces` : Invalid syntax 67 | * `ounces := 16` : Invalid syntax 68 | 69 | Question 06 70 | ----------- 71 | A gram is equal to 0.035274 ounces. Assume that the variable `mass_in_ounces` has a value representing a mass in ounces. Which arithmetic expressions below using the variable `mass_in_ounces` represent the equivalent mass in grams? 72 | 73 | ### Answer 74 | `mass_in_ounces / 0.035274` 75 | 76 | Question 07 77 | ----------- 78 | Which of the following can be used as a variable name? 79 | 80 | ### Answer and Explanation 81 | * `ounce(s)` : No, this is not a valid variable name. You cannot use parentheses in a variable name. 82 | * `16ounces` : No, this is not a valid variable name. A variable` name cannot begin with digits. 83 | * `number123` : This is a valid variable name. 84 | * `ounces` : This is a valid variable name. 85 | * `my_number` : This is a valid variable name., You can use underscores. 86 | * `__number__` : This is a valid variable name. However, convention says that Python variable names starting and ending with underscores only in special circumstances. 87 | * `MYnumber` : This is a valid variable name. However, convention says that Python variables shouldn't start with a capital letter. 88 | * `my-number` : No, this is not a valid variable name. You cannot use a dash in a variable name. The dash is interpreted as a minus sign. 89 | 90 | Question 08 91 | ----------- 92 | Assume you have values in the variables `x` and `y`. Which statement(s) would result in x having the sum of the current values of `x` and `y`? 93 | 94 | ### Answer 95 | * `x += y` 96 | * `x = x + y` 97 | * `x = y + x` 98 | 99 | Question 09 100 | ----------- 101 | Python file names traditionally end in what characters after a period? Don't include the period. 102 | 103 | ### Answer 104 | py 105 | 106 | Question 10 107 | ----------- 108 | We encourage you to save your CodeSkulptor Python files where? 109 | 110 | ### Answer 111 | In "the cloud" and on your computer. -------------------------------------------------------------------------------- /Week 02/Week 2 Quiz/Quiz2b.md: -------------------------------------------------------------------------------- 1 | Quiz 2 | ==== 3 | 4 | Question 1 5 | ---------- 6 | 7 | In the following code, what does the number `100` represent? 8 | `my_button = frame.add_button("My Label", button_handler, 100)` 9 | 10 | ### Answer 11 | 12 | Width of the button in pixels. 13 | 14 | Question 2 15 | ---------- 16 | 17 | How many control objects are allowed in a frame? 18 | 19 | ### Answer 20 | 21 | Unlimited, i.e., 0 or more 22 | 23 | Question 3 24 | ---------- 25 | 26 | In SimpleGUI, one kind of object can be added to the control panel that doesn't allow any handler. Thus, this object can't respond to anything. What kind of object is that? 27 | 28 | ### Answer 29 | 30 | Label 31 | 32 | Question 4 33 | ---------- 34 | 35 | When you enter text into an input field and press enter, the text is passed to the input field's event handler. What is the data type of the text? 36 | 37 | ### Answer 38 | 39 | A string 40 | 41 | ### Explanation 42 | 43 | The entered data is a string. The text entered into an input field is always passed to the input handler as a string even if the text corresponds to a number. 44 | 45 | Question 5 46 | ---------- 47 | 48 | Consider the following conditional statement. 49 | 50 | if p == False: 51 |     return False 52 | elif q == False: 53 |     return False 54 | else: 55 |     return True 56 | 57 | That is equivalent to which of the following simpler statements? 58 | 59 | ### Answer 60 | 61 | return q and p 62 | 63 | Question 6 64 | ---------- 65 | 66 | Which of the following describes the mistake in the following code? 67 | 68 | def volume_cube(side): 69 |     """ Returns the volume of a cube, given the length of its side. """ 70 |     print side ** 3 71 | 72 | s = 5 73 | print "The volume of a cube with sides", s, "long is", volume_cube(s), "." 74 | 75 | ### Answer 76 | 77 | The function should return, not print, its result. 78 | 79 | ### Explanation 80 | 81 | In most cases, functions should return their computed results. Furthermore, the documentation string here specifies that it should be returning that value. 82 | 83 | Question 7 84 | ---------- 85 | 86 | What kind of errors can happen if you are missing a needed `global` declaration in one of your function definitions? For this question, you need only consider the case where the problem is in the function that is missing the `global` declaration. 87 | 88 | ### Answer 89 | 90 | An incorrect computation that generates no error message 91 | 92 | ### Explanation 93 | 94 | If you only assign to the variable, without trying to use its current value, you won't get any error message. Instead, Python assumes the variable is local, which might lead to an unexpected result. 95 | 96 | Question 8 97 | ---------- 98 | 99 | Which of the following function definitions are in the recommended code style? 100 | 101 | ### Answer 102 | 103 | def f(x, y): 104 |     """ Add the two inputs. """ 105 |     return x + y 106 | 107 | ### Explanation 108 | 109 | 1. def f (x, y): 110 |     """ Add the two inputs. """ 111 |     return x + y 112 | 113 | This does not follow recommended style, there shouldn't be a space before the parenthesis 114 | 115 | 2. def myFunction(x, y): 116 |     """ Add the two inputs. """ 117 |     return x + y 118 | 119 | This does not follow recommended style, only class names should use "camel case". 120 | 121 | 3. def f(x, y): 122 |     """ Add the two inputs. """ 123 |     return x+y 124 | 125 | This does not follow recommended style, there should be spaces around the addition operator. 126 | 127 | Question 9 128 | ---------- 129 | 130 | Cut and paste the following code into CodeSkulptor. Run it and make an attempt to understand how it works. 131 | We'd like to modify the code so that the count is reset to zero whenever a new message is entered. Where would you need to modify this code to implement this change? 132 | 133 | ### Answer 134 | 135 | Add an assignment to count in the event handler for the input field. Also add a global count declaration there. 136 | 137 | Question 10 138 | ----------- 139 | 140 | In the game "Guess the number", what is the minimum number of guesses necessary to guarantee that the guesser can always win if the secret number is chosen in range(0, 400)? 141 | Review the mini-project description for "Guess the number" if you are having trouble with this problem. 142 | 143 | ### Answer 144 | 145 | 9 guesses 146 | 147 | ### Explanation 148 | 149 | log to the base 2 (400) rounded to the higher side. -------------------------------------------------------------------------------- /Week 06/Week 6 A/Example Codes/Lecture 02.py: -------------------------------------------------------------------------------- 1 | # ball physics code for generic 2D domain 2 | # the functions inside() and normal() encode the shape of the ennvironment 3 | 4 | import simplegui 5 | import random 6 | import math 7 | 8 | # Canvas size 9 | width = 600 10 | height = 400 11 | 12 | # Ball traits 13 | radius = 20 14 | color = "White" 15 | 16 | # math helper function 17 | def dot(v, w): 18 | return v[0] * w[0] + v[1] * w[1] 19 | 20 | class RectangularDomain: 21 | def __init__(self, width, height): 22 | self.width = width 23 | self.height = height 24 | self.border = 2 25 | 26 | # return if bounding circle is inside the domain 27 | def inside(self, center, radius): 28 | in_width = ((radius + self.border) < center[0] < 29 | (self.width - self.border - radius)) 30 | in_height = ((radius + self.border) < center[1] < 31 | (self.height - self.border - radius)) 32 | return in_width and in_height 33 | 34 | # return a unit normal to the domain boundary point nearest center 35 | def normal(self, center): 36 | left_dist = center[0] 37 | right_dist = self.width - center[0] 38 | top_dist = center[1] 39 | bottom_dist = self.height - center[1] 40 | if left_dist < min(right_dist, top_dist, bottom_dist): 41 | return (1, 0) 42 | elif right_dist < min(left_dist, top_dist, bottom_dist): 43 | return (-1, 0) 44 | elif top_dist < min(bottom_dist, left_dist, right_dist): 45 | return (0, 1) 46 | else: 47 | return (0, -1) 48 | 49 | # return random location 50 | def random_pos(self, radius): 51 | x = random.randrange(radius, self.width - radius - self.border) 52 | y = random.randrange(radius, self.height - radius - self.border) 53 | return [x, y] 54 | 55 | # Draw boundary of domain 56 | def draw(self, canvas): 57 | canvas.draw_polygon([[0, 0], [self.width, 0], 58 | [self.width, self.height], [0, self.height]], 59 | self.border*2, "Red") 60 | 61 | class CircularDomain: 62 | def __init__(self, center, radius): 63 | self.center = center 64 | self.radius = radius 65 | self.border = 2 66 | 67 | # return if bounding circle is inside the domain 68 | def inside(self, center, radius): 69 | dx = center[0] - self.center[0] 70 | dy = center[1] - self.center[1] 71 | dr = math.sqrt(dx ** 2 + dy ** 2) 72 | return dr < (self.radius - radius - self.border) 73 | 74 | # return a unit normal to the domain boundary point nearest center 75 | def normal(self, center): 76 | dx = center[0] - self.center[0] 77 | dy = center[1] - self.center[1] 78 | dr = math.sqrt(dx ** 2 + dy ** 2) 79 | return [dx / dr, dy / dr] 80 | 81 | # return random location 82 | def random_pos(self, radius): 83 | r = random.random() * (self.radius - radius - self.border) 84 | theta = random.random() * 2 * math.pi 85 | x = r * math.cos(theta) + self.center[0] 86 | y = r * math.sin(theta) + self.center[1] 87 | return [x, y] 88 | 89 | # Draw boundary of domain 90 | def draw(self, canvas): 91 | canvas.draw_circle(self.center, self.radius, self.border*2, "Red") 92 | 93 | class Ball: 94 | def __init__(self, radius, color, domain): 95 | self.radius = radius 96 | self.color = color 97 | self.domain = domain 98 | 99 | self.pos = self.domain.random_pos(self.radius) 100 | self.vel = [random.random() + .1, random.random() + .1] 101 | 102 | # bounce 103 | def reflect(self): 104 | norm = self.domain.normal(self.pos) 105 | norm_length = dot(self.vel, norm) 106 | self.vel[0] = self.vel[0] - 2 * norm_length * norm[0] 107 | self.vel[1] = self.vel[1] - 2 * norm_length * norm[1] 108 | 109 | 110 | # update ball position 111 | def update(self): 112 | self.pos[0] += self.vel[0] 113 | self.pos[1] += self.vel[1] 114 | if not self.domain.inside(self.pos, self.radius): 115 | self.reflect() 116 | 117 | # draw 118 | def draw(self, canvas): 119 | canvas.draw_circle(self.pos, self.radius, 1, 120 | self.color, self.color) 121 | 122 | 123 | # generic update code for ball physics 124 | def draw(canvas): 125 | ball.update() 126 | field.draw(canvas) 127 | ball.draw(canvas) 128 | 129 | field = RectangularDomain(width, height) 130 | # field = CircularDomain([width/2, height/2], 180) 131 | ball = Ball(radius, color, field) 132 | 133 | frame = simplegui.create_frame("Ball physics", width, height) 134 | 135 | frame.set_draw_handler(draw) 136 | 137 | frame.start() -------------------------------------------------------------------------------- /Week 02/Week 2 Quiz/Quiz2a.md: -------------------------------------------------------------------------------- 1 | Quiz 2 | ==== 3 | 4 | Question 1 5 | ---------- 6 | 7 | What typically calls an event handler? 8 | 9 | ### Answer 10 | 11 | Some code that you didn't write which generates the event. 12 | 13 | Question 2 14 | ---------- 15 | 16 | In CodeSkulptor, how many event handlers can be running at the same time? 17 | 18 | ### Answer 19 | 20 | 1 21 | 22 | Question 3 23 | ---------- 24 | 25 | What are the three parts of a frame? 26 | Refer to the video on SimpleGUI. 27 | 28 | ### Answer 29 | 30 | Control Area 31 | Status Area 32 | Canvas 33 | 34 | Question 4 35 | ---------- 36 | 37 | For the SimpleGUI-based programs in this course, we recommended breaking down an interactive Python program into seven parts. Below, these parts are listed alphabetically. 38 | 1. Create frame 39 | 2. Define classes 40 | 3. Define event handlers 41 | 4. Initialize global variables 42 | 5. Define helper functions 43 | 6. Register event handlers 44 | 7. Start frame and timers 45 | However, in lecture, we recommended a particular ordering of these parts. Enter 7 numbers in the range 1-7, separated only by spaces, to indicate the recommended ordering of the preceding elements of an interactive Python program. For example, if you think that the first action in your program should be to register your event handlers, enter 6 as the first number in the sequence. 46 | 47 | ### Answer 48 | 49 | 4 5 2 3 1 6 7 50 | 51 | Question 5 52 | ---------- 53 | 54 | Assume the following global definition is part of your program. 55 | `x = 5` 56 | If each of the following function definitions are also part of your program, which of them **needs** a `global x` declaration? You can try each definition in CodeSkulptor. 57 | 58 | ### Explanation 59 | 60 | 1. def c(y): 61 |     return x + y 62 | This example does not need a global declaration. You don't need a `global` declaration unless you are assigning to the global variable. 63 | 64 | 2. def d(y): 65 |     y = x + y 66 |     return y 67 | This example does not need a global declaration. You don't need a `global` declaration unless you are assigning to the global variable. 68 | 69 | 3. def b(x,y): 70 |     x = x + y 71 |     return x 72 | This example does not need a global declaration. Here a local variable `x` is being assigned to. If you add a `global` declaration, you'll get a SyntaxError. 73 | 74 | 4. def a(y): 75 |     x = x + y 76 |     return y 77 | This example does not need a global declaration. You don't need a `global` declaration unless you are assigning to the global variable. 78 | 79 | Question 6 80 | ---------- 81 | 82 | Consider the following code. 83 | 84 | count = 0 85 | 86 | def square(x): 87 |     global count 88 |     count += 1 89 |     return x**2 90 | 91 | print square(square(square(square(3)))) 92 | What is the value of count at the end? Enter a number. 93 | 94 | ### Answer 95 | 96 | 4 97 | 98 | ### Explanation 99 | 100 | Each time `square` is called the global variable `count` is increased by 1. 101 | 102 | Question 7 103 | ---------- 104 | 105 | Consider the following code. 106 | 107 | a = 3 108 | b = 6 109 | 110 | def f(a): 111 |     c = a + b 112 |     return c 113 | 114 | Which names occur in the global scope? 115 | 116 | ### Answer 117 | 118 | b, f, a 119 | 120 | Question 8 121 | ---------- 122 | 123 | Consider the following code. 124 | 125 | a = 3 126 | b = 6 127 | 128 | def f(a): 129 |     c = a + b 130 |     return c 131 | 132 | Which names occur in the local scope? 133 | 134 | ### Answer 135 | 136 | c, a 137 | 138 | Question 9 139 | ---------- 140 | 141 | Which of the following are valid calls to `create_frame`? 142 | 143 | ### Answer 144 | 145 | `f = simplegui.create_frame("My Frame", 100, 100)` 146 | `frame = simplegui.create_frame("Testing", 200, 200, 300)` 147 | 148 | ### Explanation 149 | 150 | `frame = simplegui.create_frame(100, 100, 100)` 151 |             This is not a valid call. The call is missing title argument. 152 | 153 | `frame = simplegui.create_frame("My Frame", 200, 200, 200, 200)` 154 |             This is not a valid call. The call has too many arguments. 155 | 156 | Question 10 157 | ----------- 158 | 159 | Which of the following are valid ways of making a canvas with a red background? 160 | 161 | ### Answer 162 | 163 | import simplegui 164 | frame = simplegui.create_frame("My Frame", 100, 100) 165 | frame.set_canvas_background("Red") 166 | frame.start() 167 | 168 | import simplegui 169 | frame = simplegui.create_frame("My Frame", 100, 100) 170 | frame.set_canvas_background("red") 171 | frame.start() -------------------------------------------------------------------------------- /Week 06/Week 6 A/Example Codes/Lecture 04.py: -------------------------------------------------------------------------------- 1 | # Mini-project #6 - Blackjack 2 | 3 | import simplegui 4 | import random 5 | 6 | # load card sprite - 950x392 - source: jfitz.com 7 | CARD_SIZE = (73, 98) 8 | card_images = simplegui.load_image("http://commondatastorage.googleapis.com/codeskulptor-assets/cards.jfitz.png") 9 | 10 | CARD_BACK_SIZE = (71, 96) 11 | card_back = simplegui.load_image("http://commondatastorage.googleapis.com/codeskulptor-assets/card_back.png") 12 | 13 | # initialize global variables 14 | deck = [] 15 | in_play = False 16 | outcome = "" 17 | score = 0 18 | 19 | # define globals for cards 20 | SUITS = ['C', 'S', 'H', 'D'] 21 | RANKS = ['A', '2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K'] 22 | VALUES = {'A':1, '2':2, '3':3, '4':4, '5':5, '6':6, '7':7, '8':8, '9':9, 'T':10, 'J':10, 'Q':10, 'K':10} 23 | 24 | 25 | # define card class 26 | class Card: 27 | def __init__(self, suit, rank): 28 | if (suit in SUITS) and (rank in RANKS): 29 | self.suit = suit 30 | self.rank = rank 31 | else: 32 | print "Invalid card: ", self.suit, self.rank 33 | 34 | def __str__(self): 35 | return self.suit + self.rank 36 | 37 | def get_suit(self): 38 | return self.suit 39 | 40 | def get_rank(self): 41 | return self.rank 42 | 43 | def draw(self, canvas, pos): 44 | card_loc = (card_size[0] * (0.5 + RANKS.index(self.rank)), card_size[1] * (0.5 + SUITS.index(self.suit))) 45 | canvas.draw_image(card_images, card_loc, card_size, [pos[0] + card_size[0] / 2, pos[1] + card_size[1] / 2], card_size) 46 | 47 | # define hand class 48 | class Hand: 49 | def __init__(self): 50 | pass # replace with your code 51 | 52 | def __str__(self): 53 | pass # replace with your code 54 | 55 | def add_card(self, card): 56 | pass # replace with your code 57 | 58 | # count aces as 1, if the hand has an ace, then add 10 to hand value if don't bust 59 | def get_value(self): 60 | pass # replace with your code 61 | 62 | def busted(self): 63 | pass # replace with your code 64 | 65 | def draw(self, canvas, p): 66 | pass # replace with your code 67 | 68 | 69 | # define deck class 70 | class Deck: 71 | def __init__(self): 72 | pass # replace with your code 73 | 74 | # add cards back to deck and shuffle 75 | def shuffle(self): 76 | pass # replace with your code 77 | 78 | def deal_card(self): 79 | pass # replace with your code 80 | 81 | 82 | #define callbacks for buttons 83 | def deal(): 84 | global outcome, in_play 85 | 86 | # your code goes here 87 | 88 | outcome = "" 89 | in_play = True 90 | 91 | def hit(): 92 | pass # replace with your code below 93 | 94 | # if the hand is in play, hit the player 95 | 96 | # if busted, assign an message to outcome, update in_play and score 97 | 98 | def stand(): 99 | pass # replace with your code below 100 | 101 | # if hand is in play, repeatedly hit dealer until his hand has value 17 or more 102 | 103 | # assign a message to outcome, update in_play and score 104 | 105 | def draw(canvas): 106 | pass # replace with your code below 107 | 108 | 109 | # initialization frame 110 | frame = simplegui.create_frame("Blackjack", 600, 600) 111 | frame.set_canvas_background("Green") 112 | 113 | #create buttons and canvas callback 114 | frame.add_button("Deal", deal, 200) 115 | frame.add_button("Hit", hit, 200) 116 | frame.add_button("Stand", stand, 200) 117 | frame.set_draw_handler(draw) 118 | 119 | # deal an initial hand 120 | 121 | # get things rolling 122 | frame.start() 123 | 124 | 125 | # Grading rubric - 18 pts total (scaled to 100) 126 | 127 | # 1 pt - The program opens a frame with the title "Blackjack" appearing on the canvas. 128 | # 3 pts - The program displays 3 buttons ("Deal", "Hit" and "Stand") in the control area. (1 pt per button) 129 | # 2 pts - The program graphically displays the player's hand using card sprites. 130 | # (1 pt if text is displayed in the console instead) 131 | # 2 pts - The program graphically displays the dealer's hand using card sprites. 132 | # Displaying both of the dealer's cards face up is allowable when evaluating this bullet. 133 | # (1 pt if text displayed in the console instead) 134 | # 1 pt - Hitting the "Deal" button deals out new hands to the player and dealer. 135 | # 1 pt - Hitting the "Hit" button deals another card to the player. 136 | # 1 pt - Hitting the "Stand" button deals cards to the dealer as necessary. 137 | # 1 pt - The program correctly recognizes the player busting. 138 | # 1 pt - The program correctly recognizes the dealer busting. 139 | # 1 pt - The program correctly computes hand values and declares a winner. 140 | # Evalute based on player/dealer winner messages. 141 | # 1 pt - The dealer's hole card is hidden until the hand is over when it is then displayed. 142 | # 2 pts - The program accurately prompts the player for an action with the messages 143 | # "Hit or stand?" and "New deal?". (1 pt per message) 144 | # 1 pt - The program keeps score correctly. -------------------------------------------------------------------------------- /Week 04/Week 4 Quiz/Quiz 4B.md: -------------------------------------------------------------------------------- 1 | Quiz 2 | ==== 3 | 4 | Question 1 5 | ---------- 6 | 7 | In Python, `[1, 2, 3]` is of type list. What is the name of the type of `(1, 2, 3)`? 8 | 9 | ### Answer 10 | 11 | Tuple 12 | 13 | Question 2 14 | ---------- 15 | 16 | Which of the following types of data are immutable in Python? 17 | 18 | ### Answer 19 | 20 | Numbers 21 | Strings 22 | Booleans 23 | Tuples 24 | 25 | Question 3 26 | ---------- 27 | 28 | Which of the following functions must include a `global point` declaration in order to change the global variable `point`? 29 | point = [0, 0] 30 | def function1(): 31 |     point[0] += 1 32 |     point[1] += 2 33 | def function2(): 34 |     point = [50, 50] 35 | 36 | ### Answer 37 | 38 | function2 39 | 40 | ### Explanation 41 | 42 | See details in the python code file along with this document. 43 | 44 | Question 4 45 | ---------- 46 | 47 | Consider the following program. 48 | x = range(5) 49 | ??? 50 | ??? 51 | We can replace the question marks with what two statements to make both variables have the value `[0, 1, 10, 3, 4]`? 52 | 53 | ### Answer 54 | 55 | 1. y = x 56 | x[2] = 10 57 | 2. y = x 58 | y[-3] = 10 59 | 60 | ### Explanation 61 | 62 | See details in the python code file along with this document. 63 | 64 | Question 5 65 | ---------- 66 | 67 | In our program, the variable `position` represents a 2D position on the canvas. We want to be able to change the position by some amount in variable `delta`. Why is the following code snippet incorrect? 68 | 69 | position = [50, 50] 70 | delta = [1, -2] 71 | ... 72 | position = position + delta 73 | 74 | Note that the ellipses represent that we might have code in between what is shown, but such code is irrelevant and omitted. 75 | 76 | ### Answer 77 | 78 | The `+` operator on lists does not mean addition of the numbers in a list. 79 | 80 | ### Explanation 81 | 82 | See details in the python code file along with this document. 83 | 84 | Question 6 85 | ---------- 86 | 87 | Consider the following program. 88 | 89 | a = ["green", "blue", "white", "black"] 90 | b = a 91 | c = list(a) 92 | d = c 93 | a[3] = "red" 94 | c[2] = a[1] 95 | b = a[1 : 3] 96 | b[1] = c[2] 97 | 98 | At the end of this code, to how many list objects do the variables refer? 99 | If you run the code and print the variables' values, you can begin to answer this question. After all, if two variables print differently, they certainly can't refer to the same object. However, if two variables print the same, you still need to determine whether they refer to the same object. One way is to step through the code while drawing reference diagrams. Another is to mutate one and see if others also mutate. 100 | 101 | ### Answer 102 | 103 | 3 104 | 105 | ### Explanation 106 | 107 | See details in the python code file along with this document. Run the corresponding code in Viz mode. 108 | 109 | Question 7 110 | ---------- 111 | 112 | Convert the following specification into code. Do the point and rectangle ever overlap? 113 | 114 | A point starts at `[10, 20]`. It repeatedly changes position by `[3, 0.7]` - e.g., under button or timer control. Meanwhile, a rectangle stays in place. Its corners are at `[50, 50]` (upper left), `[180, 50]` (upper right), `[180, 140]` (lower right), and `[50, 140]` (lower left). 115 | 116 | To check for overlap, i.e., collision, just run your code and check visually. You do not need to implement a point-rectangle collision test. However, we encourage you to think about how you would implement such a test. 117 | 118 | ### Answer 119 | 120 | Yes 121 | 122 | ### Explanation 123 | 124 | See details in the python code file along with this document. 125 | 126 | Question 8 127 | ---------- 128 | 129 | Assume we are using acceleration control for a spaceship in a game. That is, we regularly have the following updates: 130 | 131 | * The position is incremented by the time interval multiplied by the velocity. This happens on each draw event. 132 | * The velocity is incremented by the time interval multiplied by the acceleration. This happens on each draw event. 133 | * The acceleration is periodically incremented by some fixed vector (the same vector for each step). This could happen on keyboard or timer events. 134 | Assume that, initially, the ship is stationary and subject to no acceleration. What sort of trajectory will the spaceship fly in? 135 | 136 | ### Answer 137 | 138 | Straight line 139 | 140 | ### Explanation 141 | 142 | See details in the python code file along with this document. 143 | Since the change to acceleration is a fixed constant, the velocity will always be in the direction indicated by this constant. 144 | 145 | Question 9 146 | ----------- 147 | 148 | Write a Python program that initializes a global variable to 5. The keydown event handler updates this global variable by doubling it, while the keyup event handler updates it by decrementing it by 3. 149 | 150 | What is the value of the global variable after 12 separate key presses, i.e., pressing and releasing one key at a time, and repeating this 12 times in total? 151 | 152 | To test your code, the global variable's value should be 35 after 4 key presses. 153 | 154 | ### Answer 155 | 156 | 8195 157 | 158 | ### Explanation 159 | 160 | See details in the python code file along with this document. -------------------------------------------------------------------------------- /Week 05/Week 5 Quiz/Quiz 5A.md: -------------------------------------------------------------------------------- 1 | Quiz 2 | ==== 3 | 4 | Question 1 5 | ---------- 6 | 7 | What is the type of the parameter for a mouseclick handler? 8 | Refer to the CodeSkulptor [documentation](http://www.codeskulptor.org/docs.html#tabs-Python). 9 | 10 | * String. 11 | * List. 12 | * Tuple. 13 | * Boolean. 14 | * Number. 15 | * There is no parameter. 16 | 17 | ### Answer 18 | 19 | * Tuple 20 | 21 | Question 2 22 | ---------- 23 | 24 | Which of the following expressions mutate, i.e., change, list `my_list`? If you've forgotten what the operations do, you can look in the CodeSkulptor [documentation](http://www.codeskulptor.org/docs.html#tabs-Python). 25 | 26 | * `my_list.extend([10, 20])` 27 | * `another_list.extend(my_list)` 28 | * `my_list + [10, 20]` 29 | * `my_list.append(10)` 30 | * `my_list.reverse()` 31 | 32 | ### Answer 33 | 34 | * `my_list.extend([10, 20])` 35 | * `my_list.append(10)` 36 | * `my_list.reverse()` 37 | 38 | #### Explanation 39 | 40 | ```python 41 | my_list = [100, 200, 300] 42 | 43 | my_list.extend([10, 20]) 44 | print my_list 45 | # [100, 200, 300, 10, 20] 46 | 47 | my_list + [10, 20] 48 | print my_list 49 | # [100, 200, 300] 50 | 51 | my_list.append(10) 52 | print my_list 53 | # [100, 200, 300, 10] 54 | 55 | my_list.reverse() 56 | print my_list 57 | # [300, 200, 100] 58 | ``` 59 | 60 | Question 3 61 | ---------- 62 | 63 | We want to remove the element at the front of a list. For example, we want the following code to print `"apple"` and `["pear", "blueberry"]`, respectively. What function or method call should replace the question marks? 64 | 65 | ```python 66 | fruits = ["apple", "pear", "blueberry"] 67 | fruit = ??? 68 | print fruit, fruits 69 | ``` 70 | 71 | * `fruits.pop()` 72 | * `fruits.remove(0)` 73 | * `fruits.remove("apple")` 74 | * `fruits[0]` 75 | * `fruits[1:]` 76 | * `fruits.pop(0)` 77 | 78 | ### Answer 79 | 80 | * `fruits.pop(0)` 81 | 82 | #### Explanation 83 | ```python 84 | fruits = ["apple", "pear", "blueberry"] 85 | fruit = fruits.pop(0) 86 | print fruit, fruits 87 | # apple ['pear', 'blueberry'] 88 | ``` 89 | 90 | Question 4 91 | ---------- 92 | 93 | Which of the following uses of `range()` will generate the list `[2, 5, 8, 11, 14]`? 94 | First, think about what each of these returns, but also try each in [CodeSkulptor](http://www.codeskulptor.org/docs.html#tabs-Python). 95 | 96 | * `range(2, 15) * 3` 97 | * `range(2, 14, 3)` 98 | * `range(2, 15, 3)` 99 | 100 | ### Answer 101 | 102 | * `fruits.pop(0)` 103 | 104 | #### Explanation 105 | ```python 106 | print range(2, 15) * 3 107 | # [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14] 108 | 109 | print range(2, 14, 3) 110 | # [2, 5, 8, 11] 111 | 112 | print range(2, 15, 3) 113 | # [2, 5, 8, 11, 14] 114 | ``` 115 | 116 | Question 5 117 | ---------- 118 | 119 | To correctly compute the product of a list `numbers` of numbers, what statement should replace the question marks? 120 | 121 | ```python 122 | numbers = . 123 | ??? 124 | for n in numbers: 125 | product *= n 126 | ``` 127 | 128 | * `product = numbers[1]` 129 | * `product = []` 130 | * `product = 1` 131 | * `product = 0` 132 | * `product = numbers[0]` 133 | 134 | ### Answer 135 | 136 | * `product = 1` 137 | 138 | Question 6 139 | ---------- 140 | 141 | We can loop over strings, too! 142 | The following incomplete function is a simple, but inefficient, way to reverse a string. What line of code needs to replace the questions marks for the code to work correctly? 143 | 144 | ```python 145 | def reverse_string(s): 146 | """Returns the reversal of the given string.""" 147 | ??? 148 | for char in s: 149 | result = char + result 150 | return result 151 | 152 | print reverse_string("hello") 153 | ``` 154 | 155 | * `result = " "` 156 | * `result = 0` 157 | * `result = []` 158 | * `result = ""` 159 | 160 | ### Answer 161 | 162 | * `result = ""` 163 | 164 | Question 7 165 | ---------- 166 | 167 | Imagine a game on a map. At the beginning, we might want to randomly assign each player a starting point. Which of the following expressions may we use in place of the question marks to correctly implement this functionality? 168 | 169 | ```python 170 | import random 171 | 172 | def random_point(): 173 | """Returns a random point on a 100x100 grid.""" 174 | return (random.randrange(100), random.randrange(100)) 175 | 176 | def starting_points(players): 177 | """Returns a list of random points, one for each player.""" 178 | points = [] 179 | for player in players: 180 | point = random_point() 181 | ??? 182 | return points 183 | ``` 184 | 185 | * `points.append(point)` 186 | * `points.extend(point)` 187 | * `point.append(points)` 188 | * `point.extend(points)` 189 | * `points + point` 190 | * `points += point` 191 | 192 | ### Answer 193 | 194 | * `points.append(point)` 195 | 196 | Question 8 197 | ---------- 198 | 199 | The following function is supposed to check whether the given list of numbers is in ascending order. For example, we want `is_ascending([2, 6, 9, 12, 400])` to return `True`, while `is_ascending([4, 8, 2, 13])` should return `False`. 200 | 201 | ```python 202 | def is_ascending(numbers): 203 | """Returns whether the given list of numbers is in ascending order.""" 204 | for i in range(len(numbers)): 205 | if numbers[i+1] < numbers[i]: 206 | return False 207 | return True 208 | ``` 209 | However, the function doesn't quite work. Try it on the suggested tests to verify this for yourself. The easiest fix is to make a small change to the highlighted code. What should it be replaced with? 210 | 211 | * `range(len(numbers - 1))` 212 | * `range(len(numbers)) - 1` 213 | * `range(len(numbers) - 1)` 214 | * `range(1, len(numbers))` 215 | 216 | ### Answer 217 | 218 | * `range(len(numbers) - 1)` 219 | 220 | Question 9 221 | ---------- 222 | 223 | Turn the following English description into code: 224 | 225 | 1. Create a list with two numbers, 0 and 1, respectively. 226 | 2. For 40 times, add to the end of the list the sum of the last two numbers. 227 | 228 | What is the last number in the list? 229 | To test your code, if you repeat 10 times, rather than 40, your answer should be 89. 230 | 231 | ### Answer 232 | 233 | 165580141 234 | 235 | #### Explanation 236 | 237 | ```python 238 | list = [0, 1] 239 | i = 40 240 | while i > 0: 241 | list.append(list[-1] + list[-2]) 242 | i -= 1 243 | print list.pop() 244 | ``` -------------------------------------------------------------------------------- /Week 07/Week 7 Quiz/Quiz 7B.md: -------------------------------------------------------------------------------- 1 | Quiz 2 | ==== 3 | 4 | Question 1 5 | ---------- 6 | 7 | The class code provided for this week's mini-project supports an `ImageInfo` class to organize the data associated with the image. Consider an `ImageInfo` object of the following form: 8 | ```python 9 | ImageInfo([45, 45], [90, 90], 35) 10 | ``` 11 | What is the radius of the shape associated with this `ImageInfo` object? 12 | 13 | ### Answer 14 | 15 | 35 16 | 17 | #### Explanation 18 | This is the radius of the circle used in computing collisions involving the shape. 19 | 20 | Question 2 21 | ---------- 22 | 23 | Consider the provided `ImageInfo` and `Sprite` class code. Assume we want ten asteroids on the screen, each looking exactly alike and using the same image file. How many `ImageInfo` objects and how many `Sprite` objects should we create? 24 | 25 | * one `ImageInfo` object, one `Sprite` object 26 | * ten `ImageInfo` objects, one `Sprite` object 27 | * ten `ImageInfo` objects, ten `Sprite` objects 28 | * one `ImageInfo` object, ten `Sprite` objects 29 | 30 | ### Answer 31 | 32 | * one `ImageInfo` object, ten `Sprite` objects 33 | 34 | #### Explanation 35 | Since there is one image file, there should be one `ImageInfo`. Since there are ten displayed asteroids, each potentially with its own velocity and angle, there should be ten `Sprite` objects. 36 | 37 | Question 3 38 | ---------- 39 | 40 | The version of Rice Rocks that we will implement uses only a single asteroid image and spawns multiple instances of the provided `Sprite` class using this image. In the original Asteroids, a large asteroid split into two medium asteroids which themselves split into two small asteroids. 41 | If we only had one image and wanted to implement asteroids of varying sizes in our version, how should we do this? 42 | 43 | * Add a size attribute in the `ImageInfo` class and a size parameter to `ImageInfo.__init__`. Use this attribute when drawing the sprite. 44 | * Store the size in a global variable. Use this variable when drawing a sprite. 45 | * Store a list of sizes for each asteroid in a global variable. Use the corresponding size when drawing a sprite. 46 | * Add a size attribute in the `Sprite` class and a size parameter to `Sprite.__init__`. Use the size attribute when drawing the sprite. 47 | 48 | ### Answer 49 | 50 | * Add a size attribute in the `Sprite` class and a size parameter to `Sprite.__init__`. Use the size attribute when drawing the sprite. 51 | 52 | #### Explanation 53 | Adding a size attribute in the `Sprite` class allows each instance of a sprite to have a different size that can use in the draw method for the sprite. 54 | 55 | Question 4 56 | ---------- 57 | 58 | What is the supported range of sound volumes in `set_volume`? You can find out in the CodeSkulptor [documentation](http://www.codeskulptor.org/docs.html#tabs-Python). 59 | 60 | * 1 to 100 61 | * 0 to 1 62 | * 0 to 10 63 | * -1 to 1 64 | 65 | ### Answer 66 | 67 | * 0 to 1 68 | 69 | Question 5 70 | ---------- 71 | 72 | Assume you have code that loads and plays a sound. Unfortunately, you don't hear anything. Which of the following could be a reason? 73 | 74 | ### Answer 75 | 76 | * You have set the volume level to 0. 77 | * No file is found with the given URL. 78 | * A file found with the given URL isn't a sound file recognized by your browser. 79 | * The given URL exists, but is inaccessible due to network problems. 80 | * Your browser is loading a big sound file. Wait longer. 81 | 82 | Question 6 83 | ---------- 84 | 85 | Which of the following are valid HTML representations of the color blue? 86 | Refer to this page on [HTML color values](). 87 | 88 | * `"#FFFF00"` 89 | * `"#0000FF"` 90 | * `"blue"` 91 | * `"Red"` 92 | * `"rgb(0, 0, 255)"` 93 | 94 | ### Answer 95 | 96 | * `"#0000FF"` 97 | * `"blue"` 98 | * `"rgb(0, 0, 255)"` 99 | 100 | Question 7 101 | ---------- 102 | 103 | Imagine we are writing code for something like Rice Rocks, where things are moving in 2D toroidal space, i.e., the wrap around all four sides of the screen. How can we eliminate the duplicated code in the following function? 104 | ```python 105 | def move(position, vector): 106 | """Moves the position by the given vector in 2D toroidal space.""" 107 | position[0] = (position[0] + vector[0]) % SCREEN_SIZE[0] 108 | position[1] = (position[1] + vector[1]) % SCREEN_SIZE[1] 109 | ``` 110 | 111 | ### Answer And Explanation 112 | 113 | ```python 114 | def move(position, vector): 115 | """Moves the position by the given vector in 2D toroidal space.""" 116 | position = (position + vector) % SCREEN_SIZE 117 | ``` 118 | No, Invalid Python. 119 | 120 | ```python 121 | def move_dimension(dimension, position, vector): 122 | """Moves the position component by the given vector component in 1D toroidal space.""" 123 | position[dimension] = (position[dimension] + vector[dimension]) % SCREEN_SIZE[dimension] 124 | 125 | def move(position, vector): 126 | """Moves the position by the given vector in 2D toroidal space.""" 127 | move_dimension(0, position, vector) 128 | move_dimension(1, position, vector) 129 | ``` 130 | Yes, Valid Python Code. 131 | 132 | ```python 133 | def move(position, vector): 134 | position = [(pos + vec) % size for pos in position for vec in vector for size in SCREEN_SIZE] 135 | ``` 136 | No, this doesn't have the same behavior. 137 | 138 | ```python 139 | NUM_DIMENSIONS = 2 140 | def move(position, vector): 141 | """Moves the position by the given vector in 2D toroidal space.""" 142 | for d in range(NUM_DIMENSIONS): 143 | position[d] = (position[d] + vector[d]) % SCREEN_SIZE[d] 144 | ``` 145 | Yes, Valid Python Code. 146 | 147 | Question 8 148 | ---------- 149 | 150 | What is the primary reason for not duplicating code? It was the only reason mentioned in the Programming Tips #7 video. 151 | 152 | * You only need to get the code correct once. 153 | * It leads to faster code. 154 | * It takes less time to write the code. 155 | 156 | ### Answer 157 | 158 | * You only need to get the code correct once. 159 | 160 | Question 9 161 | ---------- 162 | 163 | What is Mike Massimino's greatest accomplishment? 164 | 165 | * Appearing on An Introduction to Interactive Programming in Python. 166 | * Receiving his PhD from MIT. 167 | * Being the first person to use Twitter in space. 168 | * Appearing on The Big Bang Theory. 169 | * Fixing the Hubble Space Telescope in space. 170 | 171 | ### Answer 172 | 173 | * Appearing on An Introduction to Interactive Programming in Python. 174 | 175 | #### Explanation 176 | 177 | Of course, how can you top this! -------------------------------------------------------------------------------- /Week 06/Week 6 Programming Assignment/Blackjack.py: -------------------------------------------------------------------------------- 1 | # Mini-project #6 - Blackjack 2 | 3 | import simplegui 4 | import random 5 | 6 | # load card sprite - 936x384 - source: jfitz.com 7 | CARD_SIZE = (72, 96) 8 | CARD_CENTER = (36, 48) 9 | card_images = simplegui.load_image("http://storage.googleapis.com/codeskulptor-assets/cards_jfitz.png") 10 | 11 | CARD_BACK_SIZE = (72, 96) 12 | CARD_BACK_CENTER = (36, 48) 13 | card_back = simplegui.load_image("http://storage.googleapis.com/codeskulptor-assets/card_jfitz_back.png") 14 | 15 | # initialize some useful global variables 16 | inPlay = False 17 | outcome = "" 18 | score = 0 19 | playerString = "PLAYER" 20 | dealerString = "DEALER" 21 | 22 | # define globals for cards 23 | SUITS = ('C', 'S', 'H', 'D') 24 | RANKS = ('A', '2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K') 25 | VALUES = {'A':1, '2':2, '3':3, '4':4, '5':5, '6':6, '7':7, '8':8, '9':9, 'T':10, 'J':10, 'Q':10, 'K':10} 26 | 27 | 28 | # define card class 29 | class Card: 30 | def __init__(self, suit, rank): 31 | if (suit in SUITS) and (rank in RANKS): 32 | self.suit = suit 33 | self.rank = rank 34 | else: 35 | self.suit = None 36 | self.rank = None 37 | print "Invalid card: ", suit, rank 38 | 39 | def __str__(self): 40 | return self.suit + self.rank 41 | 42 | def get_suit(self): 43 | return self.suit 44 | 45 | def get_rank(self): 46 | return self.rank 47 | 48 | def draw(self, canvas, pos): 49 | card_loc = (CARD_CENTER[0] + CARD_SIZE[0] * RANKS.index(self.rank), CARD_CENTER[1] + CARD_SIZE[1] * SUITS.index(self.suit)) 50 | canvas.draw_image(card_images, card_loc, CARD_SIZE, [pos[0] + CARD_CENTER[0], pos[1] + CARD_CENTER[1]], CARD_SIZE) 51 | 52 | def draw_back(self, canvas, pos): 53 | card_loc = (CARD_BACK_CENTER[0], CARD_BACK_CENTER[1]) 54 | canvas.draw_image(card_back, card_loc, CARD_BACK_SIZE, [pos[0] + CARD_BACK_CENTER[0] + 1, pos[1] + CARD_BACK_CENTER[1] + 1], CARD_BACK_SIZE) 55 | 56 | # define hand class 57 | class Hand: 58 | def __init__(self): 59 | """ Creates Hand object """ 60 | self.cards = [] 61 | 62 | def __str__(self): 63 | """ Returns a string representation of a hand """ 64 | handCards = "" 65 | for card in self.cards: 66 | handCards = handCards + str(card) + " " 67 | if len(handCards) == 0: 68 | return "Hand contains nothing." 69 | else: 70 | return "Hand contains " + handCards.strip() + "." 71 | 72 | def add_card(self, card): 73 | """ Adds a card object to a hand """ 74 | self.cards.append(card) 75 | 76 | def get_value(self): 77 | """ Computes the value of the hand """ 78 | """ Counts aces as 1, if the hand has an ace, then add 10 to hand value if it doesn't bust """ 79 | currentValue = 0 80 | isAcePresent = False 81 | for card in self.cards: 82 | rank = card.get_rank() 83 | currentValue += VALUES[rank] 84 | if rank == 'A': 85 | isAcePresent = True 86 | if isAcePresent and currentValue < 12: 87 | currentValue += 10 88 | return currentValue 89 | 90 | def draw(self, canvas, pos): 91 | """ Draws a hand on the canvas, uses the draw method for cards """ 92 | for card in self.cards: 93 | pos[0] = pos[0] + CARD_SIZE[0] + 30 94 | card.draw(canvas, pos) 95 | 96 | 97 | # define deck class 98 | class Deck: 99 | def __init__(self): 100 | """ Creates a Deck object """ 101 | self.cards = [] 102 | for suit in SUITS: 103 | for rank in RANKS: 104 | self.cards.append(Card(suit, rank)) 105 | 106 | def shuffle(self): 107 | """ Shuffles the deck, using random.shuffle() """ 108 | random.shuffle(self.cards) 109 | 110 | def deal_card(self): 111 | """ Deals a card object from the deck """ 112 | return self.cards.pop() 113 | 114 | def __str__(self): 115 | """ Returns a string representing the deck """ 116 | deckCards = "" 117 | for card in self.cards: 118 | deckCards = deckCards + str(card) + " " 119 | if len(deckCards) == 0: 120 | return "Deck contains nothing." 121 | else: 122 | return "Deck contains " + deckCards.strip() + "." 123 | 124 | 125 | #define event handlers for buttons 126 | def deal(): 127 | global outcome, score, inPlay, deck, playerHand, dealerHand, message 128 | if inPlay: 129 | inPlay = False 130 | score -= 1 131 | deal() 132 | else: 133 | playerHand = Hand() 134 | dealerHand = Hand() 135 | deck = Deck() 136 | deck.shuffle() 137 | playerHand.add_card(deck.deal_card()) 138 | playerHand.add_card(deck.deal_card()) 139 | dealerHand.add_card(deck.deal_card()) 140 | dealerHand.add_card(deck.deal_card()) 141 | outcome = "Hit or Stand?" 142 | message = "" 143 | inPlay = True 144 | 145 | def hit(): 146 | global message, outcome, score, inPlay, deck, playerHand 147 | if inPlay: 148 | if playerHand.get_value() <= 21: 149 | playerHand.add_card(deck.deal_card()) 150 | if playerHand.get_value() > 21: 151 | message = "You are BUSTED! You loose." 152 | score -= 1 153 | outcome = "New Deal?" 154 | inPlay = False 155 | 156 | def stand(): 157 | global message, playerHand, dealerHand, score, inPlay, deck, outcome 158 | if inPlay: 159 | while dealerHand.get_value() < 17: 160 | dealerHand.add_card(deck.deal_card()) 161 | if dealerHand.get_value() > 21: 162 | message = "Dealer BUSTED! You win." 163 | score += 1 164 | elif playerHand.get_value() > dealerHand.get_value(): 165 | message = "You win." 166 | score += 1 167 | else: 168 | message = "You loose." 169 | score -= 1 170 | outcome = "New Deal?" 171 | inPlay = False 172 | 173 | # draw handler 174 | def draw(canvas): 175 | canvas.draw_text("BLACKJACK", (150, 70), 50, "Aqua") 176 | canvas.draw_text(dealerString, (36, 185), 30, "Black") 177 | canvas.draw_text(playerString, (36, 385), 30, "Black") 178 | canvas.draw_text(outcome, (235, 385), 30, "Black") 179 | canvas.draw_text(message, (235, 185), 30, "Black") 180 | canvas.draw_text("Score " + str(score), (450, 115), 30, "Black") 181 | dealerHand.draw(canvas, [-65, 200]) 182 | playerHand.draw(canvas, [-65, 400]) 183 | if inPlay: 184 | dealerHand.cards[0].draw_back(canvas, [36, 199]) 185 | 186 | # initialization frame 187 | frame = simplegui.create_frame("Blackjack", 600, 600) 188 | frame.set_canvas_background("Green") 189 | 190 | #create buttons and canvas callback 191 | frame.add_button("Deal", deal, 200) 192 | frame.add_button("Hit", hit, 200) 193 | frame.add_button("Stand", stand, 200) 194 | frame.set_draw_handler(draw) 195 | 196 | 197 | # get things rolling 198 | deal() 199 | frame.start() 200 | 201 | # remember to review the gradic rubric -------------------------------------------------------------------------------- /Week 05/Week 5 Quiz/Quiz 5B.md: -------------------------------------------------------------------------------- 1 | Quiz 2 | ==== 3 | 4 | Question 1 5 | ---------- 6 | 7 | Which of the following expressions corresponds to a dictionary with no elements? 8 | 9 | * `{}` 10 | * `None` 11 | * `()` 12 | * `dict()` 13 | * `[]` 14 | 15 | ### Answer 16 | 17 | * `{}` 18 | * `dict()` 19 | 20 | Question 2 21 | ---------- 22 | 23 | Given an existing dictionary `favorites`, what Python statement adds the key `"fruit"` to this dictionary with the corresponding value `"blackberry"`? 24 | 25 | * `favorites["fruit" = "blackberry"]` 26 | * `favorites{"fruit" : "blackberry"}` 27 | * `favorites["fruit"] = "blackberry"` 28 | * `favorites = {"fruit" : "blackberry"}` 29 | 30 | ### Answer 31 | 32 | * `favorites["fruit"] = "blackberry"` 33 | 34 | #### Explanation 35 | 36 | ```python 37 | favorites = {"fruit" : "blackberry"} 38 | ``` 39 | This statement creates a new dictionary instead of adding to an existing dictionary. 40 | 41 | Question 3 42 | ---------- 43 | 44 | Keys in a dictionary can have which of the following types? 45 | 46 | * Numbers 47 | * Dictionaries 48 | * Tuples 49 | * Lists 50 | * Strings 51 | 52 | ### Answer 53 | 54 | * Numbers 55 | * Tuples 56 | * Strings 57 | 58 | #### Explanation 59 | Keys in a dictionary can have any immutable data type. 60 | 61 | Question 4 62 | ---------- 63 | 64 | Values in a dictionary can have which of the following types? 65 | 66 | * Dictionaries 67 | * Tuples 68 | * Lists 69 | * Numbers 70 | 71 | ### Answer 72 | 73 | * Dictionaries 74 | * Tuples 75 | * Lists 76 | * Numbers 77 | 78 | #### Explanation 79 | Values in a dictionary can be of any data type. 80 | 81 | Question 5 82 | ---------- 83 | 84 | We often want to loop over all the key/value pairs in a dictionary. Assume the variable `my_dict` stores a dictionary. One way of looping like this is as follows: 85 | 86 | ```python 87 | for key in my_dict: 88 | value = my_dict[key] 89 | ... 90 | ``` 91 | However, there is a better way. We can instead write the following: 92 | ```python 93 | for key, value in ???: 94 | ... 95 | ``` 96 | What code should replace the question marks so that the two forms are equivalent? Refer to the video on dictionaries or the CodeSkulptor [documentation](http://www.codeskulptor.org/docs.html#tabs-Python). 97 | 98 | * `items(my_dict)` 99 | * `my_dict.keys()` 100 | * `list(my_dict)` 101 | * `my_dict.values()` 102 | * `my_dict.keys_values()` 103 | * `my_dict.items()` 104 | 105 | ### Answer 106 | 107 | * `my_dict.items()` 108 | 109 | Question 6 110 | ---------- 111 | 112 | Conceptually, the purpose of a dictionary is to represent a relationship between two collections of data - each key in the dictionary is related to one value. Which of the following situations are instances of such a relationship? 113 | Do not include situations where you have to introduce additional information in order to fit them into such a relationship. 114 | 115 | ### Answer and Explanation 116 | 117 | * Storing names and IDs (identification numbers). 118 | Yes, map each ID (key) to the corresponding name (value). Each ID should be unique - otherwise it shouldn't be considered an ID. 119 | * Storing `x` and `y` coordinates of an arbitrary collection of 2-dimensional points. 120 | Not in general. This would make sense if the points were for a function, so that each x coordinate occurred at most once. 121 | * Storing where each person lives. 122 | Yes, map each person (key) to the corresponding address (value). 123 | * Computing averages. 124 | No, dictionaries don't compute anything. 125 | 126 | Note that it is possible to use dictionaries to represent sets and ordered collections. However, the focus of this question is on the relationship between data. 127 | 128 | Question 7 129 | ---------- 130 | 131 | Assume we have the following definition: 132 | ```python 133 | def is_even(number): 134 | """Returns whether the number is even.""" 135 | return number % 2 == 0 136 | ``` 137 | Which of the following will compute a list of all of the even elements of list `my_list`? 138 | Refer to this week's Programming Tips video about list comprehensions. Also, try each example in [CodeSkulptor](http://www.codeskulptor.org/) before answering the question. 139 | 140 | * `[n for n in my_list if is_even(n)]` 141 | * `[number for number in my_list if is_even(number)]` 142 | * `[is_even(number) for number in my_list]` 143 | * `[if is_even(number): number for number in my_list]` 144 | 145 | ### Answer 146 | 147 | * `[n for n in my_list if is_even(n)]` 148 | * `[number for number in my_list if is_even(number)]` 149 | 150 | #### Explanation 151 | * `[is_even(number) for number in my_list]` 152 | Returns a list of Booleans. 153 | * `[if is_even(number): number for number in my_list]` 154 | Syntactically incorrect. 155 | 156 | Question 8 157 | ---------- 158 | 159 | You have the following code. The goal is to display a portion of the image, rescaling it to fill the canvas. 160 | 161 | ```python 162 | import simplegui 163 | 164 | frame_size = [200, 200] 165 | image_size = [1521, 1818] 166 | 167 | def draw(canvas): 168 | canvas.draw_image(image, image_size, [image_size[0] / 2, image_size[1] / 2], [frame_size[0] / 2, frame_size[1] / 2], frame_size) 169 | 170 | frame = simplegui.create_frame("test", frame_size[0], frame_size[1]) 171 | frame.set_draw_handler(draw) 172 | image = simplegui.load_image("http://commondatastorage.googleapis.com/codeskulptor-assets/gutenberg.jpg") 173 | 174 | frame.start() 175 | ``` 176 | Run it, and observe that nothing is displayed in the frame. What is the problem? 177 | 178 | * The file doesn't exist. 179 | * The file is not an image. 180 | * The source arguments in `draw_image` are incorrect. We are trying to load pixels that are not within the image, and thus the draw fails. 181 | * The destination arguments in `draw_image` are incorrect. We aren't specifying values that would draw the image on this size canvas. 182 | * One or more of the `draw_image` arguments are of the wrong type. 183 | 184 | ### Answer 185 | 186 | * The source arguments in `draw_image` are incorrect. We are trying to load pixels that are not within the image, and thus the draw fails. 187 | 188 | Question 9 189 | ---------- 190 | 191 | Write a CodeSkulptor program that loads and draws the following image: 192 | [http://commondatastorage.googleapis.com/codeskulptor-assets/alphatest.png](http://commondatastorage.googleapis.com/codeskulptor-assets/alphatest.png) with a source center of [220, 100] and a source size of [100, 100]. What one word appears in the canvas? If a letter is capitalized in the image, enter it as a capital. 193 | Note that you do have to position the image as stated to see the correct word. 194 | 195 | ### Answer 196 | 197 | `tin` 198 | 199 | #### Explanation 200 | 201 | ```python 202 | import simplegui 203 | image = simplegui.load_image("http://commondatastorage.googleapis.com/codeskulptor-assets/alphatest.png") 204 | frame_size = [300, 300] 205 | image_size = [380, 287] 206 | def draw(canvas): 207 | canvas.draw_image(image, [220, 100], [100, 100], [frame_size[0] / 2, frame_size[1] / 2], frame_size) 208 | frame = simplegui.create_frame("test", frame_size[0], frame_size[1]) 209 | frame.set_draw_handler(draw) 210 | frame.start() 211 | ``` -------------------------------------------------------------------------------- /Week 07/Week 7 Quiz/Quiz 7A.md: -------------------------------------------------------------------------------- 1 | Quiz 2 | ==== 3 | 4 | Question 1 5 | ---------- 6 | 7 | Let's define a class for 2-dimensional points. 8 | ```python 9 | class Point2D: 10 | def __init__(self, x = 0, y = 0): 11 | self.x = x 12 | self.y = y 13 | 14 | def translate(self, deltax = 0, deltay = 0): 15 | """Translate the point in the x direction by deltax 16 | and in the y direction by deltay.""" 17 | self.x += deltax 18 | self.y += deltay 19 | 20 | ... 21 | 22 | ``` 23 | Which of the following code snippets are valid usages of the `Point2D` initializer and its `translate` method? For your first attempt at this problem, we suggest that you try to answer without using CodeSkulptor. 24 | 25 | ### Answer And Explanation 26 | 27 | ```python 28 | point = Point2D(3, 9) 29 | point.translate(5, -2) 30 | ``` 31 | Yes, it is a valid code snippet. 32 | 33 | ```python 34 | point = Point2D(3, 9) 35 | translate(point, 5, -2) 36 | ``` 37 | No, `translate` is not defined globally. It is defined only for `Point2D` objects. 38 | 39 | ```python 40 | point1 = Point2D(3, 9) 41 | point2 = Point2D() 42 | point2.translate(20, 4) 43 | ``` 44 | Yes, you can define multiple `Point2D` objects. Furthermore, the initializer is defined so that you don't have to provide arguments to `Point2D()`. 45 | 46 | ```python 47 | Point2D(3, 9) 48 | Point2D.translate(5, -2) 49 | ``` 50 | No, it is not a valid code snippet. 51 | 52 | Question 2 53 | ---------- 54 | 55 | Let's continue to use the same class for 2-dimensional points. 56 | ```python 57 | class Point2D: 58 | def __init__(self, x = 0, y = 0): 59 | self.x = x 60 | self.y = y 61 | 62 | def translate(self, deltax = 0, deltay = 0): 63 | """Translate the point in the x direction by deltax 64 | and in the y direction by deltay.""" 65 | self.x += deltax 66 | self.y += deltay 67 | 68 | ... 69 | 70 | ``` 71 | Which of the following code snippets are valid usages of the `Point2D` initializer and its `translate` method? For your first attempt at this problem, we suggest that you try to answer without using CodeSkulptor. 72 | 73 | ### Answer And Explanation 74 | 75 | ```python 76 | points = [(2, 5), (8, 3), (0, 2)] 77 | for point in points: 78 | point.translate(-1, -1) 79 | ``` 80 | No, `translate` is defined only on a `Point2D` object, not on a tuple. 81 | 82 | ```python 83 | point0 = Point2D(2, 5) 84 | point1 = Point2D(8, 3) 85 | point2 = Point2D(0, 2) 86 | points = [point0, point1, point2] 87 | points.translate(-1, -1) 88 | ``` 89 | No, `translate` is defined only on a `Point2D` object, not on a list of `Point2D` objects. 90 | 91 | ```python 92 | points = [Point2D(2, 5), Point2D(8, 3), Point2D(0, 2)] 93 | for point in points: 94 | point.translate(-1, -1) 95 | ``` 96 | Yes, it is a valid code snippet. 97 | 98 | Question 3 99 | ---------- 100 | 101 | Let's continue to use the same class for 2-dimensional points. 102 | ```python 103 | class Point2D: 104 | def __init__(self, x = 0, y = 0): 105 | self.x = x 106 | self.y = y 107 | 108 | def translate(self, deltax = 0, deltay = 0): 109 | """Translate the point in the x direction by deltax 110 | and in the y direction by deltay.""" 111 | self.x += deltax 112 | self.y += deltay 113 | 114 | ... 115 | 116 | ``` 117 | Which of the following code snippets are valid usages of the `Point2D` initializer and its `translate` method? For your first attempt at this problem, we suggest that you try to answer without using CodeSkulptor. 118 | 119 | ```python 120 | point = Point2D(3, 6) 121 | lst = list(point) 122 | ``` 123 | 124 | ```python 125 | point = Point2D(3, 6) 126 | tup = tuple(point) 127 | ``` 128 | 129 | ```python 130 | point = Point2D(3, 6) 131 | s = str(point) 132 | newpoint = Point(s) 133 | ``` 134 | 135 | ```python 136 | point = Point2D(3, 6) 137 | s = str(point) 138 | ``` 139 | 140 | ### Answer 141 | 142 | ```python 143 | point = Point2D(3, 6) 144 | s = str(point) 145 | ``` 146 | 147 | Question 4 148 | ---------- 149 | 150 | In SimpleGUI, the function `draw_image` takes an optional sixth parameter that determines the angle of rotation of the destination rectangle around its center. Do positive values for the angle rotate the image clockwise or counterclockwise? Is the angle specified in degrees or radians? 151 | Refer to the CodeSkulptor [documentation](http://www.codeskulptor.org/docs.html#tabs-Python). 152 | 153 | * clockwise, radians 154 | * counterclockwise, degrees 155 | * counterclockwise, radians 156 | * clockwise, degrees 157 | 158 | ### Answer 159 | 160 | * clockwise, radians 161 | 162 | Question 5 163 | ---------- 164 | 165 | One interesting extension of Rice Rocks would be to have two ships, with each controlled by a separate player, instead of one single ship. Using the provided class definitions, what is the best way to represent the two ships in this new variant? 166 | 167 | * Copy the `Ship` class code, e.g., 168 | ```python 169 | class Another_Ship: 170 | def __init__(self, pos, vel, angle): 171 | ... 172 | ... 173 | ``` 174 | Then create two ship objects, one of each class, assigning each to a global variable. 175 | ```python 176 | ship1 = Ship(...) 177 | ship2 = Another_Ship(...) 178 | ``` 179 | 180 | * Add another call to the `Ship` constructor, assigning the result to another global variable. 181 | ```python 182 | ship1 = Ship(...) 183 | ship2 = Ship(...) 184 | ``` 185 | 186 | * In the `Ship` class definition, change the variables `pos`, `vel`, `angle` to be lists of two values each. Then, change each method to take an additional number argument that indicates which ship should be used. Thus, when we call the constructor now, we are creating both ships. 187 | ```python 188 | ships = Ship(...) 189 | ``` 190 | 191 | * In the `Ship` class definition, duplicate every method. For example, `Ship.draw1(...)` would be used to draw the first ship, while `Ship.draw2(...)` would be used to draw the second ship. 192 | 193 | ### Answer 194 | 195 | * Add another call to the `Ship` constructor, assigning the result to another global variable. 196 | ```python 197 | ship1 = Ship(...) 198 | ship2 = Ship(...) 199 | ``` 200 | 201 | Question 6 202 | ---------- 203 | 204 | Which of the following browsers fully support MP3 audio files? Refer to the CodeSkulptor [documentation](http://www.codeskulptor.org/docs.html#tabs-Python). 205 | 206 | ### Answer And Explanation 207 | 208 | * Firefox 209 | No, Firefox currently supports MP3 files on some, but not all systems. 210 | * Safari 211 | Yes, Safari fully supports MP3 audio files. 212 | * Chrome 213 | Yes, Chrome fully supports MP3 audio files. 214 | 215 | Question 7 216 | ---------- 217 | 218 | Consider a spaceship where the ship's thrusters can accelerate the ship by 10 pixels per second for each second that the thrust key is held down. If the friction induces a deceleration that is 10% of the ship's velocity per second, what is the maximal velocity of the ship? If you are having trouble, consider writing a short program to help understand this problem. 219 | 220 | * Around 1000 pixels per second. 221 | * Around 10 pixels per second. 222 | * The ship has no maximal velocity. It can reach any velocity the player desires if you hold the thrust key down long enough. 223 | * Around 100 pixels per second. 224 | 225 | ### Answer 226 | 227 | * Around 100 pixels per second. 228 | 229 | #### Explanation 230 | At a velocity of 100 pixels per second, friction would induce a deceleration of 10 pixels per second. This deceleration would exactly cancel an acceleration of 10 pixels per second from the thrusters. We used "around" here since the true maximal velocity depends on the rate at which the frame is drawn. -------------------------------------------------------------------------------- /Week 03/Week 3 Quiz/Quiz 3B.md: -------------------------------------------------------------------------------- 1 | Quiz 3B 2 | ======= 3 | 4 | Question 1 5 | ---------- 6 | 7 | When the following code is executed, how many times is `timer_handler` called? 8 | ``` 9 | import simplegui 10 | 11 | def timer_handler(): 12 | . 13 | 14 | timer = simplegui.create_timer(10, timer_handler) 15 | timer.start() 16 | ``` 17 | The body of `timer_handler` isn't given, as it is irrelevant for this question. You may want to finish the code and run it before submitting your answer. 18 | 19 | ### Answer 20 | 21 | Unlimited - It is called repeatedly until you stop the program. 22 | 23 | ### Explanation 24 | 25 | See details in the python code file along with this document. 26 | 27 | Question 2 28 | ---------- 29 | 30 | You want a timer to create exactly 1000 events. Which of the following solutions are possible? 31 | 32 | ### Answer 33 | 34 | * Have a global counter for the number of timer calls. In the timer handler, increment the counter. In the timer handler, check the count and possibly stop the timer. 35 | 36 | ### Explanation 37 | 38 | See details in the python code file along with this document. 39 | 40 | * In the timer handler, have a local counter for the number of timer calls. In the timer handler, increment the counter. In the timer handler, check the count and possibly stop the timer. ==> With a local counter, you'll forget the count between calls. 41 | * Specify the number of timer events when creating the timer. ==> There is no such option. 42 | * Have a global counter for the number of timer calls. Outside the timer handler, increment the counter. Outside the timer handler, check the count and possibly stop the timer. ==> You can't count the timer calls outside of the handler. 43 | 44 | Question 3 45 | ---------- 46 | 47 | How do you change the frequency of a running timer, either increasing or decreasing the frequency? E.g., in the code below, we want code at the question marks that changes the timer. 48 | ``` 49 | . 50 | timer = simplegui.create_timer(1000, timer_handler) 51 | timer.start() 52 | . 53 | ??? 54 | ``` 55 | 56 | ### Answer 57 | 58 | You can't. But, you can stop this timer, and start a new one with a different frequency and same handler. 59 | ``` 60 | timer.stop() 61 | timer = simplegui.create_timer(300, timer_handler) 62 | timer.start() 63 | ``` 64 | 65 | ### Explanation 66 | 67 | That we use the same variable timer is irrelevant. This is a new timer. 68 | See details in the python code file along with this document. 69 | 70 | Question 4 71 | ---------- 72 | 73 | How many timers can you have running at once? 74 | 75 | ### Answer 76 | 77 | Unlimited 78 | 79 | ### Explanation 80 | 81 | See details in the python code file along with this document. 82 | 83 | Question 5 84 | ---------- 85 | 86 | The function time.time() is used in Python to keep track of time. What unit of time is associated with the value returned by time.time()? 87 | 88 | ### Answer 89 | 90 | Second 91 | 92 | ### Explanation 93 | 94 | time.time( ) ==> Returns the current time instant, a floating-point number of seconds since the epoch(12:00am, January 1, 1970). 95 | See details in the python code file along with this document. 96 | 97 | Question 6 98 | ---------- 99 | 100 | In Python, the `time` module can be used to determine the current time. This module includes the method `time` which returns the current system time in seconds since a date referred as the Epoch. The Epoch is fixed common date shared by all Python installations. Using the date of the Epoch and the current system time, an application such as a clock or calendar can compute the current time/date using basic arithmetic. 101 | Write a CodeSkulptor program that experiments with the method `time.time()` and determines what date and time corresponds to the Epoch. Enter the year of the Epoch as a four digit number. (Remember to `import time`.) 102 | 103 | ### Answer 104 | 105 | 1970 106 | 107 | ### Explanation 108 | 109 | Jan 1, 1970 UTC. 110 | Calculate the number of seconds in a year. Then use the current system time in seconds as well as today's date to compute the year of the Epoch. 111 | 112 | Question 7 113 | ---------- 114 | 115 | The Python code below uses a timer to execute the function `update()` 10 times, computing a good approximation to a common mathematical function. Examine the code, and run it while varying the input value `n`. 116 | What is the common name for what this computes? 117 | ``` 118 | # Mystery computation in Python 119 | # Takes input n and computes output named result 120 | 121 | import simplegui 122 | 123 | # global state 124 | 125 | result = 1 126 | iteration = 0 127 | max_iterations = 10 128 | 129 | # helper functions 130 | 131 | def init(start): 132 | """Initializes n.""" 133 | global n 134 | n = start 135 | print "Input is", n 136 | 137 | def get_next(current): 138 | """??? Part of mystery computation.""" 139 | return 0.5 * (current + n / current) 140 | 141 | # timer callback 142 | 143 | def update(): 144 | """??? Part of mystery computation.""" 145 | global iteration, result 146 | iteration += 1 147 | # Stop iterating after max_iterations 148 | if iteration >= max_iterations: 149 | timer.stop() 150 | print "Output is", result 151 | else: 152 | result = get_next(result) 153 | 154 | # register event handlers 155 | 156 | timer = simplegui.create_timer(1, update) 157 | 158 | # start program 159 | init(13) 160 | timer.start() 161 | ``` 162 | 163 | ### Answer 164 | 165 | Square root of n 166 | 167 | ### Explanation 168 | 169 | Such a computation is more typically written using loops, which we haven't introduced yet in this course. However, this example illustrates timers and handler/callback functions and one possible use for them. 170 | See details in the python code file along with this document. 171 | 172 | Question 8 173 | ---------- 174 | 175 | Given any initial natural number, consider the sequence of numbers generated by repeatedly following the rule: 176 | * divide by two if the number is even or 177 | * multiply by 3 and add 1 if the number is odd. 178 | 179 | The Collatz conjecture states that this sequence always terminates at 1. For example, the sequence generated by 23 is: 180 | 23, 70, 35, 106, 53, 160, 80, 40, 20, 10, 5, 16, 8, 4, 2, 1 181 | Write a Python program that takes a global variable `n` and uses a timer callback to repeatedly apply the rule above to `n`. Use the code from the previous question as a template. I suggest that your code prints out the sequence of numbers generated by this rule. Run this program for `n` = 217. What is the largest number in the sequence generated by this starting value? 182 | To test your code, starting at `n` = 23 generates a sequence with a maximum value of 160. 183 | 184 | ### Answer 185 | 186 | 726 187 | 188 | ### Explanation 189 | 190 | Such a computation is more typically written using loops, but this exercise is illustrating the usage of timers and callback functions. 191 | See details in the python code file along with this document. 192 | 193 | Question 9 194 | ----------- 195 | 196 | CodeSkulptor runs your Python code by converting it into Javascript when you click the "Run" button and then executing this Javascript in your web browser. Open this [example](http://www.codeskulptor.org/#examples-explosion_animation.py "Animation of explosion using 2D sprite sheet") and run the provided code. If the SimpleGUI frame is spawned as a separate window, you should see an animation of an explosion in the canvas for this frame. If the SimpleGUI frame is spawned as a separate tab on top of the existing window containing the code (as happens in some browser configurations), the animation will "freeze" and a single static image is displayed. (If the SimpleGUI frame spawns as a separate window, you can also cause the animation to freeze by opening a new tab on top of the code window.) 197 | As explained in the FAQ, what is the explanation for this behavior? 198 | 199 | ### Answer 200 | 201 | To save resources, modern browsers only execute the Javascript associated with the topmost tab of a window. The animation freezes since the code tab and its associated Javascript is no longer the topmost tab. 202 | 203 | ### Explanation 204 | 205 | Correct. If your browser does happen to open a SimpleGUI frame as a new tab on top of the existing code tab, "pull" this tab off of the top of the current window to create a new separate window. -------------------------------------------------------------------------------- /Week 07/Week 7 Programming Assignment/Spaceship.py: -------------------------------------------------------------------------------- 1 | # program template for Spaceship 2 | import simplegui 3 | import math 4 | import random 5 | 6 | # globals for user interface 7 | WIDTH = 800 8 | HEIGHT = 600 9 | score = 0 10 | lives = 3 11 | time = 0 12 | 13 | class ImageInfo: 14 | def __init__ (self, center, size, radius = 0, lifespan = None, animated = False): 15 | self.center = center 16 | self.size = size 17 | self.radius = radius 18 | if lifespan: 19 | self.lifespan = lifespan 20 | else: 21 | self.lifespan = float ('inf') 22 | self.animated = animated 23 | 24 | def get_center (self): 25 | return self.center 26 | 27 | def get_size (self): 28 | return self.size 29 | 30 | def get_radius (self): 31 | return self.radius 32 | 33 | def get_lifespan (self): 34 | return self.lifespan 35 | 36 | def get_animated (self): 37 | return self.animated 38 | 39 | 40 | # art assets created by Kim Lathrop, may be freely re-used in non-commercial projects, please credit Kim 41 | # debris images - debris1_brown.png, debris2_brown.png, debris3_brown.png, debris4_brown.png 42 | # debris1_blue.png, debris2_blue.png, debris3_blue.png, debris4_blue.png, debris_blend.png 43 | debris_info = ImageInfo ([320, 240], [640, 480]) 44 | debris_image = simplegui.load_image ("http://commondatastorage.googleapis.com/codeskulptor-assets/lathrop/debris2_blue.png") 45 | 46 | # nebula images - nebula_brown.png, nebula_blue.png 47 | nebula_info = ImageInfo ([400, 300], [800, 600]) 48 | nebula_image = simplegui.load_image ("http://commondatastorage.googleapis.com/codeskulptor-assets/lathrop/nebula_blue.f2014.png") 49 | 50 | # splash image 51 | splash_info = ImageInfo ([200, 150], [400, 300]) 52 | splash_image = simplegui.load_image ("http://commondatastorage.googleapis.com/codeskulptor-assets/lathrop/splash.png") 53 | 54 | # ship image 55 | ship_info = ImageInfo ([45, 45], [90, 90], 35) 56 | ship_image = simplegui.load_image ("http://commondatastorage.googleapis.com/codeskulptor-assets/lathrop/double_ship.png") 57 | 58 | # missile image - shot1.png, shot2.png, shot3.png 59 | missile_info = ImageInfo ([5,5], [10, 10], 3, 50) 60 | missile_image = simplegui.load_image ("http://commondatastorage.googleapis.com/codeskulptor-assets/lathrop/shot2.png") 61 | 62 | # asteroid images - asteroid_blue.png, asteroid_brown.png, asteroid_blend.png 63 | asteroid_info = ImageInfo ([45, 45], [90, 90], 40) 64 | asteroid_image = simplegui.load_image ("http://commondatastorage.googleapis.com/codeskulptor-assets/lathrop/asteroid_blue.png") 65 | 66 | # animated explosion - explosion_orange.png, explosion_blue.png, explosion_blue2.png, explosion_alpha.png 67 | explosion_info = ImageInfo ([64, 64], [128, 128], 17, 24, True) 68 | explosion_image = simplegui.load_image ("http://commondatastorage.googleapis.com/codeskulptor-assets/lathrop/explosion_alpha.png") 69 | 70 | # sound assets purchased from sounddogs.com, please do not redistribute 71 | soundtrack = simplegui.load_sound ("http://commondatastorage.googleapis.com/codeskulptor-assets/sounddogs/soundtrack.mp3") 72 | missile_sound = simplegui.load_sound ("http://commondatastorage.googleapis.com/codeskulptor-assets/sounddogs/missile.mp3") 73 | missile_sound.set_volume (.5) 74 | ship_thrust_sound = simplegui.load_sound ("http://commondatastorage.googleapis.com/codeskulptor-assets/sounddogs/thrust.mp3") 75 | explosion_sound = simplegui.load_sound ("http://commondatastorage.googleapis.com/codeskulptor-assets/sounddogs/explosion.mp3") 76 | 77 | # helper functions to handle transformations 78 | def angle_to_vector (ang): 79 | return [math.cos (ang), math.sin (ang)] 80 | 81 | def dist (p, q): 82 | return math.sqrt (((p[0] - q[0]) ** 2) + ((p[1] - q[1]) ** 2)) 83 | 84 | 85 | # Ship class 86 | class Ship: 87 | def __init__ (self, pos, vel, angle, image, info): 88 | self.pos = [pos[0], pos[1]] 89 | self.vel = [vel[0], vel[1]] 90 | self.thrust = False 91 | self.angle = angle 92 | self.angle_vel = 0 93 | self.image = image 94 | self.image_center = info.get_center () 95 | self.image_size = info.get_size () 96 | self.radius = info.get_radius () 97 | 98 | def draw (self, canvas): 99 | if self.thrust: 100 | canvas.draw_image (self.image, [130, 45], self.image_size, self.pos, self.image_size, self.angle) 101 | else: 102 | canvas.draw_image (self.image, self.image_center, self.image_size, self.pos, self.image_size, self.angle) 103 | 104 | def update (self): 105 | friction = 0.20 / 60 106 | acc_scale = 0.08 107 | self.angle += self.angle_vel 108 | self.pos[0] = (self.pos[0] + self.vel[0]) % WIDTH 109 | self.pos[1] = (self.pos[1] + self.vel[1]) % HEIGHT 110 | self.vel[0] *= (1 - friction) 111 | self.vel[1] *= (1 - friction) 112 | if self.thrust: 113 | forward = angle_to_vector (self.angle) 114 | self.vel[0] += forward[0] * acc_scale 115 | self.vel[1] += forward[1] * acc_scale 116 | 117 | def increase_angle_vel (self): 118 | self.angle_vel += 0.03 119 | 120 | def decrease_angle_vel (self): 121 | self.angle_vel -= 0.03 122 | 123 | def update_thrust (self, isThrustOn): 124 | self.thrust = isThrustOn 125 | if self.thrust: 126 | ship_thrust_sound.rewind () 127 | ship_thrust_sound.play () 128 | else: 129 | ship_thrust_sound.pause () 130 | 131 | def shoot_missile (self): 132 | global a_missile 133 | forward = angle_to_vector (self.angle) 134 | missile_position = [self.pos[0] + forward[0] * self.radius, self.pos[1] + forward[1] * self.radius] 135 | missile_velocity = [self.vel[0] + forward[0] * 6, self.vel[1] + forward[1] * 6] 136 | a_missile = Sprite (missile_position, missile_velocity, self.angle, 0, missile_image, missile_info, missile_sound) 137 | 138 | 139 | # Sprite class 140 | class Sprite: 141 | def __init__(self, pos, vel, ang, ang_vel, image, info, sound = None): 142 | self.pos = [pos[0],pos[1]] 143 | self.vel = [vel[0],vel[1]] 144 | self.angle = ang 145 | self.angle_vel = ang_vel 146 | self.image = image 147 | self.image_center = info.get_center() 148 | self.image_size = info.get_size() 149 | self.radius = info.get_radius() 150 | self.lifespan = info.get_lifespan() 151 | self.animated = info.get_animated() 152 | self.age = 0 153 | if sound: 154 | sound.rewind() 155 | sound.play() 156 | 157 | def draw(self, canvas): 158 | canvas.draw_image (self.image, self.image_center, self.image_size, self.pos, self.image_size, self.angle) 159 | 160 | def update(self): 161 | self.angle += self.angle_vel 162 | self.pos[0] = (self.pos[0] + self.vel[0]) % WIDTH 163 | self.pos[1] = (self.pos[1] + self.vel[1]) % HEIGHT 164 | 165 | 166 | # key handlers 167 | def down (key): 168 | if key == simplegui.KEY_MAP['left']: 169 | my_ship.decrease_angle_vel () 170 | elif key == simplegui.KEY_MAP['right']: 171 | my_ship.increase_angle_vel () 172 | elif key == simplegui.KEY_MAP['space']: 173 | my_ship.shoot_missile () 174 | elif key == simplegui.KEY_MAP['up']: 175 | my_ship.update_thrust (True) 176 | 177 | 178 | def up (key): 179 | if key == simplegui.KEY_MAP['left']: 180 | my_ship.increase_angle_vel () 181 | elif key == simplegui.KEY_MAP['right']: 182 | my_ship.decrease_angle_vel () 183 | elif key == simplegui.KEY_MAP['up']: 184 | my_ship.update_thrust (False) 185 | 186 | 187 | def draw (canvas): 188 | global time 189 | # animiate background 190 | time += 1 191 | wtime = (time / 4) % WIDTH 192 | center = debris_info.get_center () 193 | size = debris_info.get_size () 194 | canvas.draw_image (nebula_image, nebula_info.get_center(), nebula_info.get_size(), [WIDTH / 2, HEIGHT / 2], [WIDTH, HEIGHT]) 195 | canvas.draw_image (debris_image, center, size, (wtime - WIDTH / 2, HEIGHT / 2), (WIDTH, HEIGHT)) 196 | canvas.draw_image (debris_image, center, size, (wtime + WIDTH / 2, HEIGHT / 2), (WIDTH, HEIGHT)) 197 | # draw ship and sprites 198 | my_ship.draw (canvas) 199 | a_rock.draw (canvas) 200 | a_missile.draw (canvas) 201 | # update ship and sprites 202 | my_ship.update () 203 | a_rock.update () 204 | a_missile.update () 205 | # draw text and score 206 | canvas.draw_text ('Lives: '+ str(lives), (50, 50), 36, "White") 207 | canvas.draw_text ('Score: '+ str(score), (625, 50), 36, "White") 208 | 209 | 210 | # timer handler that spawns a rock 211 | def rock_spawner (): 212 | global a_rock 213 | a_rock = Sprite ([random.randrange (WIDTH), random.randrange (HEIGHT)], [random.choice ([0.5, -1]) * random.random () * 2, random.choice ([0.5, -1]) * random.random () * 2], 1, random.choice ([0.5, -1]) * 0.05, asteroid_image, asteroid_info) 214 | 215 | 216 | # initialize frame 217 | frame = simplegui.create_frame ("Asteroids", WIDTH, HEIGHT) 218 | 219 | # initialize ship and two sprites 220 | my_ship = Ship ([WIDTH / 2, HEIGHT / 2], [0, 0], 0, ship_image, ship_info) 221 | a_rock = Sprite ([WIDTH / 3, HEIGHT / 3], [1, 1], 0, 0, asteroid_image, asteroid_info) 222 | a_missile = Sprite ([2 * WIDTH / 3, 2 * HEIGHT / 3], [-1,1], 0, 0, missile_image, missile_info, missile_sound) 223 | 224 | # register handlers 225 | frame.set_draw_handler (draw) 226 | frame.set_keydown_handler (down) 227 | frame.set_keyup_handler (up) 228 | timer = simplegui.create_timer (1000.0, rock_spawner) 229 | 230 | # get things rolling 231 | timer.start() 232 | frame.start() --------------------------------------------------------------------------------