Unit 2: Sarven Desert

Layout of Sarven Desert

Learning Outcomes

By the end of this unit students will be able to:

  • Access the property of an object and use it in other parts of the code
  • Write code that responds to human input
  • Use the result of a mathematical operation as an argument in a method without knowing the value of at least one of the operands
  • Access passed time and use it with in the code
  • Use variables to keep track of a changing value by repeatedly adding or subtracting
  • Make increments to variables to keep track how many times they go through a loop
  • Use the break command to terminate a loop
  • Create a while-loop that ends when a condition is met
  • Access a specific item in an array by using its index value
  • Loop through all the items in array by incrementing an index value
  • Create an algorithm to filter through a list

Timeframe

The Sarven desert will take around 10-15 hours of work for average students.

Concepts Reinforced

Property

Property is a special kind of variable that is associated with an object. But it differs from regular variables in one important aspect: most of the time we cannot directly manipulate these properties. We cannot, for instance, increase hero.health, or hero.gold. We also cannot assign values to hero.pos.x or hero.pos.y. If we could, everything would just be too easy!

If / elif /else

Programmingis all about handling various situations automatically. The main tool for doing different things based on the state of things are if and elseelif simply stands for else if. In order to understand how nested if-statement works, it is useful to draw a tree diagram indicating all the branches.

Input Handling

Programming is about doing automatically; but occassionaly it does want your input. Consider this as a robot waiting for further instructions. After your have given the instruction, the computer needs to go back to automatic behavior.

New Concepts

Conditional While Loops 

A while True loop is used to repeat actions without the need to repeat codes. But once you get inside a while True loop, you can never get out. Because what is True will always be True. Now, what about situations where you want to repeat only a while and get out? This is where conditional loop comes into place. It will start with a condition that is True. During the loop you need to make changes so that eventually this condition will become False.

Lists or Arrays

A list is a collection of indexed data. We need to know to use loops to access and filter through information stored on this list.

Break

Breakis a keyword that stops a loop when the computer sees it. The computer will stop the loop and run the code underneath the loop.

Iteration

Iteration means repeating.

Levels and their corresponding skills

Levels Programming concepts
the mighty sand yak ; oasis; sarven road MoveXY combined with hero.pos
basin stampede ; cross roads; thunderhooves Position comparison as conditional, buildXY
Fast and furry-ous; PET: event handler and parallel processing
cursed valley Enemy and item type
interception Find the place between two objects
Crux of the desert Position comparison as Boolean variable
Kithgard enchanter Make your own movement functions
operation killdeer ; medical attention Health check as conditional, return in functions
sarven sentry Flag induced actions (user input handling): move and build
Keeping time New method: time control (while-if-elif structure)
hoarding gold; book keeper; decoy drill New Control statement: break; while-if-if structure
Double cheek; desert combat; dust While loop with conditionals (and incrementals)
continuous alchemy New Control statement: continue; while-if-continue structure
dont rush be quiet ; zigzag and zoom Time, function and return value
Cubic minefield; desert delta; safety blanket Function that calculates; list index
sarven savior; bank raid; wandering souls; lurkers While index < len() structure
Teamwork; List index quote
Coordinated defense List index quote + len()> 0 loop; refresh array within loop
Recruiting queue Len() as conditional itself; refresh array within loop
Second gem Len(), index etc.
marauder Attack while health > 0
sarven shepherds; shine getter Integrative lesson: type and array index
mad maxer; sand snakes Find farthest or nearest object (the typical structure of max value iteration)
Brittle morale; diamond dozen Find strongest enemy or best valued coin
Chain of command; pet translator; PET: event speaker; event message;
alchemic power; Pet engineer PET: findNearestByType
Pet adjutant; dangerous key; olympic race PET: integrative lesson
Wishing well; gas attack; fair battle List iteration and sum
clash of clones Program From Scratch
Goalkeeper, sarven treasure, sarven siege Replayable and challenge level
The trials Challenge Level

Lesson Plans

The Mighty Sand Yak

Objectives

  • Understand how to move relatively to current position
  • Move in reaction to external circumstances

Main Lesson

From now on, you gain the ability to control your own position. You can move relative to where you were. This is the very first step of making your own game!

To accomplish that, you need to do three things:

  1. retrieve your curent position and store it in variables
  2. add or subtract from these position to get where you want to go
  3. now move to the new position indicated by the variables

Oasis

