03/12/2024

Week 9 Assigments

1. Change the shape

Modify the program to draw other kinds of shapes in stead of the ellipse.  Change the direction of the shape, or make it spin while it moves.

2. Three's a party

Modify the program to draw multiple (at least 3) shapes at the same time.  Carefully plan the initialiser program to ensure they go at different directions and with different speeds.  Otherwise it'd be boring!

3. There's an end to every movement

Modify the program to introduce an energy loss at each bounce, to mimic the real world physics.  At each bounce the speed will reduce, eventually the shape would stop at some point.

4. Get me out of this!

This is difficult, and fun.  Look up Arcade docs to see how to add keyboard interactions to the program.  

Modify the program to include keyboard interaction.  When a certain key is hit, the shape can stop, or reverse!

27/11/2024

Week 9 Learning Summary

Week 9 subject: Your first Arcade game from scratch

Step 1: Define the problem

In a playground (SCRWID * SCRHGT), draw a shape (ellipse to start with), let it move within the playground, bounce off each side of the playground.  Easy!

In order to create that game, you obviously need:

  • The Arcade package,
  • An Arcade program template,
  • Your own Shape class which has properties and actions

Step 2: An 'Empty' Arcade program

import arcade

# Constants
SCRWID = 800
SCRHGT = 600
SCREEN_TITLE = "My First Arcade Game"

# MyGame class exists in each arcade program
class MyGame(arcade.Window):
    def __init__(self):
        super().__init__(SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_TITLE)
        arcade.set_background_color(arcade.csscolor.CORNFLOWER_BLUE)

    def on_update(self):
        pass

    def on_draw(self):
        self.clear()

# Main program, first initalise the MyGame class, then call arcade.run()
game = MyGame()
arcade.run()

Don't forget to add then more code to actually initialise your shapes (in our case only one shape) in the shape_list data member of the MyGame class.  Each member of the list is an object of the Shape class.  Don't forget to provide the values used by the initialiser of the Shape class.  Like this:

    def __init__(self):
        super().__init__(SCRWID, SCRHGT, SCRTTL)
        arcade.set_background_color(arcade.csscolor.CORNFLOWER_BLUE)

        # Initialise your list of shapes, we are going to use only 1
        self.shape_list = []

        # Set all initial values used to initalise shapes in the list
        x = SCRWID / 2
        # All other intialisation...
        c = (255, 0, 0, 127)

        # Initialise shape
        shape = Shape(x, y, w, h, a, dx, dy, da, c)

        # Add to list of shapes
        self.shape_list.append(shape)

Step 3: Define the Shape class

The shape, presumably an ellipse, will have a number of properties (data members), including x, y, w, h, dx (speed on the x-axis), dy (speed on the y-axis), a (angle from horizontal) and c.  It will also need to have a method to move(), based on x, y, dx and dy, and to bounce of the 4 walls.

class   Shape:
    # called when the Shape object is created, make sure you pass all parameters!
    def __init__(self, x, y, w, h, a, dx, dy, da, c):
        self.x = x
        self.y = y
        # all other initialisation...
        self.c = c

    # called by the MyGame class on_update() method
    def move(self):
        # update location based on current location and direction of move 
        self.x += self.dx
        self.y += self.dy
        self.a += self.da

        # bounce is literally just reversing direction
        if (self.x < 0 and self.dx < 0) or (self.x > SCRWID and self.dx >0):
            self.dx *= -1
        if (self.y < 0 and self.dy < 0) or (self.y > SCRHGT and self.dy >0):
            self.dy *= -1

    def draw(self):
        arcade.draw_ellipse_filled(self.x, self.y, self.w, self.h, self.c, self.a)

Step 4: Add movement (event handling)

Arcade calls the on_update() method of MyGame class at a certain interval.  (Look up the Arcade docs to see how to set this interval.)  Movement must be handled in on_update(), by simply calling Shape.move() where the real work is done.

However, the drawing of the moved shape is done in another event handler on_draw(), which is also called by Arcade whenever there's anything to draw.

    def on_update(self, dt):
        for shape in self.shape_list:
            shape.move()

    def on_draw(self):
        self.clear()

        for shape in self.shape_list:
            shape.draw()

Step 5: Let's go!

Check your code again, make sure all elements are updated.  Then run the program, please the first Arcade game you create.

13/11/2024

Week 8 Learning Summary

Week 8 subject 1: Arcade self paced learning

There's abundant resources online to learn Python programming with Arcade.  Like the Arcade Academy.  Skip directly to the 'drawing' part: 

5. How to Draw with Your Computer — Arcade 2023 documentation,

