4. Finishing the first program

What We Will Cover


Illuminations

Questions from last class or the Reading?

  • String review
  • Guild names due Thursday -- roll call with guild names
  • Remember that guilds sit together and help each other
  • Reminder: Challenges

Homework Questions?

  • B3: Random choices (Canvas) (2/18/20)
    Lab 3: Finishing the Crab (2/18/20)
    Q3: Methodical Improvement (2/20/20)
  • Please do not put spaces in folder names of zip files turned in for homework
  • The Java compiler has problems with spaces in folder or file names

Matching Relationships Game

Match the questions with the answers. Use the box on the left to write your choice. Then click on the Answers box to see if your answers are correct.

1. Less than    a. ==
2. Assignment    b. =
3. Less than or equal    c. <=
4. Not equal    d. >=
5. Greater than    e. >
6. Greater than or equal    f. <
7. Equal    g. !=

4.1: Forming Guilds

Learner Outcomes

At the end of the lesson the student will be able to:

  • Join a guild
  • Commit to a future guild meeting
  • Choose a name for their guild
  • Discuss how to work together in a guild

4.1.1: Introduction to Guilds

  • This week we want to form guilds
  • A guild is a small group of people with complementary skills who:
    • are committed to a common purpose, goals and approach
    • hold themselves and each other accountable to meet their goals
  • We want several guilds of four to five members
  • Guilds get to choose their own names, leaving out the usual words
  • Some quests, labeled "guild", are completed by all guild members
  • Guilds are given options on how they decide to complete the designated quests
  • An especially important set of quests is the final project, which covers multiple weeks and deliverables
  • The following are important characteristics of successful guilds

Small Group Size

  • Guilds usually work best with a small group of people
  • Smaller numbers make administrative tasks easier, such as deciding where and when to meet
  • Meetings are generally shorter when fewer people need to speak
  • Small size also makes it easier to develop a common purpose with mutual goals and mutual accountability
  • Also, small groups of people avoid the "herd" mentality of large groups
  • Large groups of people tend to go along with popular opinion rather than thinking for themselves
  • We will form guilds of four to five people

Complementary Skills

  • Complementary skills are also important for a guild
  • Complementary means that people work together in such a way as to enhance or emphasize the qualities of each other
  • Guilds need skills in multiple areas including:
    • Programming
    • Graphics creation and editing
    • Sound creation and editing
    • Effective communication and interpersonal relationship
    • Leadership and decision-making
  • We will look at these skills before forming guilds

Commitment and Accountability

  • Guilds need to have a strong commitment to a common purpose and goals
  • This is especially true when we develop the final project
  • The guild chooses a project which meets the final project requirements
  • If one member does not meet their commitment then the whole project suffers
  • For this reason, we have extra credit applied at the end of the final project (secret ballot):
    1. Guild Leader: 20 pts. (major player in the guild; gets things done)
    2. Raid Leader: 15 pts. (major contributor to the guild and its projects)
    3. Solid Guild: 10 pts. (could be counted on to do their part, but not more)
    4. Needs Rez: 5 pts. (coasting, minimal effort, needs resurrection as a player)
    5. Leeroy Jenkins: 0 pts. (Usually AFK or minimal contribution)
  • To be successful, teams need to hold each other accountable for meeting commitments

4.1.2: Getting to Know Each Other

  • Today we will take some time to form guilds
  • Between now and Thursday, the guild needs to meet one time and choose a guild name
  • First we find out when guild members can meet outside of the classroom for at least an hour, like:
    • Before class
    • After class
    • Other times (write on board)
  • Let us start by getting to know each others interests and skills

Exploring Our Interests and Skills

Arrange yourself in a line based on your: (click line)

  1. Interest in games vs simulations
Next step is forming a guild

Exercise 4.1: Forming Guilds (10m)

In this exercise we start forming guilds.

  • Who can meet one hour before class?
  • Who can meet one hour after class?
  • What other times can people meet?

Specifications

  1. Join a group in one of the time locations in the room

    Find people NOT like you. Diversity creates better solutions.

  2. Within your group, exchange names and email addresses, and then copy down everyone's information to turn in as guild.txt.
  3. In addition, list everyone's skills in the following areas a 1-5 scale with 5 being highly skilled
    1. Audio
    2. Graphics
    3. Programming

    For example:

    Emma Gamer      A1  G3  P5
    

    In the above, A1, G3, P5 would be low audio, medium graphics, high programming skills.

  4. Save all the information you collect in a file named guild.txt.

    Note that you can choose to have one person in your group record the information and email it to all the students in the group. However, every student in the guild must submit the list of guild members.

  5. Arrange for a time to meet before the next class meeting.
  6. During your meeting time, decide on the name of your guild.
  7. Save the guild.txt file so you can submit it to Canvas as part of the next lab.

4.2: Setting up a Scenario

Learner Outcomes

At the end of the lesson the student will be able to:

  • Prepare scenarios automatically
  • Code constructors
  • Construct new objects programmatically

4.2.1: World Construction Click for link

  • Recall how we "Save the World" in Greenfoot
  • To see the process we open the current World subclass
  • Next we populate the scenario, right-click on the world background, and select "Save the World"

    select save the world

  • Looking at the source code, we now have a new method in the World subclass named prepare
    private void prepare()
    {
        // some code here
    }
    
  • Notice where the prepare() method is called:
    public LessonWorld()
    {
        super(600, 400, 1);
        prepare();
    }
    
  • The method LessonWorld is known as a constructor
  • Whenever an object is instantiated, the constructor for the object is called automatically
  • The Greenfoot IDE automatically calls the constructor of the current world
  • We use this property of being called automatically to set up our scenario
  • If we look at the LessonWorld source code before calling "Save the World", we see something like the following

Example LessonWorld Code with Constructor

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import greenfoot.*;  // Greenfoot framework

/**
 * Write a description of class LessonWorld here.
 *
 * @author (your name)
 * @version (a version number or a date)
 */
public class LessonWorld extends World
{

    /**
     * Constructor for objects of class LessonWorld.
     *
     */
    public LessonWorld()
    {
        super(600, 400, 1);
    }
}
  • The first line is the import statement, which allows access to the Greenfoot framework
    import greenfoot.*;  // Greenfoot framework
    
    followed by several lines of comments that the compiler ignores
  • Then comes the class header and another comment block
  • Then comes the part that controls how the world starts -- the constructor:
    public LessonWorld()
    {
        super(600, 400, 1);
    }
    
  • The purpose of a constructor is to prepare a new object for use
  • A constructor is coded like a method but there are some differences
  • By looking, can you identify two differences? answer
  • The first line in the body of the constructor sets up the size of the world
    • In our case, 600 pixels wide by 400 pixels high with 1 pixel per cell
  • We can add code to the constructor to automatically create actors:
    public LessonWorld()
    {
        super(600, 400, 1);
        Hero hero = new Hero(); // new expression
        addObject(hero, 150, 100); // add hero to world
    }
    
  • The added code automatically creates a new hero and places it in the specified (x, y) location
  • If we look at a prepare() method, we see similar code
  • We have two statements added here:
    1. the new expression which creates an object and assigns it to the variable
    2. the addObject() method which adds an actor to the scenario
  • We will consider both in the following sections

