Unit 1B: Backwoods Forest

Layout of Backwoods forest

Learning Outcomes

This unit reinforces the techniques learnt in the last unit: loops, objects and methods. It also introduces new, intermediary programming techniques such as conditional and function. It will also explore more datatypes such as the list, dictionary and array. By the end of the unit student shouldbe able to:

  • Understand Python’s variable naming convention
  • Understand conditional and how to use it inconjunction with loop and if
  • Write code that has nested loops and ifs
  • Access the property of an object and use it tomake decisions
  • Write code that responds to human input
  • Use mathematical operators and pass the resultas an argument in a method without knowing the value of at least one of theoperands
  • Accesses passed time and use it to assistdecision
  • Use variables to keep track of a changing valueby repeatedly adding or subtracting
  • Use the break command to terminate a loop
  • Understand function and get to know when and howto use it
  • Know the difference between argument andparameter
  • Get to know the idea of refactoring
  • Access a specific item in an array by using itsindex value
  • Loop through all the item in array byincrementing an index value

Timeframe

For most students, this part can be done within 6-7 hours.

CS Standards

  • Use data values that they don’t know the exact value of within their code for decision making, comparisons, and arithmetic(including incrementing).
  • Terminate loops in a variety of ways.
  • Access a specific datum or loop through the dataset in an array or list by utilizing index values.
  • Use a loop to cycle through a list or array ignoringor acting upon objects with specific properties.

Concepts Reinforced

**String ** strings can be combined together toform new strings. Some parts of the string can be from variables!

**Variable ** A variable can be assigned from othervariables. Or it can be assigned to a manipulation of itself, by adding orsubtracting it.

Boolean Values Variables can be True and False depend on circumstances. This ishow we determine the flow of program. If conditional: means the followingstatements will run if the condition is met.

Objects and Methods

The idea of object is an extremely powerful programmingconcept that has been adopted by nearly all major high level programminglanguages today. At this point students won’t have to worry about how to defineobjects of their own, but they will need to know how to identify an object (theentity before the dot!) and some ideas of what it means to access an object.

Methods belong to an object and they perform some action. Itis the part after the dot. The parentheses at the end let the computer knowthat it is a method instead of property.

New Concepts

Properties

Properties save values or attributes related to an objectand are attached to an object with a period. A property follows an object andthe dot but do not have parentheses.

Conditional

Programming is all about handling various situationsautomatically. The key component to allow such flexibility is the conditional:a condition can be evaluated either as True or False.

If statement

The if statement determines a particular path that the coderuns at a given moment.

Input

Input is what the program takes in while it is running. Inthis course, the only form of input is the flags.

Conditional Loops

A while loop is used to repeat actions without the playerneeding to write the same lines of code over and over. The loop can be used inconjunction with conditional to limit its running time.

**Lists or Arrays ** A list is a collection of similaritems. All these items have a corresponding index, which is how we access it.

**Break ** Break is a command that breaks out aloop when the computer sees it. The computer will run the code immediatelyafter the loop.

Levels and their corresponding skills