follow the tutorial step by step.

If you don't like to follow through and learn Python all over again (however this is recommended!), go directly to the Arcade Tutorial:

Simple Platformer - Python Arcade 2.6.17

Week 8 subject 2: Platformer Program Template

This is a simplistic example of what a platformer game program should look like.  
Wonder what a platformer game is? Look here: Build a Platform Game in Python With Arcade – Real Python.

Super Mario is a symbolic Platformer game.  Also try one of the successful platformers: Lode Runner Web Game.  Learn more about Lode Runner here: Lode Runner - Wikipedia.

import arcade
# Constants
SCREEN_WIDTH = 1000
SCREEN_HEIGHT = 650
SCREEN_TITLE = "Platformer"
class MyGame(arcade.Window):
    """
    Main application class.
    """
    def __init__(self):
        # Call the parent class and set up the window
        super().__init__(SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_TITLE)
        arcade.set_background_color(arcade.csscolor.CORNFLOWER_BLUE)
    def setup(self):
        """Set up the game here. Call this function to restart the game."""
        pass
    def on_draw(self):
        """Render the screen."""
        self.clear()
        # Code to draw the screen goes here
def main():
    """Main function"""
    window = MyGame()
    window.setup()
    arcade.run()
if __name__ == "__main__":
    main()

Week 7 Assignments

Mess with the Enemies!

Read the code of the 'Enemies' example.  Make changes to:

  • Size of the stage, width, height
  • Number of enemies
  • Speed
  • Gravity
  • (Advanced) your look, enemies' look, look of the stage.
  • (Advanced) not allow jumping off limits, bounce off walls!

Make it your own game!

Week 7 Learning Summary

Week 7 subject 1: Python built-in functions

  • abs(x): find out absolute values
  • bool(x): returns truth value
  • dir(object): returns all information(attributes) of the object
  • help(request): evoke the online help system
  • eval(expression): run and return result
  • exec(object): run expression or program(!)
  • float():
  • int():
  • len():
  • min() and max():
  • range():
  • sum():
It is essential skill to be able to look up reference websites to continually learn Python.  Example: Python Docs.

    • constants defined to be false: None and False

    • zero of any numeric type: 00.00jDecimal(0)Fraction(0, 1)

    • empty sequences and collections: ''()[]{}set()range(0)

Week 7 subject 2: Game programming with Arcade

Arcade is a good package for developing games with Python.  Try to read this code and make changes to make your game more fun.

12/09/2024

Week 6 Assignments

 1. GSPLZ

You've recently quit the school library job because you get bored of the routines.  It so happens that the GSPLZ (George Sun's Python Learning Zoo) has an opening for the development of a software system called ZOO (Zoo Objective Organiser).

The GSPLZ gives you a manual of how animals are classified in the zoo. 

Animal Classification for Children: Classifying Vertebrates and  Invertebrates for Kids - FreeSchool 

They know that you can program Python.  They want you to first build this classification into your program by creating a hierarchy of Classes.  In addition to the picture, they've specified:

  • Each animal has a name and an age.
  • Each animal can move.
  • Each vertebrate can 'strechback'.
  • Each vertebrate has a number of sections of their spine.
  • Each fish has a number of gills.
  • Each fish can 'blub'.
  • Each bird can 'chirp'.
  • Each bird has a feature colour.
  • Each mammal can milk.
  • Each amphibian has a preferred habitat.
  • Each reptile can crawl.
Please build the Python program for the ZOO that defines all the types of animals in GSPLZ as classes, with their data members and methods defined.  

Week 6 Learning Summary

Week 6 subject 1: Data Members of Classes

  • Data members of Classes are created when they are assigned values.
  • Data members can be dynamically added or deleted (with del statement).
  • Parent and child Classes can have data members with the same name, when referred to, child will override parent.
  • ADVANCED: Data members can be attached to the Class as well as the instance.  In the former they are called Class Variables, latter Instance Variables.  Class Variable values are common across all instances of the Class, while Instance Variable values are local to the exact instance.

class Car(vehicle):
    NumOfWheels = 4
    def move(self, direction, distance):
        pass
 
myCar.NumOfWheels = 5
print(Car.NumOfWheels, myCar.NumOfWheels)
myCar = Car()

Week 6 subject 2: Methods

  • Methods are functions attached to Classes.  Like functions they need to be defined before being used.
  • Methods have 1 implicit parameter: self.  self means the instance itself.  methods use the self variable to access other members of the instance.