Check yourself

  1. True or false: the purpose of a constructor is to prepare a new object for use.
  2. A constructor differs from a method in that the constructor has ________ and ________. (answer)
  3. The name of the class that contains this code is ________. (why?)
    private Hero hero;
    private Food food;
    public LessonWorld() {/* statements here */}
    
    1. Hero
    2. LessonWorld
    3. Food
    4. Cannot determine class name from the information given

4.2.2: The addObject() Method

  • The method header for the addObject() method is:
    void addObject(Actor object, int x, int y)
    
  • Where:
    • object: the new object to add
    • x: the x coordinate of the location where the object is added
    • y: the y coordinate of the location where the object is added
  • For example:
    addObject(new Hero(), 150, 100);
    
  • The addObject() method belongs to the World superclass
  • Since our world subclass inherits from the world, we just call the method directly

Check Yourself

  1. True or false: use the addObject() method to add objects to a scenario world.
  2. When calling the addObject() method, we specify the object location using the ________ and ________ coordinates of the scenario world.
  3. True or false: you can call addObject() from any World subclass.

4.2.3: Creating New Objects

  • The addObject() method lets us add an object to the world
  • However, we must first have an object to add
  • The Java keyword new lets us create new objects:
    new Hero()
  • We may create the new object within the addObject() method call:
    addObject(new Hero(), 150, 100);
    
  • Another way is to save the object in a variable and use the variable in the method call:
    Hero myHero = new Hero();
    addObject(myHero, 150, 100);
    
  • Notice that the data type of the variable is the name of the class: Hero
  • Since the first technique is more compact, it is most often used when typing code
  • We only use the second technique if we want to save the object for later use
  • For example, we may set an initial rotation of an object with code like:
    Hero myHero = new Hero();
    myHero.setRotation(45);
    addObject(myHero, 150, 100);
    
  • The key point is that you must use the new keyword to create a new object
  • If we save the actor in a variable, we may then apply more transformations to the actor

Check yourself

  1. True or false: the purpose of the addObject() method is to add objects to a scenario world.
  2. For a class named Foo, you create a new object using the code ________.
    1. new Foo
    2. Foo()
    3. new() Foo
    4. new Foo()
  3. To place a Hero object in the world at the coordinates (200, 300) use the statement ________.
    1. addObject(new Hero(), 200, 300);
    2. addHero(200, 300);
    3. addActor(new Hero(), 200, 300);
    4. addObject(Hero.class, 200, 300);

4.2.4: Using Loops to Randomly Add Objects

  • Saving the world is nice but allows no variation in how a game starts
  • To make the game more interesting we add the food at random coordinates
  • We could a random food object using code like:
    int x, y;
    x = Greenfoot.getRandomNumber(600);
    y = Greenfoot.getRandomNumber(400);
    addObject(new Food(), x, y);
    
  • For ten food, we would need to repeat the last three lines nine more times
  • A better approach is to use a counting loop

A series of steps

Group Activity: Exploring Counting Loops

  • Clap your hands 5 times.
  • True or false: as you are clapping, you are repeating an action.
  • You know when to stop clapping because you ________.
  • True or false: as you are counting, you are testing the count against the number 5.
  • Every time you clap, you update the count by ________.

The for-Loop

  • The counting loop to use in Java is the for-loop
  • The syntax of the for-loop is:
    for (int i = start; i < end; i = i + 1) {
        ...
    }
    
  • Where:
    • i: the name of a counter variable
    • start: the initial starting value
    • end: the final ending value
  • As an example, we could add the ten food using this code:
    int x, y;
    for (int i = 0; i < 10; i = i + 1)
    {
        x = Greenfoot.getRandomNumber(600);
        y = Greenfoot.getRandomNumber(400);
        addObject(new Food(), x, y);
    }
    
  • The parenthesis of a for loop has three parts:
    1. Initialization: int i = 0;
    2. Test condition: i < 10;
    3. Update counter: i = i + 1
  • The first part of a for-loop initializes a counting variable
    for (int i = 0; i < 10; i = i + 1)
    
  • We use the counting variable to keep track of how many times the loop repeats
  • The middle section is a test condition, like in an if-statement, that decides when to keep the loop going and when to stop
    for (int i = 0; i < 10; i = i + 1)
    
  • As long as the test condition evaluates to true, the loop continues
  • When the test condition evaluates to false the loop exits
  • The last section updates the counting variable by adding one to the current value
    for (int i = 0; i < 10; i = i + 1)
    
  • After the loop statement we add the statements to repeat inside a pair of curly braces
  • When a loop exits the program continues with the statement after the loop's closing curly brace }

Diagram of for Loop Operation

for loop flow chart

Execution Steps

           ❶    ⇛    ❷   ⇚   ❹
for (int i = start; i < end; i = i + 1) {
    ... ❸
}
❺
  1. When for loop is reached, execute the initialize statement (example: int i = 0;)
  2. Check if condition is true (example: i < 10;)
    1. if true then continue with Step 3
    2. Otherwise, continue with Step 5
  3. Execute the block containing the statements to repeat (body)
  4. When end of loop body is reached, execute the update statement (example: i = i + 1) and return to Step 2
  5. Loop is finished: continue with statements after the loop

Check Yourself

Map the following terms to the example code:

for (int i = 0; i < 10; i++)
{
    x = Greenfoot.getRandomNumber(600);
    y = Greenfoot.getRandomNumber(400);
    addObject(new Food(), x, y);
}
  1. Initialization: ________
  2. Test condition: ________
  3. Loop body: ________
  4. Update: ________

Exercise 4.2: Scenario Setup (5m)

In this exercise, we automatically initialize our Hero scenario.

Specifications

  1. Download and save the following scenario file and then double-click the file to extract it.

    Scenario file: lesson4.gfar (or zip).

  2. Open the scenario (see lesson 1.3.4).
  3. Open the source code editor of the LessonWorld class (see lesson 1.3.8).
  4. Delete the prepare() method and the method call to prepare().
  5. In the constructor method, add code like the following to automatically add a hero to the scenario.
    addObject(new Hero(), 150, 100);
    

    Compile the class and verify there are no errors. Resolve any errors you find, getting help from a classmate or the instructor as needed.

  6. Create seven Food objects and use a for-loop to add them to the scenario at random coordinates using code like the following:
    for (int i = 0; i < 7; i = i + 1)
    {
        int x = Greenfoot.getRandomNumber(600);
        int y = Greenfoot.getRandomNumber(400);
        addObject(new Food(), x, y);
    }
    

    Place the code in the LessonWorld constructor.

  7. Compile and run your scenario to verify all the changes work well.

    If you have problems, ask a classmate or the instructor for help as needed.

  8. In addition, add one or more predators to your scenario.

    Compile the class and verify there are no errors. Resolve any errors you find, getting help from a classmate or the instructor as needed.

  9. Save a copy of your scenario to upload to Canvas later as part of the next lab.

    We will be adding more code to these files in subsequent exercises, so it is not time to submit them to Canvas yet. However, it is a good idea to have a backup copy in case of problems later in development.

  10. When finished, check your code against the listing below and then help other students.

Listing of LessonWorld() Constructor Method