Levels Programming concepts
1) Defense of Plainswood 2) Winding Trail String (item type) and number (coordinates) as argument
3) One Wrong Step 4) Forest evasion New method: MoveXY; combined with loop
5) Patrol Buster 6) Picnic Buster 7) Eagle Eye Loop, variable and conditionals (if enemy) together
8) Thumb biter 9) Gems or Death Conditionals and arithmetic operations
10) Village Guard Defining variables and use as conditionals
11) Back to Back Conditional plus moveXY
12) Ogre Encampment Simple If then else structure
13) Woodland Cleaver 14) backwoods standoff New method: cleave; conditional as timing of action
15) Peasant protection New method: distanceTo; use as conditional
16) Muchkin swarm DistanceTo combined with loop and if-else structure
17) forest fire dancing Coordinates with if else
18) stillness in motion 19) The Agrippa Defense Combinatory use of loop, two cases of conditional (if enemy; distance), and proper course of action (coordination move or attack)
20) village rover Introducing FUNCTION-reuse
21) a fine mint Sequencing of functions
22) leave it to the cleaver Function with parameter
23) Agrippa refactored Introducing “refactor”
24) Agrippa returned Function as conditional: return value
25) Backwoods buddy Everything is an OBJECT; New method: findNearestItem()
26) Go fetch 27) friend and foe Event trigger, Object and function
28) deja brew String manipulation
29) the wizard’s door 30) the wizard’s haunt 31) the wizard’s plane Arithmetic operations and variable
32) Coinucopia New method: flag; user input handling and interaction
33) Burlbole grove Function and return value
34) Copper Meadows Position as an object with assignable attributes; input handling (flags)
35) Drop the flag Flag as object; pos attributes; item’s position
36) Mind the trap Incorporating flags into the combined structure of loop, conditionals.
37) Hold the Forest Pass Boolean operation in conditionals
38) Signal Corpse Else and elif
39) Rich Forager Else if: stacked conditionals
40) Siege of Stonehold Everything above: this unlocks the desert world

Lesson Plans

Defense of Plainswood

Objectives

  • Use number and strings as arguments in methods
  • Find coordinates

Main Lesson

This level is similar to the last level of last world: use buildXY() method to build “fence” and block out the ogres! Move your mouse cursor over a spot to find the x and y numbers of the location.

Winding Trail

Objectives

  • Understand moveXY() method

Main Lesson

Forget those old simple moveRight boots! Your new boots letyou move continuously until you reach a specified point! It takes two arguments: x and y.

Just like with buildXY, you can hover over the level to find x and y coordinates for you to move to.

Stop the ogre from getting you by building a fence on the X marker. Check out the bonus achievements on this level for grabbing extra gems if you want an extra challenge.

One Wrong Step

*Objectives

  • Reinforce the use of moveXY()

Forest Evasion

Objective

  • Combine moveXY() with the loop

Woodland Cubbies

Objectives

  • Use if statement to execute a code only if the condition is true
  • Understand what is Null and how does that work as conditional

Main Lesson

Your new Programmaticon book grants you more statements and methods! It now gives the ability to use if-statements.

An if-statement dictates that, if the condition specificed is true, then run the code that follows.

The if-statement consists of three things:

  1. the if keyword
  2. the conditional, which is an expression that will be evaluated into True or False in runtime
  3. the colon!
    Also, remember that the if-statement is like while True loop: codes that belong to them will need to be indented.