class Car(vehicle):
    NumOfWheels = 4
    def move(self, direction, distance): 
         pass
    def showwheels(self):
        print(self.NumOfWheels)   

  • Like Data Members, parent and child classes can define methods with the same names.  When called, child will override parent.
  • ADVANCED: Methods can also be added to Classes after initial definition of Classes.  Methods can be attached to both the Class and the Instance.  This is too complex, don't try.

Week 5 Learning Summary

Week 5 subject 1: Python is an OOPL

  • Programming in procedural languages is like writing a cook book, which includes a series of steps that are executed either sequentially or according to defined control flows.
  • On the other hand OOPLs mimic the real world by defining 'objects' and how they interact with each other, so that we can stay reasonably far away from the tedious work of recreating all the 'steps' each time we need to describe the interactions, and let the 'objects' do it according to their definitions.

Procedural Programming and Object-Oriented Programming in C++ - Scaler  Topics

Week 5 subject 2: Classes

  • 'Objects' are grouped into Classes.  Classes define the common properties and capabilities of objects.  Objects are 'instances' of their respective Classes.  Example: 'Cars' is a Class, and my 2020 BMW 320i is an object of this Class, my friend's 2018 Honda CRV is another object of this Class.
  • Instances of Classes are accessed in Python by declaring variables of a Class.  A Class is essentially a type, like int or string.
  • Just like there are different levels of group objects in real life, there can be hierarchies of Class definitions.  Objects can be instances of different Classes.

Inheritance and Polymorphism in Python

  • Parent Classes / Child Classes; Base Classes / Sub Classes.  
  • There's inheritance between parent and child classes.
  • Define Classes, use pass to indicate you don't define the contents of the Class at this moment;

Class Car:
    pass
 
Class Car(Vehicle):
    define drive():
        pass
 
    define park():
        pass

  • You can define variables and functions inside Classes. They are called characteristics, or members of Classes.  Particularly functions inside Classes are called 'methods' of Classes.
  • Note: because of inheritance, instances of child classes can access members of parent classes.

04/08/2024

Week 4 Assignments

 1. Head, tail, and more

You've managed to recreate the classical Unix command wc with Python.  Dennis Ritchie and Ken Thompson send their regards.

They would like you to continue with a few more extremely useful Unix commands:

head: takes an input file name, number n, and an output file name; writes the first n lines of the input file to the output file.  If the output file name is not provided, just write to the screen.

hint: what happens if there are less than n lines in the input file?

tail: very similar to head, only that it writes the last n lines.

more: takes an input file name.  Writes the contents of the file to screen, but pause at a full screen and wait for input.  Once the ENTER key is hit, show the next full screen of file content, until the entire file is shown.

hint: how do you know how many lines is a full screen?  Make some assumptions.  If you really want to be accurate, look up shutil.get_terminal_size().
Extension: what if the program accepts 'any key' instead of ENTER for the next screen of output?  Do some research.

2. Everything has a price

Johnny English (2003) - IMDb

You are a secret agent.  You buy and sell classified information for a living.  Such classified information has several properties:

- From country: a string of letters;
- To country: a string of letters;
- Classification level: a number between 1 and 5;
- Financial value: a number between 1 and 100.

When a piece of information is being traded, its price is calculated as follows:

1. You add values of all the letters in the from country, 'a' being 1 and 'z' being 26, to get a FC value;
2. You add values of all the letters in the to country, to get a TC value;
3. You use the Classification level C and Financial value F to calculate the CF value as follows: add up the squares of numbers from 1 to C, then add up the square roots of numbers from 1 to F, then add these 2 to get a CF value;
4. get the Price = (FC + TC) * CF

Get a list of classified information from an input file: jamesbondsclassifiedinformationforsaledontshowanybodybecauseitsstillnotencrypted.txt.  Each line contains the from country, to country, classification level and the financial value.  For each piece, write the calculated price to prices.txt.

First try to write the program without using functions.  Then rewrite your program using functions.  See if that simplifies your life. 

3. Scopes of variables

Write some simple functions for example adding 2 numbers.  Try different scenario like accessing values of local variables within / outside the functions, and accessing values of global variables within / outside the functions.

Also try changing values of variables within the functions, then see what happens to them outside the functions.

30/07/2024

Week 4 Learning Summary

Week 4 subject 1: File Operation (contd.)

  • More ways to process File contents in Lists:
    • List(File) is a list of lines from File,
    • .readlines(hint) returns a list of lines.
  • One way to avoid explicitly closing files is using 
        with open(Filename) as File:

            File will be automatically closed at the end of the with block.

  • Opening files for output using the 'w' or 'a' modes in the open() function.  Note the different behaviour vs. 'r' when the file doesn't exist.
  • Output to files with the write() function.
  • Files by default is a sequential media.  There's a historical reason for this.  However there are ways to move in a file in both directions:
    • .seek(offset, from) moves forward or backward in file,
    • .tell() tells the current position in file.