public LessonWorld()
{
    super(600, 400, 1);
    Hero hero = new Hero();
    addObject(hero,150,100);
    for (int i = 0; i < 7; i = i + 1)
    {
        int x = Greenfoot.getRandomNumber(600);
        int y = Greenfoot.getRandomNumber(400);
        addObject(new Food(), x, y);
    }
    Predator predator = new Predator();
    addObject(predator,304,329);
}

4.2.5: Summary

Constructors

  • Games and simulations need to place actors automatically
  • To automatically place an actor, you use the constructor of the World subclass (like LessonWorld)
  • The purpose of a constructor is to prepare a new object for use
  • A constructor is coded like a method but with two important changes:
    • No return type
    • Same name as the class name

Adding Actors

  • To add an actor to a scenario, we use the addObject() method
  • For example:
    addObject(new Hero(), 150, 100);
  • Notice that we create a new object programmatically in the addObject() method
    new Hero()
  • The other two parameters are the (x, y) coordinates for the actor

For Loops

  • Loops allow us to repeat statements in a program
  • One common use for loops is to count
  • When counting, we need to remember the number of the count
  • To remember a value, we use a variable
  • Thus, to count, we need both a loop and a counter variable
  • The for loop gives us a compact way to code program counter-controlled loops
    for (int i = start; i < end; i = i + 1) {
        ...
    }
    
  • The for-loop executes as shown in the following diagrams:

    for-loop flow diagram

  • We used for loops to add actors to our scenario
    int x, y;
    for (int i = 0; i < 10; i = i + 1)
    {
        x = Greenfoot.getRandomNumber(600);
        y = Greenfoot.getRandomNumber(400);
        addObject(new Food(), x, y);
    }
    

Check Yourself

Answer these questions to check your understanding. You can find more information by following the links after the question.

  1. True or false: scenarios should always have actors placed manually. (4.2.1)
  2. What is the purpose of a constructor? (4.2.1)
  3. Which of the following is NOT a difference between a method and a constructor? (4.2.1)
    1. A constructor name is always the same as the class name whereas a method name need not be the same.
    2. A constructor cannot not return a value but a method can return a value.
    3. A constructor is called automatically when the object is created whereas a method must be called explicitly.
    4. All of these other answers are differences between a method and a constructor.
  4. Which of the following is a difference between a method and a constructor? (4.2.1)
    1. The name is the same as the class name.
    2. The name is the same as the class name, except lower case.
    3. The name cannot start with a number.
    4. The name cannot have spaces.
  5. Which of the following is a difference between a method and a constructor? (4.2.1)
    1. A constructor cannot have parameters.
    2. A method has a name but a constructor does not.
    3. A method body is enclosed in curly braces but a constructor body is enclosed in parenthesis.
    4. A method always has a return type, unlike a constructor.
  6. True or false: the addObject() method has three parameters. (4.2.2)
  7. For a class named Foo, which of the following is a valid expression for creating a new object? (4.2.3)
    1. new Foo
    2. Foo()
    3. new() Foo
    4. new Foo()
  8. A counting loop has the following three parts: (4.2.4)
    1. ___________________
    2. ___________________
    3. ___________________

4.3: Animating Images

Learner Outcomes

At the end of the lesson the student will be able to:

  • Discuss animation using images
  • Write programs with animated images
  • Write code for instance variables
  • Assign values to instance variables

4.3.1: About Image Animation

  • Animation is the illusion of motion created by displaying a series of images or shapes
  • For example, the following animation displays at 10 frames per second (FPS):

    example animation

  • The speed of the display is fast enough that you cannot easily see the individual frames
  • Contrast this with the following image that displays at 2 frames per second:

    example animation at slower frame rate

  • At 2 FPS, the animation is slow enough that you can see the individual frames
  • Both of these animations were produced by displaying these images, known as frames:

    animation frames

  • Note that these images are in the public domain and were obtained from Wikipedia

Check Yourself

  1. Animation is the ________ of motion created by displaying a series of images or shapes.
  2. True or false: if the animation is too fast, it appears jerky.
  3. Each image in an animation is sometimes called a ________.

4.3.2: Adding Images to a Scenario

  • We want to apply image animation to make our actors look more realistic
  • For this, we need to add more images to our hero scenario
  • We can use the following similar but slightly different images for our hero
  • The slight difference is in the position of the legs

Images for Animation

Bug with legs forward Bug with legs sideways Bug with legs back
Bug with legs forward Bug with legs sideways Bug with legs back

Saving Images in a Scenario

  • We can save these images in our scenario
  • Right click the images and select, "Save Image As..." (or "Save Picture As..." in IE)
  • In the Save Image dialog, find the Greenfoot scenario folder for your project and save in the images folder
  • In Greenfoot, right click on the actor and select, "Set image..."

    Set image menu

  • You will see the images on the left in the Scenario images area
  • Click the image to select it and press the OK button

Select image dialog

Check Yourself

  1. True or false: to create an animation effect we often change the images of an actor.
  2. The name of the command for changing the image an Actor displays is ________.
  3. True or false: you cannot import new images into a Greenfoot scenario.

4.3.3: Greenfoot Images

  • Greenfoot has a class named GreenfootImage that helps us make use of an image
  • We can get an image by creating a new GreenfootImage object:
    new GreenfootImage("bug-a.gif");
    
  • All actors have images and get one from their class by default
  • However, we can change the images in an actor object by calling a method
  • There are two methods in the Actor class that lets us change an image
    void setImage(String filename)
    void setImage(GreenfootImage image)
    
  • Where:
    • filename: the name of an image file
    • image: a GreenfootImage object
  • We could use the first method and load the image directly
  • However, it is better to use the second method for animation
  • The reason is that we want to change the image many times every second
  • Loading an image from a file is a relatively slow operation
  • Also, constantly creating and destroying images is a lot of work for the computer
  • If we load the images only once we can simply exchange them
  • To make this trick work, we need to save an image when we load it from a file
  • To save the images, we need to discuss instance variables

Check yourself

  1. To change the image of an Actor call the method ________.
  2. True or false: in Greenfoot, the name of the class for storing images is called GreenfootImage.
  3. Of the following, ________ is NOT one of the methods of Actor that works with images.
    1. getImage()
    2. setImage(String)
    3. setImage(GreenfootImage)
    4. changeImage(GreenfootImage)

4.3.4: Instance Variables (Fields)

  • An instance variable, also called a field, is declared inside a class but outside any method
  • General syntax:
    private dataType VariableName1, VariableName2, ...;
    
  • Where:
    • dataType: one of the Java data types
    • VariableNameX: the name of the variable
  • For example:
    private int count;
    private GreenfootImage image1;
    
  • The word private is known as an access modifier
  • Technically, we can use words other than private, but for now ALWAYS use private
  • Professional programmers use private to ensure projects can be changed as they grow larger
  • Can you identify each of the syntax items in the examples above?
    • acess modifier
    • data type
    • variable name

Comparing Local Variables and Instance Variables

  • A local variable is like an instance variable but is a variable declared inside a method or other block
  • Like an instance variable, a local variable is a place in memory to store information
  • Also, like an instance variable we specify a data type and a name to declare a variable
  • Likewise, the naming rules of local and instance variables are the same
  • In addition, we assign values to both local and instance variables using an equals ("=") sign
  • In contrast, a local variable is declared inside a method while an instance variable is declared outside of any method
  • Because of location, the memory for a local variable is associated with a method or block of code
  • With an instance variable, the variable is associated with the object
  • Every object you create (instantiate) of the class with the instance variable has memory space for the variable
  • Also, the instance variable has an accessibility modifier: private
  • Unless we assign a value to an instance variable, Java assigns a default value