Main Lesson

This level reinforces what you did in the last one by making you do left and right dodgings.

Basin Stempede

Main Lesson

This level reinforces what you did in the last one by making you do up and down dodgings.

Sarven Road

Main Lesson

This level reinforces what you did in the last one by making you modify both your x and y positions.

Double Gaps

Main Lesson

This level reinforces what you did in the last one by putting the coordination changing inside functions.

Pay attention to something: it could refer both to an enemy or a coin!

Cross Roads

Main Lesson

In this level enemies will come from four main directions. Compare the x or y of enemy to those of the hero to find out where they come from.

Thunderhooves

Main Lesson

In this level yaks will come from top or bottom. You need to build your fences in relation to where the yak is (not where you are!). Also, during your spare time, try move to right until you reach the oasis.

Interception

Main Lesson

This level contains a very useful lesson which you can use later on in your battles.

How do you put yourself in between the enemy and the friend so you can protect the latter?

Hint: you need a special ring to be able to use the findFriends() method.

Crux of the Desert

Main Lesson

The idea is clear: you compare positions and then store your findings in a series of four variables that are highly readable. In your if-statements, make use of those variables to find out where you should build your traps. This level requires a lot of patience and work with details.

Tip: if something is not working, pay close attention to what happens on the screen to find out where you have made mistakes!

Operation “Killdeer”

Objective

  • Understand your health and how it works
  • Reinforce the idea of function returning Boolean values

Main Lesson

This level introduces two new properties health and maxHealth. Obviously, none of these can be directly changed by you. In addition, the maxHealth property is a fixed number that is only affected by armor and such. Your health, however, is a dynamic variable.

Medical Attention

Main Lesson

This level reinforces what you learned in Operation “Killdeer”.

Tip: You can survive this level using one while True loop containing just 4 commands !

Sarven Sentry

Objectives

  • Use multiple flags

Main Lesson

In this level, you’ll get to use different color flags to tell your hero to perform different tasks.

Watch the archers, they’ll let you know if an ogre or a sand yak is coming. Then you’ll place flags to build on the X mark near that archer.

If there’s a sand yak coming, you’ll build a “fence”, using flagGreen.pos.x and flagGreen.pos.y as the X and Y for buildXY.

If there’s an ogre coming, you’ll build a “fire-trap” using flagBlack.pos.x and flagBlack.pos.y as the X and Y for buildXY.

After building any of these flags, remember to use pickUpFlag to remove the flag.

Keeping Time

Objectives

  • Understand the concept of game time
  • Learn how to use time to sequence blocks of actions

Main Lesson

Your new wristwatch gives yet another valuable property: hero.now().

It tells you what time it is now, starting from the moment you hit Run or Submit.

If we know what time it is now, then we can use a conditional to determine the different time of the day and accordingly, different kind of actions.

For this level, the first 10 seconds should be devoted to fighting the ogres. After that, until it reaches 30 seconds, you should be collecting coins. Finally, at the third stage, you join the fight again!

Hint: If you’re having trouble surviving the final fight, have your hero retreat to safety when your health is low!

Hint:You may also want to avoid attacking if the enemy.type is “palisade”.

Hoarding Gold

Objectives

  • Use break to get out of the while True loop
  • Use a variable that keeps changing during the loop
  • Design a condition to trigger the break event

Main Lesson

It is nice to stay in the loop. But sometimes we need a break! In this level you learn how to do this.

When you break from a loop, it means the your program will skip the rest of the loop and jumps on to whatever code that comes immediately after your loop.

There are two things to know to make this work:

  1. You do need to stay in the loop for a while. So your loop should not go to the break on its first run. The way to do this is to put the break command inside a if-statement: the trigger.
  2. You need to be careful designing the conditional for that trigger: will it be triggered in the foreseeable future? If not you get endless loop!
  3. Therefore you need something that keeps changing during the loop and eventually meet the trigger: a trigger variable.

In our example the totalGold is such a trigger variable. Its value keeps changing by:

totalGold += coin.value

The trigger condition is:

if totalGold >= 25:

If there are coins for you to collect, and you indeed move to collect them, you will get out of the loop. If you misspelled one of the two so that the trigger event never happens, you will be stuck!

By the way, to tell Naria how much gold youhave, you can just say(totalGold), but if you want to get fancy, you can use the string concatenation operatorlike this:

hero.say ("I have collected ", totalGold, " gold!")

