W1501 Introduction to Objects

From Coder Merlin
Revision as of 23:31, 27 February 2021 by Chukwuemeka-tinashe (talk | contribs)
PDP-15 Graphics Terminal with Tablet

Prerequisites[edit]

Background[edit]

Introduction[edit]

Definitions[edit]

Class
An extensible program-code-template for creating objects.
Extensible
Something that is able to be extended by allowing the addition of new capabilities and functionality.
Template
Something that serves as a model for duplication.
Object
An instance of a class.

Classes are a useful construct to aid humans in constructing software that is sensible by enabling encapsulation. In its most basic sense, encapsulation is the action of enclosing something in or as if in a capsule. As it relates to computer science, encapsulation has a specific meaning, and refers to:

  • Bundling related data (nouns, something that an object has)
  • Bundling related functions (verbs, something that an object does)
  • Protecting data by controlling visibility (restricting undesirable access to data and functions)

Let's contrast this definition with that of an array:

Array Object
Collection of similar elements Group of dissimilar yet related data

Consider the following table:

First Name Last Name ID GPA
Tom Baker 74 3.75
Christopher Eccleston 5 3.5
David Tennant 10 4.0
Matt Smith 29 3.2

In this table, a column is similar to an array, a collection of similar elements:

First Name Last Name ID GPA
Tom Baker 74 3.75
Christopher Eccleston 5 3.5
David Tennant 10 4.0
Matt Smith 29 3.2

In the same table, a row is similar to an object, a group of dissimilar yet related data:

First Name Last Name ID GPA
Tom Baker 74 3.75
Christopher Eccleston 5 3.5
David Tennant 10 4.0
Matt Smith 29 3.2

Swift Example[edit]

Closely review the below code segment. Be sure to read each of the four numbered comments.

// 1. The next line defines a CLASS named Student.  Like all types, class names should be capitalized.
class Student {
    let firstName : String    // 2.  This section defines PROPERTIES, the DATA that an object HAS.
    let lastName : String     // |
    let id : Int              // |
    let GPA : Double          // |

    // 3. The next code segment is a CONSTRUCTOR.  It is invoked automatically to initialize the object.
    init(firstName:String, lastName:String, id:Int) {
        self.firstName = firstName
        self.lastName = lastName
        self.id = id
        self.GPA = 4.0
    }

    // 4. The next code segment is a METHOD.  It's similar to a function but has access to the object's 
    //    properties.  It's something that an object DOES.
    func adjustGPA(newGPA:Double) {
        GPA = newGPA
    }
}

Scenes[edit]

We'll begin our exploration of objects using Scenes. Scenes is an object-oriented, event-driven platform that enables us to write server-side Swift code which (rapidly) sends a series of instructions to a browser to generate visual effects, and optionally, an interactive experience. Scenes is built upon another framework called Igis.

WarnIcon.png
Caution

It's important to understand that while many of the objects we'll be using have an associated visual representation, the majority of the objects that we build and interact with in programming will not have such a representation.

Prepare[edit]

HintIcon.png
Helpful Hint

If you see something similar to:

ERROR: '/home/john-williams/Experiences/W1501/dylib.manifest' has been changed but '/home/john-williams/Experiences/W1501/.dir-locals.el' has not. Did you mean to execute dylibEmacs?

Simply execute (in the root of the project):

john-williams@codermerlin:~/Experiences/W1501$ rm .dir-locals.el
john-williams@codermerlin:~/Experiences/W1501$ dylibEmacs


Create a new Scenes shell project within your Experiences directory:

ty-cam@codermerlin:~$  cd ~/Experiences
ty-cam@codermerlin:~/Experiences$  git clone https://github.com/TheCoderMerlin/ScenesShellBasic W1501


Enter the Sources/ScenesShell directory of the new project:

ty-cam@codermerlin:~/Experiences$  cd W1501/Sources/ScenesShell/


Start button green arrow
Run the program.
ty-cam@codermerlin:~/Experiences/W1501/Sources/ScenesShell$  run


Ensure that you are logged on to the wiki. Then, click on the Tools menu followed by right-clicking on IGIS and selecting the menu item Open in New Window or Open in New Tab.

You'll know you're successful if you see the title bar change to "Coder Merlin: IGIS". (The browser window will be blank because we haven't added any graphics yet.)

HintIcon.png
Helpful Hint
It's useful to bookmark this page in your browser.

Hello World[edit]

Text[edit]

Stop button red ex
Stop the running program.

Return to the console and press CONTROL-C

Open the file Background.swift in emacs. Read through the file. You'll find some code as follows:

class Background : RenderableEntity

This defines a new class named Background. The colon and the following identifier, RenderableEntity, indicates that the class Background inherits properties and methods from the class RenderableEntity. You'll note that the class includes a constructor, indicated by the keyword init on line 2:

1 class Background : RenderableEntity {
2     init() {
3         // Using a meaningful name can be helpful for debugging
4         super.init(name:"Background")
5     }
6 }

The constructor is invoked automatically as the object (an instance of the class) is being initialized. This is the place where you'll set up your object. The current constructor in this file sets the object's name using the keywords super and init. super indicates that we're invoking a function (or accessing a property) on our parent class, the class from which we inherited. In this case, that would be the RenderableEntity.

We're going to display some text on our canvas (the virtual surface on which we'll be rendering images in the browser). In order to do that, we'll first declare a Text object as follows:

1 class Background : RenderableEntity {
2     let text : Text
3 
4     init() {
5         // Using a meaningful name can be helpful for debugging
6         super.init(name:"Background")
7     }
8 }

We'll initialize our text object in the constructor:

 1 class Background : RenderableEntity {
 2     let text : Text
 3 
 4     init() {
 5         // Initialize objects
 6         text = Text(location:Point(x:50, y:50), text:"Hello, World!")
 7 
 8         // Using a meaningful name can be helpful for debugging
 9         super.init(name:"Background")
10     }
11 }

At this point, we have a Text object that "knows" how to render itself on the canvas, but it hasn't yet actually done any rendering. There are two methods in which we generally render. The first is called setup. The setup function executes once. It's an opportunity to set up objects and/or render if we're creating a static (non-animated) display. The other function is render which executes once per frame. In this case, using setup is sufficient.

Add a new method (below init) as follows:

1     override func setup(canvasSize:Size, canvas:Canvas) {
2         canvas.render(text)
3     }

This code instructs the text object to render itself on the canvas.

Be sure to edit the file as indicated above, save the file, then suspend emacs.

Start button green arrow
Run the program and refresh the browser page.


ObserveIcon.png
Observe, Ponder, and Journal : Section 1
  1. What do you observe?
  2. How large is the text?

Font[edit]

Stop button red ex
Stop the running program.


Let's change the font. Resume emacs and add a line below where the text object is instantiated.

    init() {
        // Initialize objects
        text = Text(location:Point(x:50, y:50), text:"Hello, World!")
        text.font = "30pt Arial"

        // Using a meaningful name can be helpful for debugging
        super.init(name:"Background")
    }
GoingDeeperIcon.png
Going Deeper
Graphic Coordinate System.png

You should notice that the location of the text above was specified as:
location:Point(x:50, y:50).
This is familiar from your studies of the Cartesian plane in grade school. However, it's important to note that for many (but not all) computer graphic platforms the y-axis is inverted, with the origin at the top-left of the screen and larger y values moving down the screen.


Remember to save the file, then suspend emacs.

Start button green arrow
Run the program and refresh the browser page.


ObserveIcon.png
Observe, Ponder, and Journal : Section 2
  1. What do you observe?
  2. How large is the text now?

Rectangle[edit]

Stop button red ex
Stop the running program.


Let's add a rectangle around the text. Resume emacs and add the highlighted lines:

class Background : RenderableEntity {

    let text : Text
    let rectangle : Rectangle

    init() {
        // Initialize objects
        text = Text(location:Point(x:50, y:50), text:"Hello, World!")
        text.font = "30pt Arial"

        let rect = Rect(topLeft:Point(x:20, y:10), size:Size(width:300, height:50))
        rectangle = Rectangle(rect:rect, fillMode:.stroke)

        // Using a meaningful name can be helpful for debugging
        super.init(name:"Background")
    }

Then, update the following, highlighted line in the setup function:

    override func setup(canvasSize:Size, canvas:Canvas) {
        canvas.render(text, rectangle)
    }

Remember to save the file, then suspend emacs.

Start button green arrow
Run the program and refresh the browser page.


ObserveIcon.png
Observe, Ponder, and Journal : Section 3
  1. What do you observe?
  2. What is the purpose of the location parameter in the Text constructor?
  3. What is the corresponding parameter named in the Rectangle?
  4. What is the difference between a Rect and a Rectangle? Hint: Are you able to render a Rect?


Stop button red ex
Stop the running program.

Exercises[edit]

ExercisesIcon.png
Exercises
  •  J1501  Create a journal and answer all questions. Be sure to include all sections of the journal, properly formatted.
  • Making use of your accumulated knowledge to date (loops, functions, coding style, etc.) and using only Rectangles and Text on a single canvas:
    1. Draw a single rectangle (without any text)
    2. Draw a grid (at least 3 x 3)
    3. Draw a brick wall (at least 5 x 5)
    4. Draw a pyramid constructed of bricks (at least seven rows high)
    5. Draw a skyscraper with a large sign on the roof containing your name
    6. Draw at least three skyscrapers of different heights on the same Canvas, each containing your name


Designed with pride in Silicon Valley, CA, USA