Week 4 subject 2: Functions

  • A Function is a block of code with:
    • A name,
    • Zero or more parameters,
    • Zero or more return values.
  • Functions are useful for:
    • Eliminating repetition, and
    • Simplifying code, making it easier to read.
  • The same number of parameters need to be provided when calling a Function, as the number of parameters in the definition of the function.
  • You can specify default values of parameters in the definition.  When there are default values, less parameters can be provided when calling.
  • Use the return statement to return values to the caller.  You can return multiple values:
    • In the form of a tuple, i.e., multiple values separated by commas, or
    • In a list.

Week 4 subject 3: Scope of variables

  • Variables have scopes, i.e., parts of the program where they can be referenced.
  • There are 2 types of variables based on their scopes:
    • Global variables: those defined outside any function, and
    • Local variables: those defined inside a function
  • Global variables are valid inside functions, but local variables aren't valid outside functions.
  • All variables must be first defined before referenced, within their respective scopes.
  • Functions are like global variables, they must be defined before being called.
  • Expand your knowledge by doing research of the concept Namespace.

03/07/2024

Week 3 Assignments

1. Not Lonely Anymore:

A second librarian, Charlie, joins you in the school library.  Charlie suggests that the book list you keep can be improved to include names of the authors.  You agree.  The two of you start to upgrade your automation to do the following:

  • Input a line which contains the book name followed by the author's name.  Both are single words.
  • If the book doesn't exist in your list, add it; if it does, update the author's name.
  • Handle deletion by book name as it already does.
  • If the input is 'search' followed by author's name, output a list of books by this author.
  • At the end of the process, output the complete book list, one line per book, each containing the book name followed by the author's name. 

2. Bond, James Bond:


You live a double life.  During the day you are GS the lonely librarian, but when you are off and nobody sees you, you are James Bond the MI6 secret agent, the King's spy, with a license to kill.

You can't let others know the content of your communication with M, the head of MI6.  You have a secret code book jamesbondscodebooktopsecretcantletanybodyseebecauseitsnotencrypted.txt.  The book contains many lines, each containing the plain text word followed by its code word.  Example:

    I            poop
    hungry       *&%#
    bored        78534
    irritated    buzzinga!

So that a message like 'I am always hungry or bored or irritated' will be translated to 'poop am always *&%# or 78534 or buzzinga!'

Input a line of message you need to send to M.  Use the code book to translate it word by word to the secret form and output the translated line.  Repeat this process until a blank line is input.

3. Real Legend:

The Unix system (https://en.wikipedia.org/wiki/Unix) is a legend. It sets the foundation for most of the modern-day operating systems that run on billions of devices. More importantly its design philosophy of simplicity and reusability has a massive influence on generations of programmers, in simple terms, to create a program that does one thing really well, and let it work with other programs.

The Unix system has many very famous commands which are also legends.  wc is one of them.  See https://en.wikipedia.org/wiki/Wc_(Unix).  You want to recreate the functions of wc in Python so that you can be a real legend too.

Input the name of an existing text file.  Output 3 numbers, the number of lines, the number of words (delimited by spaces), and the number of characters (including spaces and newlines).

Week 3 Learning Summary

 Week 3 subject 1: Tuples

  • Tuples are just like Lists, only they're immutable, i.e., their elements, and the numbers of elements, can't be altered.  HOWEVER, the elements are immutable doesn't mean that the elements of the elements can't be altered.  
    • Example, if an element of a Tuple is a List, you can't replace the List with another, but you can alter the elements of the List.
  • There are limited operations applicable to Tuples, including the len() function, and the .count() and .index() methods.

Week 3 subject 2: Dictionaries

  • Dictionarys are like Lists, but their elements are pairs: Key:ValueKeys are just like subscripts of Lists only that they can be of many other data types and other values.
  • Dictionary is perfect for registers, dictionaries and anything you need to use an index to locate values.
  • Use methods like .items(), .keys() and .values().items() returns a list of Tuples, while other two return Lists.
  • You can't use arithmetic operations like + or * with a Dictionary.
  • Learn how to tell if one Key exists in a Dictionary?  What about one Value?
  • There's no .append().  Use assignments directly.  
    • Note the difference with Lists where you can't assign value to an element that hasn't been appended yet.
  •  A Dictionary can be initialised 
    • Using initialisers directly like d = {1:'one', 2:'two', 3:'three},
    • Using the dict() constructor like d = dict([(1, 'one'), (2, 'two'), (3, 'three)]), note the parameter of dict() is a list of tuples,
    • There's a fancier while more confusing way, when Keys are simple strings: d = dict(one=1, two=2, three=3)
    • Using the .fromkeys() method like d = dict.fromkeys([1,2,3], "numbers")
  • As I said, keep exploring all the possibilities!

Week 3 subject 3: File Operations

  • File means text files.  It's a giant leap forward which means you are finally free from keystrokes and can now process something much more complex and more meaningful!
  • Always use the open() function to open a file before using, which returns a File object you'll need to refer to whenever you need to operate a file.
  • Always use the .close() method to close the file after use.
  • Read from files using:
    • .read(number of characters)
    • .readline()
  • Pay attention lines read from a File contain the newline characters at the end of each line.
  • You can use File like a list of lines with for l in f: 
  • ATTENTION: the File object keeps track of the current position read.  It always moves forward.

01/07/2024

Lightning challenge

Mind reader:

Your computer tells you it has mind reading capabilities.  You certainly don't buy that because you go to the Opportunity Class.  Your computer suggests a game with which it will show you that it reads your mind.

You give it a range, like 1..100, and the computer guesses an integer within that range.  All you need to do is tell it 'too large' or 'too small'.  You two repeat this Q&A until the computer guesses the correct number you have in mind.  By doing so you are able to tell if the computer can really read your mind, or it's simply doing maths.

Input 2 integers that indicate the range.  For each integer the computer guesses, input 'too large', 'too small', 'correct', or 'quit'.  The game ends when the input is 'correct' or 'quit'.  The computer outputs the integer you have in mind, and the number of guesses taken.  If the computer finds out you are trying to cheat, it also ends guessing and outputs 'you can't fool me!'.

20/06/2024

Week 2 Assignments

1. Clean format:

Input a line of strings of mixed cases, format each word (words are strings delimited by spaces) so that they are capitalised.  Output the formatted line. 

2. Stammer Bob: 

Bob stammers when facing long words.  He speaks all words with less than or equal to 5 letters fluently, but for each word with more than 5 letters, each extra letter causes him to repeat the word once more.  For example, when you say ‘Good Morning Bob’, he will have to reply ‘Good Morning Morning Morning George George’.  

Input a sentence, output how Bob actually pronounces it.

3. Preprocessing:

You work for a big data company.  They take vast number of texts from the media and perform data analysis.  Your job is to preprocess the text by attaching data points to the words so that they can be processed by the data scientists.  The rule is simple: for each input line, separate them into words (delimited by spaces), prefix each word with the sequence number of it in the line, and suffix it with the length of the word.  For example, for the input ‘giant leap for mankind’, you produce an output ‘0giant5 1leap4 2for3 3mankind7’.

Input a line, output the outcome of the preprocessing with the additional data points attached.

4. Lonely librarian:

You are the only librarian in the school library.  You get sick of keeping record of new books and writing labels, you decide to create some automation.  You want to keep entering names of new books, until at one point you enter ‘end’so the automation stops.  For each book entered, it’s added to your record, unless the same name already exists in the record.  When the automation stops, it prints a list of all the books entered.

Input a series of book names, output the list of books entered.

Extension: 

People make mistakes, a lonely librarian makes more.  When you discover a mistake, instead of entering the name of the book, you enter ‘del’ followed by the name of the book incorrectly entered.  The book is then removed from your list.  

Input a number of book names and delete commands, output the final list of books.

5. Letter from Moscow:

Your friend lives in Moscow.  He sends you email messages.  Because of the extreme cold, people have a different accent there.  They pause after each word, and at the end of each sentence they yell.  This even affects the way they write emails, for each word they write, they always add a comma after, and wherever we use a comma or full stop, they always use an ‘!’.  You may receive a message from Moscow saying ‘Good, day, mate! How, are, you! I, don’t, yell! I’m, just, friendly!’.

Input a line of message, output the result after translating to the Moscow accent.

6. The more the merrier:

You are organising 2 parties.  At one point it suddenly occurs to you: if people come to parties to have fun, why hold two when you can have everybody in one.  There’s twice the fun and you don’t have to work twice as hard.  You need to merge the 2 guest lists.  They are both sorted alphabetically.  You need a program to merge them so that the combined list is still sorted alphabetically.

Input 2 lines, each containing a list of names sorted alphabetically, output a combined list of names sorted alphabetically.