Book Keeper

Objective

  • Get used to the idea of dividing your program into several sections
  • Know what should go inside the loop and what not
  • By now students should have little problem writing several nested if-statements wrapped inside a loop—if this is not the case, need to reinforce this knowledge

Main Lesson

This level appears rather long. But once you divided it into three segments, it is not that complicated.

  1. the first stage is about fighting and keeping count. By the end of this stage (triggered by time) you go to Narnia and report your count.
  2. the second stage is about collecting gold. Pay attention, however, that you need to report the amount of gold you collect in this session. You hero may start with some gold. So if you report the amount of gold your hero has by the end of this stage, it will be incorrect. The key to take a snapshot of your hero’s gold when she starts. And then subtract from the final amount this snapshot value. This is an important programming technique!
  3. the third stage goes back to fighting. Notice the following structure:if enemy.health <=0:​ defeated += 1

    What happens if you don’t do this (meaning you simply increase your count when you see an enemy)?

Be careful not to nest the two ifs inside each while loop. For it will deactivate the trigger event.

Decoy Drill

Main Lesson

This level is similar to what you did in the last level, with only one difference: the increment of trigger variable is put inside a conditional. Pay attention that this may bring problem: if the condition is not met, your trigger variable will not change and the trigger event will never happen.

Double Cheek

Objective

  • Introducing while conditional loop

Main Lesson

This level introduces the while loop with conditional. Instead of using the break command inside the loop, here the trigger condition is shifted to where the loop is.

Here is how you would use it:

  1. Initialize your trigger variable: in this level it is defeatedOgres
  2. Set up a condition for the loop such as: while defeatedOgres < 6:
  3. Somewhere in your loop change the trigger variable towards the condition: defeatedOgres += 1

Reflection question: how would you modify the following code using break instead of conditional while?

Continuous Alchemy

Objective

  • Introduce a new statement: continue

Main Lesson

The continue statement is different from the break statement: it only skips the rest of the loop from the continue statement. This level shows you why do you need this. It implements the dazzlingly logic as shown in the following diagram.

Remember, in real world programming, things could get far more complicated than this!

Challenge question: how do we change the code so as to avoid using continue?

Dust

Main Lesson

This level reinforces the idea of conditional while loop introduced in Double Cheek.

Cubic Minfield

Objective

  • Using conditional loops inside functions
  • Understand the correlation between trigger condition and changes made to the trigger variable
  • Using functions with multiple arguments and return value

Main Lesson

This lesson bundles several things together at once so it is somewhat challenging for most students.

The idea is that you need to understand what is done for you in the mult(number, times) function and do a similar thing to the power(number, exponent) function:

Multiplication means adding a number for a certain times.

Exponent power means multiplying a number for a certain times (the exponent).

The example given shows a reversed way of changing trigger variable: instead of increasing it until a threshold it now decreases from the given parameter. The new threshold, therefore, needs to be zero. And you need to subtract 1 from the trigger variable.

Challenge question: how would you change the code so that you can still increase the trigger variable?

P.S. It uses direct index to an array, although this is not in the code where you are not supposed to temper.

Sarven Savior

Objectives

  • Introducing array/list
  • Understand what is index and how to use index to go through a list
  • Introducing the function len(list)

Main Lesson

Array is an important data type. It provides functionalities beyond the primitive data types. It basically is a group of similar items. The similarity is the type: the items are all of a same type! You can have a list of strings, or numbers, of boolean values, or of objects.

What is known as array is more complicated than list. Apart from list, an array can also be dictionary and tuple. But in the Desert all we need to know is the most simple form of array: list.

Now, we all understand what is a list. But the question is, how do we access items in a list?

To solve this problem, computer science uses a concept that already exists in the real world: index. Imagine an index as your index finger: you use it to point at a certain member of the list. If you want to point to a different member of the list, you move your finger. You can keep on doing this until you reach the end of the list.

Every memeber of the list has a builtin index value: it starts with zero.

Therefore listName[0] refers to the first member of the list.

Who is the last member? To know how to quote this we need to make use of the function len(). This function returns the length of your list. So if you have six items in your list, it returns 6.

Now, as the first item is indicated by index 0, the last item will be indicated by len()-1