Example of Three Instance Variables Declared in a Class

import greenfoot.*;

// comments omitted

public class Hero extends Mover
{
    private GreenfootImage image1, image2, image3;

    // methods omitted
}

Default Values for Instance Variables

  • Local variables are not initialized automatically
  • However, the compiler will initialize all instance variables to default values including:
    • int: 0
    • double: 0.0
    • boolean: false
    • Class types: null
  • The type null above is a special value that means "no object"
  • A programmer can explicitly declare an initial value for instance variables
  • For example:
    private int count = 0;
    private double power = 200.0;
    private Hero myHero = new Hero();
    

Check yourself

  1. True or false: an instance variable is a place to store data in memory.
  2. True or false: A local variable is declared inside a method while an instance variable is declared outside a method, though still inside a class.
  3. The three parts of this instance variable are known as a(n):
    private GreenfootImage image1;
    1. private: ________
    2. GreenfootImage: ________
    3. image1: ________

4.3.5: Constructors and Reference Variables

  • In section 4.2.2, we discussed how to use the constructor of the world class to initialize the world
  • In a similar way we can use a constructor in an actor class to initialize the actor
  • The world class had a constructor included automatically by Greenfoot, but an actor does not
  • Instead we write our own constructor using the following syntax
    public ClassName(parameterList) {
        statements
    }
    
  • Where:
    • ClassName: the name of the class
    • parameterList: the types and names of the parameters
    • statements: the commands to execute when the constructor is called
  • Technically, we can use words other than public, but for now always use public
  • We can see an example of a constructor in an actor class below

Example of a Constructor in an Actor Subclass

import greenfoot.*;

// comments omitted

public class Hero extends Mover
{
    private GreenfootImage image1, image2, image3;

    public Hero()
    {
        image1 = new GreenfootImage("bug-a.gif");
        image2 = new GreenfootImage("bug-b.gif");
        image3 = new GreenfootImage("bug-c.gif");
        setImage(image1);
    }

    // methods omitted
}

Constructing Objects

  • Notice how we create multiple new GreenfootImage objects and save the images for later use
  • The purpose of a constructor is to set up an object including instance variables
  • After the constructor finishes, we have four objects:
    • Three GreenfootImage objects
    • One Hero object
  • The instance variables are part of the Hero object and allow us to refer to the GreenfootImage objects
  • This is shown in the following diagram
  • The first object (Hero) is constructed in the world constructor
    addObject(new Hero(), 150, 100);
  • The image objects are constructed in the actor constructor
    image1 = new GreenfootImage("bug-a.gif");
    image2 = new GreenfootImage("bug-b.gif");
    image3 = new GreenfootImage("bug-c.gif");
    
  • These variables are known as reference variables because they refer to an object
  • We can see how reference variables work in the following image

Hero Object With Variables Referring to Image Objects

Hero object with reference variables

Check yourself

  1. The purpose of an Actor constructor is to ________
  2. True or false: a reference variable is a variable with a class name as the data type.
  3. Of the following variable declarations, ________ is a reference variable.
    1. int x;
    2. double trouble;
    3. float away;
    4. String aling;
  4. True or false: every object has a separate and unique set of instance variables.

4.3.6: Alternating Images with if-else Statements

  • Now that we have multiple images available, it is time to sequence the animation
  • For the animation to work, we need to alternate between the images
  • In other words, whenever we are were showing image1 we now want to show image2
  • Also, whenever we are were showing image2 we now want to show image1
  • For this alternation we can use an if-else statement
  • The if-else statement alternates between two conditions:
    • If a condition is true
      • then do this
    • Otherwise it is false
      • so do something else
  • Syntax:
    if (test) {
       statements1
    } else {
       statements2
    }
    
  • Where:
    • test: the test condition to evaluate
    • statementsX: the statements to execute depending on the test
  • For example:
    if (getImage() == image1)
    {
        setImage(image2);
    }
    else
    {
        setImage(image1);
    }
    

Diagram of if-else Statement Operation

If else operation

  • Notice that there is no test condition for the else clause
    if (getImage() == image1)
    {
        setImage(image2);
    }
    else
    {
        setImage(image1);
    }
    
  • The decision on which set of statements to use depends on only one condition
  • We might be tempted write an if-else as a pair of complementary if statements instead, like:
    if (getImage() == image1)
    {
        setImage(image2);
    }
    
    if (getImage() == image2)
    {
        setImage(image1);
    }
    
  • However, this actually does not work because:
    • the first if-statement sets the image to image2 and
    • the second if-statement sets the image right back to image1 before displaying the image
  • Also, it is easier and clearer to write an if-else statement
  • For clarity, write the if and else parts on different lines than the other statements
  • Also, indent the statements nested inside the curly braces

More Information

Check yourself

  1. If the current image displayed is image1, the image displayed after the following code fragment runs is ________.
    if (getImage() == image1)
    {
        setImage(image2);
    }
    else
    {
        setImage(image1);
    }
    
  2. True or false: there is a separate test condition for both the if and the else clause of an if-else statement.
  3. True or false: if alternation is taking place it is clearer to write an if-else statement.
  4. What is wrong with the following if-else statement? (answer)
    if (getImage() == image1)
    {
        setImage(image2);
    }
    else (getImage() == image2)
    {
        setImage(image1);
    }
    
  5. What is the value of x after the following code segment? (answer)
    int x = 5;
    if (x > 3)
    {
        x = x - 2;
    }
    else
    {
        x = x + 2;
    }
    
  6. True or false: always indent inside the curly braces of an if-else-statement.

4.3.7: Multiple Alternatives

  • It is possible to extend the image sequence with multiple if-else statements
  • We do this by nesting an if-else statement inside another if-else statement
  • We can nest in either the if clause or the else clause
  • When we want only one selection from a list then we should nest in the else clause
  • When we nest in the else clause, the else clause does not execute if the test evaluates to true
  • The else part executes only when the if test condition evaluates to false
  • The if statement inside the else clause works in the same way
  • By continuing to nest in the else clause, we can build a series of test conditions
  • The first test condition that evaluates to true executes and the remainder of the clauses are skipped

Psuedocode

  • Explaining the sequence is often hard to explain using natural language alone
  • It often helps to write out ideas like this using psuedocode
  • Psuedocode is an informal description of the steps for solving a problem
  • We just want to express the idea and not try to write syntactically correct programming code
  • For instance:
    if (current image is image1) then
        display image2 now
    else if (current image is image2) then
        display image3 now
    else
        display image1 now
    
  • Notice that our pseudo code is a mixture of natural language and programming code

Implementing the Sequencing With if-else Statements

  • When choosing between alternatives, we nest in the else clause
  • Syntax:
    if (test1)
    {
       statements1
    }
    else if (test2)
    {
       statements2
    }
    else
    {
       statements3
    }
    
  • Where:
    • testX: the test conditions to evaluate
    • statementsX: the statements to execute depending on the test
  • For example:
    if (getImage() == image1)
    {
        setImage(image2);
    }
    else if (getImage() == image2)
    {
        setImage(image3);
    }
    else
    {
        setImage(image1);
    }
    
  • The first test condition that evaluates to true is selected and no others
  • Notice that there is no test condition for the else clause
  • The final else clause serves as the default condition