To complete this level, you should move to each of the X marks with moveXY. At each X spot, use findNearestEnemy() to find the enemy and attack it.
However, you need to know that there may or may not be an ogre when your program runs at this particular moment–The ogres are spawned randomly each time you press the Submit button! So you need to use an if statement to determine if an ogre is present at each spot:
`if enemy:

If there is an enemy, the conditional will be an object. If not, it will be NULL, which translates to False. It is important to check if the enemy exists, otherwise you will get an error by trying to attack an enemy when there is no one!
Also, pay attention to the following structure as it will be used numerous times later on!

Patrol Buster, If-stravaganza, Picnic Buster

Objectives

Combine if statement with While True loop

Main Lesson

Now that you have learned how to use conditional and if, combine these with the while-true loop to keep killing enemies! All the above levels are exactly the same. Use them to reinforce the idea.

Eagle Eye

Objective

  • Understand that enemy is not always called enemy!
    Main Lesson
    This lesson is optional. If the student chooses to work on it, it offers a similar exercise with a bit of healthy twist. The result of findNearestEnemy() is assigned to a variable named target. Tell the student it is important to have consistency: once you change enemy to target, you need to use target in the following, such as as argument inside a method.

Gems or Death:

Objectives

Understand how the conditional is generated

Main Lesson

This level is still about other ways to generate the conditional for if statement. Instead of using the result returned by a method, we use comparison of numbers. But you don’t have to write any code. Your job is debugging and fixing the conditionals so that the actions you want your hero totake happen and the ones you don’t want don’t happen.

For example:

if 1 + 1 + 1 == 3:

hero.moveXY(5,15) # Move to the first mines.

Since 1 + 1 + 1 does equal 3 the conditional, which is the whole part of 1+1+1==3, turns out to be true. So, off into the mines we run…

Village Guard

Objectives

  • Understand how python variables should be named
  • Use multiple if-statements inside the loop

Main Lesson

Ogres are coming from the left and right, so you need two variables to refer to them: one is called leftEnemy, the other, rightEnemy.
Notice that we do NOT capitalize the first letter in a python variable. But we do need to capitalize every first letter of all the words that follow!

Reflection question: what happens if your hero goes to the left and doesn’t see an enemy there?

Back to Back:

Objectives

  • Use if statement with the else part to divide situations according to the conditional

Main Lesson

This level introduces the else part of if-statement. When you add an else clause, you tell the computer what to do both when the condition is not true. For example, if there is an enemy then attack it, else move to the X.

To show you how it works, the if and the else are set up for you, and you need to put in the attack and moveXY methods so that your hero attacks enemies on sight, but when there are no enemies, moves back to the X marker to defend the peasants.

Make sure you get the coordinates for the X marker correct,or you might not be able to defend both your peasants in time.

Reflection Question: what happens if you don’t go back to the middle?

Ogre Encampment

Objectives

  • Use if/else statement

Main Lesson

For this level, you’ll need to use both if and else to attack different targets. When the ogres attack you, you want to fight back, but when there are no ogres, you shouldn’t stand there idling. Instead you need to keep attacking the “Chest” to open it.

Woodland Cleaver

Objectives

  • Use the two new methods cleave(), and isReady()
  • Understand how to use cleave together with isReady()

MainLesson

The woods are swarming with ogre munchkins, but you have a new Long Sword, and its cleave ability will make short work of them! Cleave hits every enemy within ten meters of your hero and deal damage to all of them at once.

Special abilities like cleave have cooldown periods, which means you can’t use them all the time. For example, you can only cleave every ten seconds. So when you want to use your special ability, you need to check if they are ready to use first. This is granted to you by your Sundial Wristwatch.

Cleave() doesn’t take any argument. But isReady() does because there are other special abilities.

Reflection question: is there anything wrong with the above code? What happens if there is no enemy?

Backwoods Standoff

Objectives

  • Use if-else statement with different actions

Main Lesson

This level will sometimes not working correctly. But when it does, the enemies should be scared away when your hero say “Boo!”. If this is not the case, simply use attack(enemy) instead.
This level will grant you crude glasses which is required for next level.

Range Finder

Objectives

  • Understand how distanceTo(object) method works

Main Lesson

You’ve been asked to test special glasses that can see through trees! This time, you don’t need to go out and deal with the ogres personally.

Your artillery can’t sight through the trees, so use distanceTo() and say() to call out the range to each target.

Be careful, though! There are peaceful woodsmen living in these woods.

Peasant Protection

Objectives

  • New method: distanceTo()
  • Use conditional to determine your action: attack or defend

Main Lesson

In this level, you’ll use the measured distance to your enemy to make sure you stay close to vulnerable peasant. If your enemy is too far away, don’t be tempted to go after them because other enemies will sneak up and kill your peasant! In order to do this you need to:

  1. Never go attack enemy that is 10 meters away.
  2. Once you finish an enemy, always come back to the defending point.

Munchkin Swarm (now Maniac Munchkin)

Objectives

  • Use nested if-statement
  • Make sure the else statement is matched to the right if

Main Lesson

In this level, you put together everything you’ve learned over the past few levels in order to use if/else, distanceTo, <, and cleave to defeat vast numbers of ogre munchkins while looting a giant treasure chest.

These munchkins have become suitably terrified of you and your mighty Long Sword, so they will only approach when there are a lot of them together in a pack. Check the distance to the nearest munchkin and only cleave if the munchkin is closer than ten meters. Use an else clause to attack the “Chest” otherwise.

Tip: Make sure you match your else to the right if; check your indentation!

Forest Fire Dancing

Objectives

  • Understand different possibilities and how to divide them into if and else branches
    Main Lesson
    Most students cannot solve this level by themselves! It makes sense therefore to make sure they have enough practices in nesting ifs and then do more exercises on dividing conditions before they try to tackle this level.
    Analysis of the situation:
    First, there could be an evilstone or not. We need to use one if statement for that purpose. We would assume that we start from the middle position and if there is no stone, we would go back to the middle.
    Then the evilstone could come at left and right. We just go to the opposite direction.
    Finally, what happens when the stone comes at the middle?

Stillness in Motion

Objectives

  • Understand new method: shield()
  • Reinforce the use of nested ifs
  • Understand how to make a structure for the code first and fill in the details later

Main Lesson

For this level, you want to stay in the middle where the Headhunters can’t see you! You will use nested if-statements. When dealing with nested if statements, you need to pay close attention to how you set up the flow of your program. If your if statements are complicated, it’s often easier to build them up one at a time, using comments to fill in the future statements. For example, in this level we could begin by writing the following:

Next, fill in the if/else statements and their conditions for real.

Then, fill in the action statements.

Finally, wrap everything inside a loop. You can highlight several lines of code and press Tab to indent all of those lines, or Shift+Tab to un-indent all of those lines!

The Agrippa Defense

Objectives

  • Reinforce the combinatory use of loop and nested ifs
  • Understand the increasing mental complexity of nesting ifs

Main Lesson

Sometimes it’s best not to open with your strongest attackimmediately. If you cleave at the first sight of the enemy, you may only catchthe first few, leaving their friends to finish you off!

Try using distanceTo() to wait until the enemy is closer before you cleave. You can experiment to find the best range at which to strike; in this level, around 5 meters works well.

If your cleave isn’t ready, don’t just stand there! Use a normal attack() while you wait for it to be ready again.

Your code may end up having three layers of if-statement. This is as far as you would go for such things. More nesting you would quickly lose the ability to debug!

Reflection question: what happens if you match the else with a wrong if?

Village Rover

Objectives

  • Understand Function: how to define it and call it
  • Understand the concept of readability
  • Understand what part of the code belong to the function and what part belongs to the main loop

Main Lesson
This level introduces a very important concept: function. A function is a chunk of code that you reuse multiple times. But even if you only use a function once, it adds to the readability of your code.
In the following code, what follows def is how do we define a function. Note that the parentheses are mandatory, with or without anything inside. Pay attention to that colon!
Inside the function everything needs to be properly indented.
If a chunk of code doesn’t belong to any function, then it belongs to the main loop.
When the computer runs your program, it goes to the main loop first and if they see you calling a function, it will then go to the function definition to see how to run it.

Reflection question:

What happens if we define a function without calling it?

What happens if we define a function AFTER we call it?

Backwoods Fork

Objectives

  • Reinforce the idea of function
  • Use parameters in the function

Remember the last time we need to go left and right for incoming enemies? This time, they come from top and bottom.
Also, notice that there is something named target inside the parentheses of function definition. This is called parameter.

A parameter needs to match an argument, like this:
def checkAndAttack(target):

checkAndAttack(topEnemy)
In the above example, topTnemy is passed to target. This means that in the main loop you use the variable called topEnemy but in your function you use a variable called target. They should have the same value as when calling the function we are doing something like target = topEnemy.

A Fine Mint

Objectives

  • Reinforce the idea of function
  • Use nothing but a sequence of functions in your main loop

Main Lesson
In the real world, we often divide a task into smaller tasks. This is how we do it in programming. First we divide the task into several functions and call them one by one in the main loop (even if there is no loop).
Then we go on to write/implement those functions.
This is what happens here. Make sure your students understand what is going on here because this will be a model of programming for all the advanced levels!

Leave it to the Cleaver

Objectives

  • Understand the idea of refactoring
  • Reinforcing the idea of argument-parameter match

Main Lesson
When enemies get close, use cleave attack. This is something we have done before, in Agrippa Defense. Here, we extract a big chunk of the original code from main loop and make it into a function called cleaveWhenClose(). This is called refactoring.
Also, notice we use a variable called target inside the function while using another, enemy, in the main loop.

Agrippa refactored

Objectives

  • More ideas on refactoring
    Main Lesson

In the last level we lump a lot of actions inside the function cleaveWhenClose(). How about we take some of it out and let it stay in the main loop?

Reflection question: how is this level different from the last, and the original Agrippa?

Agrippa Returned

Objectives

  • Further considerations on refactoring
  • Understand the return of a function

Main Lesson

There are endless ways to refactor your code! In this level you will see yet another way to chop up and rearrange the code so that it does exactly the same thing!
All functions we have seen so far do not return anything; they could take something in, but they don’t give something in return. Here we have an example of function taking in and giving back something at the same time.
The enemyInRange(enemy) function is a bit different. It returns a boolean value: True or False. If it is true, then we know the enemy is close. We can then use this return value as a conditional, just like we have used isReady, or enemy.

Friend and Foe

Objectives

  • Manipulating strings

Deja Brew

Objectives

  • Understand the idea of using loop to change value
  • Reinforce string manipulation

The Wizard’s Door, The Wizard’s Haunt, The Wizard’s Plane

Objective

  • Understand how to use arithmetic oeprators

Coincrumbs

Objectives

  • New method: hero.findNearestItem()
  • Understand the idea of property and how is it related to object and method
  • Know how to retrieve the position of an object and move accordingly

Main Lesson
This level introduces a new method, findNearestItem(). It returns an object (coin, gem, or potion) that has properties but not methods.
Each item is an object, which contains other pieces of information known as properties. Each item object (and each unit) has a pos property, which stands for its position. And each pos is itself an object, which has x and y properties that you can use with moveXY and buildXY.

Like method, a property is also associated with an object (as witnessed by the dot) but not parentheses.

White Rabbit

Objective

  • Reinforcing the use of item, position

Chameleons

Objective

  • Reinforcing the use of item, position

Salted Earth

Objective

  • Introducing another property: item.type

Spring Thunder

Objective

  • Introducing another property: item.value

Usual Day

Objective

  • Using both the object and its property in one conditional

Passing Through

Objective

  • Use != as part of the conditional

Useful Competitors

Objective

  • Enemy has type too!
  • Reinforce the kind of conditional construction in last level

Logical Path, Logical Circle, Logical Conclusion

Objectives

  • Use logical operators such as AND, OR, NOT

The following code belongs to Logical Path

The following code belongs to Logical Circle

The following code belongs to Logical Conclusion

Coinucopia

Objectives

  • New method: findFlag() returns a flag object; pickUpFlag(flag) takes an argument and picks the flag specified
  • Use flag to implement human input

Main Lesson

Your hero has a limited line of sight. So he/she cannot see coins very very far away, or blocked by walls. If that’s the case, you need to intervene by guiding your hero to where he/she can see.
A typical way of using flag is this:

Flag is the only input available in CodeCombat.
In order to use flags, you need to submit your code. Simply running the code will not give you the ability to use flag. As the level is running, The flag buttons will show up in the lower left corner. Start by click on the flag you wish to use. Then click where you want to deploy it.

Read the sample code in this level to understand how flags work, then press Submit and start placing flags where the coins are. You’ll have to be quick to get 20 gold in 40 seconds.

Copper coins are worth 1 gold, silver coins are worth 2 gold, and gold coins are worth 3 gold.

Tip: you don’t need to change the sample code.

Copper Meadows

Objective

  • Use flags in conjunction with other action commands

Main Lesson
Use flags to guide your hero to each meadow full of coins.

Tip: The meadows are randomized, so the layout will change each time.

Drop the Flag:

Objectives

  • Use flag in conjunction with other action commands

Main Lesson

It is important to realize that every object has a pos property, which allows us to retrieve its coordinates and then use them in methods such as buildXY or moveXY.

Mind the Trap

Objectives

  • Understand the idea of minimal execution unit
  • Integrate flag in nested-if and loop structures
  • Use elif in the place of else: if

Main Lesson

If you have an if immediately following else, you can contract them into one statement: elif

Some actions your hero takes will have exclusive command of the computer. When this happens, all other things will pause until the command is finished. MoveXY() is this way. attack() is also this way.

This level demonstrates this idea by having do an attack against an enemy that’s far away. You will see that your program stops responding to other commands (such as pickUpFlag) while your hero runs toward the enemy.

In this level, that means your hero will run straight intothe mines! (boom!)

To avoid this, you’ll need to use distanceTo and only engage in attacks if enemies are within 10 meters.

Use your flags to move close to any enemy you want to attack!

Rich Forager

Objectives

  • reinforce everything learned in the last level

Main Lesson
This level is very similar to the previous one.

End of Unit 1B Review

In this unit you have learned some computer science concepts (e.g., object and method; Boolean and arithmetic operations; parameter and argument) and the most essential programming techniques such as loops, conditionals.

While we promote a “concrete first” approach to programming, after you have gained enough exposure to concretized CS concepts it is still important to reinforce your learning with clear and concise explanation of key concepts. The following reference will help you understand some of the most abstract or tricky ideas in programming that has been largely implicit in your learning.

Identify common data types

Just like the computer, a programmer needs to be perfectly clear about the data type of everything in the code. If not, errors! The following algorithm helps you quickly indentify what you see…

  • text after a hashtag: comments

#this is a comment; you should do what I say

  • texts inside quotes: String

“this is a string” + “ and its value will always be the same”

  • text before a dot:object

hero, enemy, item, etc.

  • text after a dot:method or property.

hero.attack() is a method because of the parentheses

hero.health is a property because there is no parentheses

  • text with a pair of parentheses, but not preceded by a dot: function

pickUpCoin(); remember the python naming convention asks youto have every word, except the first, to have the first letter capitalized.

  • text that does belong to any of the above category: variable

In other programming languages, you need to declare a variable before start using it. In Python you simply need to assign some value to it, like this:

enemyIndex = 0

enemy = "Greg"

When to use variable?

In many cases, as you will see, using variable is an optional choice. Some of the early examples demonstrate this:

enemy = "Greg"

hero.attack(enemy)

Why not simply use: hero.attack("Greg")?

Similarly, instead of the following code:

distance = hero.distanceTo(enemy)

if distance < 5:

We might simply use:

if hero.distanceTo(enemy) < 5:

As a programmer, you need to exercise good judgement on when to use variable to make your code more readable and when to skip variable to make your code more compact. There is no fixed rule.

Indentation

Pay attention to indentation, as this is how we give structure to code in python. A language that has no hiearchial strcuture (such as BASIC) is terrible to follow. Some languages use special characters (Javascript uses curly braces; LISP uses parentheses) or scope markers (Pascal uses statements such as “being” and “end”). But python uses a fixed number of blank spaces (four to be precise) to form a structure of indentation.

  • Codes that have zero indentation is at the “main level” or “main loop” (because you often have a loop at this level). You need at least some code at this level to be qualified as a program
  • Codes that are equal level should have equal level of indentation. Pay close attention to if and else! They should always pair with right other part. This is especially important if you have multiple ifs or elses.
  • Codes belong to a statement need to have ONE more indentation: function def, loop, if statements all need to have their codes “tucked in”.

How to use function

  • You need to define it first by using the following format: def funcName():
  • You need to call it by having it somewhere in your code: funcName()
  • The definition needs to appear before first calling (but it can be after some codes in the main level)
  • Function definition should be on the main level (zero indentation)
  • You need to match arguments and parameters:a. argument is what we send into the function.

    b. parameter is what is used inside the function; it exists only within the function

    c. argument and parameter can be of the same name, but they will be treated differently

    d. to avoid confusion, the best practice is to have different names

  • Return value:a. in python, you use the return statement to explicitly assign a return value

    b. return statement also marks the end of the function execution. Anything that appear after the return statement will simply be ignored

  • Refactoring: wrap a chunk of code as a function so that you can use it multiple times and improve readability.

Conditional

A conditional is something that will be evaluated as True or False. A conditional can normally have three kinds of components:

  1. Variable of the Boolean type; Boolean constant; function or method that returns Boolean value
  2. Boolean operators such as and, or, not
  3. Boolean evaluation phrases such as A == B, A!=B, A > B, A < B, etc.

Notice that if is not part of the conditional; it is a statement. The conditional is the part that follows if and before the colon.

A conditional can also be used together with the while loop, like this:

while True: or while hero.gold < 80:

But what does if enemy: mean? Why is enemy a conditional?

So here goes the fourth kind of component that serves as conditional:

What counts as True What counts as False
An object that exists (enemy, item) ; a numbers that is not 0 ; a string that is not empty; an array that is not empty An object that doesn’t exist (enemy, item) ; number 0 (integer, float, etc.); an empty string; an empty array

Undefined vs None

  • “Undefined” means an object or function is being called without first defined.
  • “None” or “Null” means an object, which is also a variable, is empty. It’s value is NULL

Final-exam Sample Sheet

Name:

1. Who is who

Identify the DATA TYPE of following code snippets by filling what are applicable from the following choices (you may use more than one; every choice can be used multiple times)

OBJECT, METHOD, STATEMENT, CONDITIONAL, FUNCTION, VARIABLE,CONSTANT, PROPERTY, STRING, INTEGER, BOOLEAN, COMMENT

Code Fragment Data Type
friend.distanceTo()
hero
pickupCoin()
false
True
soldier.findNearestEnemy()
cleaveOrAttack(enemy)
item.pos.x
if rightEnemy:
“enemy”
ready
# if ready:
5
hero.pos.x > 3
soldier.health

2. Finding Bugs

What is wrong with the following code? Circle everything that are incorrect.

3. Coding from scratch

Write a function called heroAttack(enemy) that does the following:

  • Only attack when enemy is close enough (distance< 5); otherwise just tease
  • Use cleave when hero is ready; otherwise attack

Final-exam Answer

1. Who is who
Identify the DATA TYPE of following code snippets by filling what are applicable from the following choices (you may apply more than one; every choice can be used multiple times)
OBJECT, METHOD, STATEMENT, CONDITIONAL, FUNCTION, VARIABLE, CONSTANT, PROPERTY, STRING, INTEGER, BOOLEAN, COMMENT

Code Fragment Data Type
friend.distanceTo() Method
hero Object
pickupCoin() Function
false Variable
True Constant, Boolean
soldier.findNearestEnemy() Method
cleaveOrAttack(enemy) Function
item.pos.x Variable, Property
if rightEnemy: Statement
“enemy” String
ready Variable
# if ready: Comment
5 Integer
hero.pos.x > 3 Conditional, Boolean
soldier.health Property

2. Finding Bugs
What is wrong with the following code? Circle everything that are incorrect.

  1. Function naming convention: all words except the first need to capitalize first letter.
  2. Colon after def statement.
  3. Within the function, variables should following the parameter in the def statement.
  4. method calling need parentheses
  5. variable use should be consistent
  6. no statement between if and else
  7. use indentation to signify hiearchy

3. Coding from Scratch
Write a function called heroAttack(enemy) that does the following:

  • Only attack when enemy is close enough (distance < 5); otherwise tease
  • Use cleave when he/she is ready; otherwise attack​