This level shows you how to use a conditional while loop to go through every item in your list, a practice you will do numerous times in the coming levels! This is how you do it:

  1. Initialize index variable: friendIndex = 0
  2. Construct a loop with index variable and len(): while friendIndex < len(friendNames):
  3. In your loop, extract the item by using a variable to store the list member indicated by the current index: friendName = friendNames[friendIndex]
  4. increase the index variable by 1

Bank Raid

Objectives

  • Introducing new method: findEnemies()
  • Introducing new method: finditems()
  • Understand how to iterate through the array
  • Use two conditional loops inside one big main loop!

Main Lesson

Now that you have learned array, you are granted access to new method such as findEnemies() and findItems(). Instead of only getting the nearest enemy or item, now you have everything at your disposal!

More power comes at more responsibility though. It takes some careful planning to get to any particular enemy or item. But with some practice, you will get used to the process.

Remember, just like findNearestEnemy() you need to refresh your enemy list once you start killing them. Some of them will be dead and you don’t want to ask your hero to attack dead guys!

Wandering Souls

Main Lesson

This is level reinforces the previous one, only adding another while loop keeping attack the enemy until dead.

Teamwork

Main Lesson

This lesson mainly shows that you can refer to a list member without assigning it to a variable first.

Coordinated Defense

Main Lesson

This level shows you one way to accomplish a typical task: you have a list of enemies, how can I make sure that I have killed all of them?

Notice that we do not have a loop where we attack every enemy in the list. Instead we always attack the first enemy in the list. This is rather arbitrary and doesn’t always make sense (why? because it might be farther away than other enemies).

Challenge question: can you write different code to do the same thing?

Recruiting Queue

Main Lesson

This level is similar to previous one except for a small but useful detail: notice how we are using len() itself as the conditional. What does this mean? Also, what does the last line do?

Lurkers

Main Lesson

This level doesn’t introduce new knowledge, but it asks the students to complete part of the code that is previously written for them. This is an importance difference. As long as the code is written, most students don’t necessarily read them careful enough: they main concern is what they need to do to beat the level!

So for a typical complex algorith our pedagogical methodology consists of several steps:

  1. First, introduce the algorithm and ask the student to fill in the smallest detail.
  2. Then, repeat the algorithm in different settings and ask the student to fill in different details.
  3. Finally, test if students have indeed mastered the algorithm by presenting challenges where they need write code from scratch.

If we use Donald Norman’s terminology developed in his Psychology of Everyday Things, we can say that the learning cycle begins with knowledge in the world: we know how to do things because there are clues out there helping us; the cycle ends with knowledge in the head: we memorize all the steps so we can write it out on a blank sheet of paper.

Sarven Shepherd

Main Lesson

This is level is similar to Lurkers in that it asks the students to wrap a while loop around written code. However, the same task is more difficult here because there is another while True loop outside. A frequent mistake students will make is to make the two while loops on the same level. Therefore the program will get stuck in the first loop and never get out.

Also, it is important that the moveXY() command should be after (outside) your inside loop, but
inside the main loop.

Shine Getter

Main Lesson

Same idea here, only to replace enemies with coins. As indicated by the analogy, the value property of the coin works similar to the type property of enemy.

Mad Maxer

Objective

  • Introduce a new loop command: loop:
  • Understand how to iterate through a list and find one value that we need

Main Lesson

This level shows how to do a very important task: you need to loop through a list and find out the one that has the (longest, shortest, biggest, smallest) value of your choice. This is how you do it:

  1. Initialize three variables: the index variable, the threshold variable and the target object variable. In our case, the threshold variable is maxDistance; and the target object variable is farthest.
  2. Construct a loop where you go through every item in the list, with the help of index variable and len() function.
  3. Inside the loop, if the value in question (be it health, distance or other things) held by the current list item is better (could be bigger or smaller) than the threshold variable, then refill the threshold variable with that better value. Also, point the target object variable to the current item. This is done in line 16-18
  4. Increase your index and finish the loop. You now have your best value and target object!

Sand Snakes

Main Lesson

The algorithm introduced in Mad Maxer is important and difficult. Students need more levels to practice it.

Here the trick is that we need to set the initial value of nearestDistance to 9999, the highest number possible. Ask students why this is the case. What else do we need to change compared to last level?

Challenge question: how would one write code that collects the farthest coin?

Brittle Morale

Main Lesson

Yet another example of how you can use the “survival of the fittest” algorithm. We write it into a function this time, which is what we will be doing in the future!

Pay attention to this: what do you need to return?

Diamond Dozen