Check yourself

  1. True or false: psuedocode is a technique for working out the logic of a program.
  2. True or false: we can choose among multiple alternatives by nesting an if statements in an else clause.
  3. If the current image displayed is image1, the image displayed after the following code fragment runs is ________.
    if (getImage() == image1)
    {
        setImage(image2);
    }
    else if (getImage() == image2)
    {
        setImage(image3);
    }
    else
    {
        setImage(image1);
    }
    
  4. In the above code, if the current image displayed is image2, the image displayed after the code executes is ________.
  5. In the above code, if the current image displayed is image3, the image displayed after the code executes is ________.

Exercise 4.3: Adding Animation (7m)

In this exercise, we add animation to our hero scenario.

Specifications

  1. Start Greenfoot and open the Hero scenario from the last exercise.

    If you did not complete the last exercise, download the following project file and continue with this exercise. Then go back and finish the last exercise at a later time.

    Scenario file: lesson4.gfar (or zip).

  2. Add the following images to the Hero scenario, saving the images with the names shown below the image:
    Bug with legs forward Bug with legs sideways Bug with legs back
    bug-a.gif bug-b.gif bug-c.gif

    For more information see lesson: 4.3.2: Adding Images to a Scenario.

  3. Add three instance variables to the Hero class named image1, image2 and image3 at the start of the class that are suitable for storing GreenfootImage objects.
    public class Hero extends Mover
    {
        private GreenfootImage image1, image2, image3; // add this line
        // other code ommitted
    

    For more information see lesson: 4.3.4: Instance Variables (Fields).

  4. Add a constructor to the Hero class after the instance variables as shown in the bold code below.
    public class Hero extends Mover
    {
        private GreenfootImage image1, image2, image3;
    
        public Hero()
        {
            // assign variables here
        }
        // other code ommitted
    

    For more information see lesson: 4.3.5: Writing Actor Constructors.

  5. Within the constructor, assign the following values to the instance variables as shown below:
    image1 = new GreenfootImage("bug-a.gif");
    image2 = new GreenfootImage("bug-b.gif");
    image3 = new GreenfootImage("bug-c.gif");
    
  6. Write a method named updateImage() and call the method from the act() method.
    public void updateImage()
    {
        // add if-else statements here
    }
    
  7. Add if-else statements to the updateImage() method to alternate between the images.
    if (getImage() == image1)
    {
        setImage(image2);
    }
    else if (getImage() == image2)
    {
        setImage(image3);
    }
    else
    {
        setImage(image1);
    }
    

    For more information see lesson: 4.3.7: Multiple Alternatives.

  8. Compile and run your scenario to verify the legs move on the hero.

    If you have problems, ask a classmate or the instructor for help as needed.

  9. Save a copy of your scenario to upload to Canvas as part of the next lab.

    We will be adding more code to these files in subsequent exercises, so it is not time to submit them to Canvas yet. However, it is a good idea to have a backup copy in case of problems later in development.

  10. When finished, check your code against the listing below and then help other students.

Partial Listing of Hero Class

public class Hero extends Actor
{
    private GreenfootImage image1, image2, image3;

    public Hero()
    {
        image1 = new GreenfootImage("bug-a.gif");
        image2 = new GreenfootImage("bug-b.gif");
        image3 = new GreenfootImage("bug-c.gif");
    }

    /**
     * Act - do whatever a Hero does.
     */
    public void act()
    {
        checkKeyPress();
        move(2);
        turnAtEdge();
        lookForFood();
        updateImage();
    }

    public void updateImage()
    {
        if (getImage() == image1)
        {
            setImage(image2);
        }
        else if (getImage() == image2)
        {
            setImage(image3);
        }
        else
        {
            setImage(image1);
        }
    }
    // other code omitted

4.3.8: Summary

  • Animation is the illusion of motion created by displaying a series of images or shapes:

    example animation

  • We looked at how to apply image animation to make our actors look more realistic
  • For this we discussed how to add more images to our scenarios
  • Then we discussed the GreenfootImage class and how to construct new image objects
    GreenfootImage img = new GreenfootImage("bug-a.gif");
  • We then change the image displayed by calling the setImage() method
    setImage(img);
    
  • To create an animation, we need to change the image many times per second
  • The best way to change the images repeatedly is to load the images once and save them in GreenfootImage objects
  • We looked at how to save images in instance variables (see below)
  • An instance variable is like a local variable but is available throughout the object
  • We code instance variables in a class and each object of the class has its own set instance variables
  • To initialize the instance variable, we added a constructor to an actor (see below)
  • After executing the constructor, we end up with multiple objects like this:

    Bug object with instance variables

  • To develop our thinking on alternating objects, we use pseudo code:
    if (the current image is image1) then
        display image2 now
    else
        display image1 now
    
  • Psuedocode is an informal description of the steps for solving a problem
  • We then translated the pseudo code to program code using an if/else statement (see section 4.3.7)

Code Snippet With Instance Variables, Constructor and Image Update

public class Hero extends Actor
{
    private GreenfootImage image1, image2, image3;

    public Hero()
    {
        image1 = new GreenfootImage("bug-a.gif");
        image2 = new GreenfootImage("bug-b.gif");
        image3 = new GreenfootImage("bug-c.gif");
    }

    /**
     * Act - do whatever a Hero does.
     */
    public void act()
    {
        checkKeyPress();
        move(2);
        turnAtEdge();
        lookForFood();
        updateImage();
    }

    public void updateImage()
    {
        if (getImage() == image1)
        {
            setImage(image2);
        }
        else if (getImage() == image2)
        {
            setImage(image3);
        }
        else
        {
            setImage(image1);
        }
    }
    // other code omitted

Check Yourself

Answer these questions to check your understanding. You can find more information by following the links after the question.

  1. What is animation? (4.3.1)
  2. What is the name of the method for adding images to a scenario? (4.3.2)
  3. True or false: in Greenfoot, the name of the class for storing images is called GreenfootImage. (4.3.3)
  4. Which of the following is NOT one of the methods of Actor that works with images? (4.3.3)
    1. getImage()
    2. setImage(String)
    3. setImage(GreenfootImage)
    4. changeImage(GreenfootImage)
  5. True or false: an instance variable is a place to store date in memory. (4.3.4)
  6. What is the difference between a local variable and an instance variable? (4.3.4)
  7. True or false: an instance variable is a variable defined in a class for which each object (instance) has a separate copy. (4.3.5)
  8. What is the purpose of a constructor? (4.3.5)
  9. If the current image displayed is image1, what image is displayed after the following code fragment runs? (4.3.6)
    if (getImage() == image1)
    {
        setImage(image2);
    }
    else
    {
        setImage(image1);
    }
    
  10. True or false: there is a separate test condition for both the if and the else clause of an if/else statement. (4.3.6)

4.4: Counting and Arithmetic

Learner Outcomes

At the end of the lesson the student will be able to:

  • Count in Java
  • Discuss the two ways that Java stores numbers
  • Code simple arithmetic

4.4.1: Counting Food Click for link

  • Games need a way to win and a way to loose and scenarios must end
  • We already have a way to loose our scenario -- the hero gets eaten by a predator!
  • However, we still need a way to win the scenario
  • One way we can win our scenario is to count the number of food objects eaten
  • When our hero eats some number of food objects, say 8, we win the game
  • We can also play a short success sound when this happens

Counting

  • To keep track of the number of food objects eaten, we need to count
  • In Java, we count with a variable, a little arithmetic and an assignment statement
  • We start by declaring a variable like:
    public class Hero extends Mover
    {
        private GreenfootImage image1, image2, image3;
        private int foodEaten;
    // other code here
    
  • As we discussed in lesson 4.3.4, we always start an instance variable with the word private
  • The data type int means we are storing integer (whole number) data
  • As we learned before, we assign new values to variables using a single equal (=) sign
    foodEaten = 0;     // initialize count to 0
    
  • Remember that the equal sign is really an assignment operator and does not denote equality
  • Thus, unlike math, we may have the same variable on both sides of an equals sign:
    foodEaten = foodEaten + 1; // add to count
    
  • In an assignment statement, the right-hand side is always evaluated first
  • On the right-hand side, we read the value of foodEaten from memory and add 1 to it
  • Then we assign the value back to the foodEaten variable as the concluding step
  • As a result, the variable is incremented by 1

    Incrementing a variable by 1

Increment and Decrement Operators

  • Adding or subtracting one is a common operation in programming
  • Java provides arithmetic shortcuts for these operations with the increment and decrement operators
  • The increment operator (++) adds 1 to a variable's value
  • Post-increment evaluates the expression and then adds 1
    foodEaten++;
  • Preincrement adds 1 before evaluating an expression
    ++foodEaten;
  • The decrement operator works like the increments operator, except it subtracts 1 from the variable:
    foodEaten--;
    --foodEaten;
    

When Pre- and Post- Increment Matters (Optional)

  • Pre- and post- increment matters when the operation is part of a larger expression
  • For example, consider the code:
    int x = 5;
    int y = x++;
    System.out.println("x=" + x + " y=" + y);
    
  • We may expect y to be 6 after this code executes
  • Instead, y has the value of 5
  • The reason is that ++ after a variable (post-increment) is equivalent to:
    y = x;
    x = x + 1;
    
  • On the other hand, ++ before a variable (pre-increment) is equivalent to:
    x = x + 1;
    y = x;
    

Check yourself

  1. True or false: the following variable is an instance variable.
    private int count;
  2. The value of count after the following code executes is ________.
    int count = 0;
    count = count + 1;
    
  3. In the following assignment statement, the ________ side of the equals sign is evaluated first.
    count = count + 1;

4.4.2: Winning the Game

  • Now that we can count, let us look at how to win the game
  • In the lookForFood() method, we increment our foodEaten variable
    foodEaten = foodEaten + 1;
  • After we increment the variable, we test to see if we have met the win condition
  • If so, we play the success sound and stop the game
  • Here is a success sound we can use: success.wav
  • See the updated lookForFood() method below

Method lookForFood() With Win Condition

/**
 * Checks whether we have stumbled upon a food object.
 * If we have, then eat it. Otherwise, do nothing.
 */
public void lookForFood()
{
    if (isTouching(Food.class)) {
        removeTouching(Food.class);
        Greenfoot.playSound("slurp.wav");

        foodEaten = foodEaten + 1;
        World w = getWorld(); // w is a reference variable
        w.showText("Score: " + foodEaten, 42, 12);
        if (foodEaten >= 8) {
            Greenfoot.playSound("success.wav");
            w.showText("You Win!", 315, 200);
            Greenfoot.stop();
        }
    }
}

Testing Our Code

  • We should always test our code after any change to make sure it works correctly
  • In general, we should test our code every time we make a change
  • To test our counting code, we inspect our Hero object

    Inspect the hero

  • When the scenario runs, notice how the foodEaten variable increments each time the hero eats a food object

Displaying Text

  • One of the methods of the World is showText()
  • The showText() method will display text at a specified location in the world
  • The method has the following signature:
    void showText(String text, int x, int y)
    
  • Where:
    • text: literal text (in double quotes) or a String variable
    • x: the x coordinate of the location where the object is added
    • y: the y coordinate of the location where the object is added
  • To call the method, we supply arguments for the parameters like:
    getWorld().showText("Score: " + foodEaten, 30, 100);
    
  • Since showText() is a method of the world, we must prefix the method call with getWorld().
  • The Actor method getWorld() returns a reference to the world in which the actor exists

Check Yourself

  1. True or false: when an object contains an instance variable, we can see the value of the instance variable by inspecting the object.
  2. The three statements for counting food are:
    1. ________
    2. ________
    3. ________
  3. After every change, one should ________ the code.
  4. The world method for displaying text to the game screen is ________.

4.4.3: More About Numbers

  • While we are working with numbers, lets discuss how Java handles them
  • Java has two general types of numbers: integers and floating-point (decimal)
  • Both integers and floating-point numbers cannot have any commas or other special symbols

Integer Numbers

  • An integer is zero or any positive or negative number without a decimal point
  • For example:
    0   1   -1    +5    -27   1000    -128
  • We call numbers like these literal integers because they represent what they look like

Floating-Point Numbers

  • A floating-point number is any signed or unsigned number with a decimal point
  • For example:
    0.0   1.0   -1.1   +5.   -6.3    3234.56    0.33
  • Note that 0.0, 1.0 and +5. are floating-point numbers, but could be rewritten as integers

Storing numbers

  • Integers and floating-point numbers are stored in different ways
  • Java stores the integer types as a binary number
integer representation
Image source: Dan Gookin
  • Java stores floating point numbers in a format known as IEEE 754
single precision representation
Image source: Dan Gookin
  • We must specify the data type of a variable so the computer can handle numbers correctly

Some Commonly Used Numerical Data Types

Type Bytes Use
int 4 Integers with a range from -2,147,483,648 to 2,147,483,647.
float 4 Single-precision, floating-point numbers with 6 or 7 significant digits, +/- range, and exponents from about 10-45 to 1038.
double 8 Double-precision, floating-point numbers with 14 to 15 significant digits, +/- range, and exponents from 10-308 to 10308.

Check yourself

  1. The two types of numbers in Java are ________ and ________.
  2. Of the following literal numbers, the integer is ________.
    1. 1
    2. 1.2
    3. 1.23
    4. 1.234
  3. If you want to count with whole numbers, use the data type ________.

4.4.4: Arithmetic

  • When we work with numbers, we often want to perform some simple arithmetic
  • Java uses the following operators for arithmetic:
    • + for addition
    • - for subtraction
    • * for multiplication
    • / for division
    • % for modulus (remainder after division)
  • Modulus is a type of division operation for integer numbers

Precedence Rules

  • Precedence: what gets done first
  • In algebra we are taught to use PEMDAS
    • Parentheses, Exponents, Multiplication and Division, and Addition and Subtraction
  • Arithmetic operators in Java are processed in the same algebraic order:
    1. Parenthesis: ( )
    2. Multiplication, division, modulus: *, /, %
    3. Addition, subtraction: +, -
  • Operators of same precedence are evaluated from left to right
  • As in algebra, multiplication and division are performed before addition and subtraction
  • To change the order of operation, we use parentheses
  • For example:

    a + b / 2 is written as: a + b / 2

    (a + b) / 2 is written as: (a + b) / 2

  • In the following examples, the fully parenthesized column shows the precedence explicitly
  • Notice that we cannot use parenthesis to indicate multiplication, but must explicitly use the '*' operator in Java

Examples of Expressions

Algebra Expression Java Expression Fully Parenthesized
2(10 + 5)
2 * (10 + 5) (2 * (10 + 5))
1

12.2 + 3 · 7.3
1 / (12.2 + 3 * 7.3) (1 / (12.2 + (3 * 7.3)))
10 - 7

3.2 + 9 · 1.6
(10 - 7) / (3.3 + 9 * 1.6) ((10 - 7) / (3.3 +(9 * 1.6)))
2 · 42
2 * 4 * 4 ((2 * 4) * 4)

Integer Division and Remainder

  • Dividing two integers can produce unexpected results for the unwary
  • In division, if at least one of the numbers is a floating-point number, the result is a floating point number:
    7.0 / 2.0   // 3.5
    7 / 2.0     // 3.5
    7.0 / 2     // 3.5
    
  • However, if both numbers are integers, then the result is an integer:
    7 / 2       // 3
    
  • The decimal remainder is truncated (cut short, discarded, thrown away)
  • To get the remainder from division, we use the remainder (modulus) operator: %
    7 % 2       // 1 (remainder)
    
  • 7 % 2 returns 1 because 1 is the remainder when 7 is divided by 2:
        3  r 1
    2 ) 7
       -6
        1 remainder
    
  • For a refresher on remainders see: Long Division with Remainders
  • In Java, the remainder operator (%) can be used with both integers and floating point numbers
    0.5 % 0.3   // 0.2
    

More Information

Check yourself

  1. The five arithmetic operators in Java are ________.
    1. +, -, /, *, %
    2. +, -, \, *, %
    3. +, -, /, *, ^
    4. +, -, \, *, ^
  2. The first operation performed in the following arithmetic expression is ________.
    1 + 2 * 3 / 4 % 5
    
  3. If we wanted a different ordering of operations in the above example, we add ________ to the expression.

Exercise 4.4: Finishing the Game (5m)

In this exercise, we add a successful ending condition (win!) to our scenario.

Specifications

  1. Start Greenfoot and open the Hero scenario from the last exercise.

    If you do not have your exercise, start with this one: lesson4b.gfar (or zip).

  2. Add an instance variable to the Hero class named foodEaten that is suitable for storing integer numbers:
    private int foodEaten;
    
  3. In the constructor of the Hero class, set the value of foodEaten to zero (0).
    foodEaten = 0;
    
  4. In the lookForFood() method, add code to increment the value of foodEaten.
    foodEaten = foodEaten + 1;
    

    For more information see lesson: 4.4.1: Counting Food.

  5. Save the following sound file in the scenario "sounds" folder: success.wav

    For more information see lesson: 3.5.3: Adding Sound.

  6. In the lookForFood() method, add code to test the number of food eaten and play both the success.wav sound and stop the game.
    public void lookForFood()
    {
        // .. some code omitted here
        foodEaten = foodEaten + 1;
        if (foodEaten >= 7) {
            Greenfoot.playSound("success.wav");
            Greenfoot.stop();
        }
    }
    

    For more information see lesson: 4.4.2: Winning the Game.

  7. Save a copy of your completed lesson scenario to upload to Canvas as part of the next lab (Lab 4).

When finished, please help those around you and then try the following Crossword Puzzle.

Crossword Puzzle

Fill in the crossword which is based on concepts from this section.

  1
              2
 
3
       
            4
   
               
      5
       
6
               
                   

Across

3. Base two number system
6. Used to group arithmetic expressions

Down

1. What it looks like
2. ______-point; number with a decimal point
4. Number of arithmetic operators (as a word)
5. Data type for an integer

As time permits, read the following sections and be prepared to answer the Check Yourself questions in the section: 4.4.5: Summary.

4.4.5: Summary

  • Games need a way to win and a way to loose and scenarios must end
  • In this section we looked at how to win our scenario by counting the number of food objects our hero ate
  • To keep track of the number of food objects eaten, we need to count
  • In Java, counting is done with a variable, a little arithmetic and an assignment statement
  • The pattern is to declare and initialize a variable by setting its value to zero (0)
  • Every time we want to add to the count, we add one to the variable
  • For example:
    foodEaten = 0;     // initialize count to 0
    foodEaten = foodEaten + 1; // add to count
    
  • To check for a winning condition, we just add an if-statement like:
    if (foodEaten >= 8) {
        Greenfoot.playSound("success.wav");
        Greenfoot.stop();
    }
    
  • We also looked at how we can test the code by inspecting the Hero:

    Inspect the hero

  • In general, you should test your code every time you make a change
  • We also looked at numbers and arithmetic in this section
  • Java has two general types of numbers: integers and floating-point
  • Integers are whole numbers (no decimal point) and floating point numbers have decimal points
  • Both types of numbers are stored in a different way by the computer
  • Because of the differences, you must specify the data type of a variable so Java can handle them numbers correctly
  • Java uses the following operators for arithmetic:
    • + for addition
    • - for subtraction
    • * for multiplication
    • / for division
    • % for modulus (remainder after division)
  • As in algebra, multiplication and division are performed before addition and subtraction
  • To change the order of operation, we use parenthesis

Check Yourself

Answer these questions to check your understanding. You can find more information by following the links after the question.

  1. What is the value of count after the following code executes? (4.4.1)
    int count = 0;
    count = count + 1;
    
  2. True or false: You should always test your code after making changes. (4.4.2)
  3. How can you tell the difference between an integer and a floating-point number? (4.4.3)
  4. Which of the following is an integer? (4.4.3)
    1. 1
    2. 1.2
    3. 1.23
    4. 1.234
  5. What are the five operators Java provides for arithmetic? (4.4.4)
  6. What is the first operation performed in the expression: 1 + 2 * 3 / 4 % 5? (4.4.4)

4.5: Sharing Scenarios

Learner Outcomes

At the end of the lesson the student will be able to:

  • Share your scenarios with others
  • Publish scenarios on the web

4.5.1: Exporting Your Scenarios

  • When we finish a scenario, we may want to share it with others
  • Users of our work need to start and run the scenario, but not to see the class diagram or source code
  • Greenfoot has the capability to export a scenario so that others can use, but not change, our scenario
  • Also, we can decide whether to share our source code or not

Documenting Our Work

Exporting Scenarios

  • To export scenarios, we click the Share button
  • After this, we will have a choice of three export options:

    Scenario export types

  • Publish adds your scenario to the Greenfoot Gallery on the web at greenfoot.org/home
  • Application produces an executable JAR file that will run on any computer with Java installed
  • Project makes a zip-like project folder called a GFAR.
  • We will look at each of these options in the following sections

4.5.2: Publishing on the Greenfoot Gallery

  • The first export option lets you publish your scenario to the web at greenfoot.org
  • The Greenfoot gallery is a public site that lets anyone see and run your scenario
  • The Greenfoot site automatically converts scenarios using the TeaVM transpiler
  • To submit scenarios or post comments, we need to register
  • During our first quest (Q1: Getting Started) we all registered using our Avatar name
  • Registration is to make sure everyone follows the rules of:
    • Be nice
    • Don't do anything stupid, offensive or illegal
  • When we choose this option, we will see a dialog like that shown below
  • We can change or even delete any scenarios that we upload

Dialog Options

  • Notice the "Cabrillo" tag
  • This lets us find other Cabrillo students
  • Another option is to lock your scenario
  • Locking a scenario removes the Act button and the speed slider
  • Typically you lock the scenario for games
  • However, if you have a more experimental simulation, you can export your scenario without locking

Export to Gallery Dialog

Export to gallery dialog

4.5.3: Exporting to an Application

  • The second option is to export as an application
  • An application is a program that users can run on any computer with Java installed
  • Java application files have a suffix of .jar, which is short for Java ARchive
  • To distribute your scenario, you just give people a copy of your executable JAR file and some install instructions
  • The instructions need to include the commands to run on their machine
  • Unfortunately, starting with Java 11 these commands are complicated
  • For more information see: Running Exported Standalone Scenarios

Export to Application Dialog

Export to application dialog

4.5.4: Exporting to a Greenfoot Project

  • Another option is to create a project .gfar file
  • This allows the whole project to be given to someone as a single file
  • Then anyone with Greenfoot installed can open and run the project
  • This may be useful while working with other guild members

Export Project Dialog

Export to Greenfoot project dialog

Exercise 4.5: Exporting (5m)

In this exercise, we export our Hero scenario.

Specifications

  1. Start Greenfoot and open the Hero scenario from the last exercise.
  2. Press the Share button in the upper left-hand corner of the main screen.

    Share button

  3. Click the Project menu.

    Export as project dialog

  4. Export the Hero scenario as a Greenfoot Project and save the file to a convenient location like the Desktop.

    For more information see lesson: 4.5.4: Exporting to Greenfoot Project.

  5. There is no need to turn in the exported file.

As time permits, be prepared to answer the Check Yourself questions in the section: 4.5.5: Summary.

4.5.5: Summary

  • Greenfoot makes it easy to share your scenarios with others
  • We may publish on the web using the Greenfoot Gallery
    • The Greenfoot Gallery is a public web space that the makers of Greenfoot provide
    • Anyone can view and use the scenarios on the gallery
    • However, to submit scenarios or post comments, we first need to register
  • We may create an executable JAR file that people can run on any computer with Java installed
    • However, instructions for running can be complicated
  • We may also export to a project that anyone with Greenfoot installed can run
    • This option may be useful when working on projects with others

Check Yourself

Answer these questions to check your understanding. You can find more information by following the links after the question.

  1. What are three ways to share your scenarios? (4.5.1)
  2. True or false: anyone can publish to the Greenfoot Gallery as long as you register. (4.5.2)
  3. True or false: exporting as an application creates a JAM file. (4.5.3)
  4. True or false: exporting as a project lets you share your complete scenario with others. (4.5.4)

4.6: Guild Next Steps

Learner Outcomes

At the end of the lesson the student will be able to:

  • Describe the typical phases of a guild
  • Describe how to develop a high-perfoming guild
  • Develop an action plan for the guild

4.6.1: Phases of Guild Development

  • When guilds, or any team, develops they tend to go through stages
    1. Forming: members learn about what they need to do
    2. Storming: members form opinions about other members and often voice those opinions
    3. Norming: guild members take responsibility to meet goals and work towards the group's success
    4. Perfoming: with group norms and roles established, members focus on achieving goals

Forming

  • Guild members get to know each other during this stage
  • Most guild members are positive and polite
  • Some members are anxious to understand what the group will do
  • People make an effort to get to know each other
  • During this stage it is important to select a leader to help organize the group

Storming

  • In this stage, people start to push against the initial boundaries
  • Members often develop conflict because of different people's working style
  • People may become frustrated with differences in each other's approach
  • Some members may even refuse to complete their tasks, leaving the projects in disarray
  • Disagreements and personality clashes must be resolved so the team can progress
  • During this stage it is important to resolve conflicts quickly if and when they occur
  • By defining standards of behavior, the group can move past this stage

Norming

  • In this phase, members start to resolve their differences
  • Members start tolerating the whims and fancies of the other team members
  • They accept others as they are and make an effort to move on
  • People start to build on each other's strengths
  • Members are able to ask one another for help and provide constructive feedback

Perfoming

  • In this stage the team works hard without friction to achieve goals
  • The guild makes most of the necessary decisions to meet goals through consensus

More Information

4.6.2: Canvas Communication Tools

  • Canvas has a number of communication tools that can help your guild

People

  • The People page shows all the users enrolled in the course
  • The Groups tab shows all the current members of your guild
  • If a student member chooses to do so, the student can add information to their account profile
  • For example, a student could add contact information
  • More information: How do I use the People page as a student?

Chat

  • The Chat tool allows students and teachers to interact in real time
  • It is like texting but within Canvas
  • Everyone actively viewing the chat tool appears in the chat list
  • A guild could arrange to meet during a certain time through chat
  • More information: How do I use Chat as a student?

Collaborations

  • Canvas allows multiple people to work together on the same document at the same time
  • Documents are saved in real-time, meaning a change made by any of its users will be immediately visible to everyone
  • Google Docs is the default collaborations tool
  • Each collaborator will need a Google account to use this tool
  • A guild could use a collaboration to develop an action plan or game proposal
  • More information: How do I create a Google Docs collaboration as a student?
  • Pronto app is also available inside Canvas or on your phone

Google Drive

Non-Canvas Tools

  • Discord: free voice and text chat for gamers
  • Skype: free video and voice chat over the internet
  • Teamspeak: free voice and text chat for gamers

4.6.3: Guild First Goals

  • First guild goal: decide on a name for the guild (due today)
  • Second guild goal: get to know each other and choose a leader willing to help all the members
  • Third guild goal: Develop guild norms.
  • Fourth goal will be to work together to develop a scenario in Quest 6

What Sets Successful Groups Apart from Others?

  • Psychological safety: Can we try new things on this team without feeling insecure or embarrassed?
  • Dependability: Can we count on each other to do high quality work on time?
  • Structure and clarity: Are goals, roles, and execution plans on our team clear?
  • Meaning: Are we working on something that is personally important for each of us?
  • Impact: Do we fundamentally believe that the work we're doing makes a difference?

Good Guild Norms

  • Establish psychologically safe environments

    No bullying. To succeed, each and every team member must feel confident speaking up and making mistakes. Each member must know they are being heard.
    Suggestion: Start team's first meeting by sharing something about yourself.

  • All teams members speak roughly the same amount

    Otherwise the collective intelligence declines.

  • Member's listen to each other and are sensitive to member's feelings.

    Chat before and after meetings. Joke around and have fun.

  • Express enthusiasm for one another's ideas.
  • Ask a lot of questions.
  • Always have goals and a plan to meet them.

    Set clear action items so everyone knows what is expected and by when

  • Develop a culture of dependability.

    We work as much as it takes to get things done on time.

More Information

Wrap Up

Due Next:
Q3: Methodical Improvement (2/20/20)
B4: Thinking clearly (Canvas) (2/25/20)
Lab 4: White Blood Cell (2/25/20)
Q4: Finishing Touches (2/27/20)
  • When class is over, please shut down your computer
  • You may complete unfinished lesson exercises at any time before the due date.
Last Updated: April 05 2020 @17:21:59