Main Lesson

This level is rather long. And it starts to resemble the kind of code you will be writing in the challenge levels. Notice you use two functions findMostHealth() and findBestItem() in your main loop to enhance the readability of your code. You also call another function valueOverDistance() from within the findBestItem() function. Most students will have some problem understanding how to do this. Therefore, ask them first write the code that finds the best value item, and then replace it with best value over distance item.

Wishing Well

Main Lesson

This level shows several important programming techniques—the students won’t necessarily notice them, so you need to highlight them:

  1. Use variables to store your string and number constants in the beginning of code: ask students what the advantage of doing this.
  2. Use a function to sum up a list: you can ask your students to do a similar task.
  3. item = hero.findNearest(hero.findItems()) is a comprehension. We do not need to formally introduce this concept here. But ask students to think about the pros and cons of doing it.
  4. Line 19-21 consists of a way to go through the list without using the index. Have you seen it before? How does it work?

Clash of Clones

Main Lesson

This is the level that will unlock the next world: Cloudrip Mountain. Although there is no set answer for the level, there are several considerations:

  1. You clone will have the same equipment, which means that you do not want to put on all your expensive equipments!
  2. Your clone doesn’t know how to use special abilities, although he has the same glove.
  3. If you find yourself dying too soon, keep a distance from the battle field!
  4. Don’t attack the sand-yak!
  5. Take out enemy longrangers first.
  6. There will be two waves of enemies: first wave consists of soldiers and archers; the second wave will have scouts, ogres and shamans. Plan your action accordingly if you care about the type.

The following code needs programmaticon book V.

A much simpler version, taking out all the summoning and commanding, still works:

The Trials

Main Lesson

This level is probably the most challenging in Sarven Desert. But it is definitely not “mega hard”. However, it is a good opportunity for you to see your student’s level of skills. If someone can figure out how to solve this by herself, it is a very good sign of mastery.

Here are some general ideas on solving this level.

  1. The level consists of a series of local battles. You start from left bottom corner. You need to go to all other three corners for local battles. Then you need to come in to the center of the map to fight the oracle of Zha.
  2. Each local battle has multiple waves: enemies will spawn but there will be intervals where no enemy is in sight. Your battle therefore should not be hinged on the presence of enemy.
  3. Collecting mushroom will regenerate full health for your hero. So the best strategy would be to finish all enemies in sight and then start collecting mushrooms.
  4. Each local battle is properly ended when you have defeated a special enemy: oasis-guardian. If you leave without fighting him, you cannot finish the level.

Generally speaking there are three ways to do this level, all three pertain to different ways to sequence the delimit the local battles.

  • You can use flags. This is the easiest way to solve the level. If a student presents this solution, advise her to try solving it without using flag for maximum learning.
  • You can use hero.now() and divide the whole compaign by how long does it take for each local battle. This should work theoretically although it is definitely not the best way.
  • You can set up trigger events so you would know when to proceed to the next battle. This is the “correct” way to solve the level.
  • Finally, if you have infinity glasses you will be able to see all the enemies on the map. This way you won’t need to use the flags at all and consider the whole map one local battle. But this will take more time to finish.

The flag option:

The autonoumous option:

End of Unit Review

Final Exam

Unit 3: Cloudrip Mountain (WIP)

Learning Outcome

Lesson Plan

Crag Tag

Objective

  • Introduce move() command
  • Demonstrate comprehension

Main Lesson

There are two kinds of moves. One moves until we are where we need to go; the other moves toward a given destination. In the following example:

moveXY (35, 40)

Hero.say (“nice view!”)

Your hero will say “nice view!” only once, after she has arrived her destination.

On the other hand, in the following code:

Your hero will say “nice view!” many times between her moves. Notice how the say() interrupt the flow of execution.

In fact, in the level Kithgard Enchanter, you can make your moveRight() and moveUp() commands using move().

Reflection Question: Why do we need two kinds of moves?

Slalom

Objective

  • Understand what is object literal and how is it constructed
  • Understand in what circumstances one cannot use moveXY()
  • Combine move() with conditional loops

Main Lesson

This level is not the first to introduce object literal, but it is the first to make it a learning objective. It is important to point out to students that move() command takes an object as argument. And they have already seen this object in use many times: it is in fact the pos property of any object, be it hero, enemy, or item. We need to stress the exact syntax of how to write this object, as it will be used many times in the future.

Leave a Reply