Skip to content

Instantly share code, notes, and snippets.

@a1ip
Last active June 6, 2021 05:58
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save a1ip/eb7939872dc85b5ddc2f to your computer and use it in GitHub Desktop.
Save a1ip/eb7939872dc85b5ddc2f to your computer and use it in GitHub Desktop.
CodeCombat Backwoods Forest Campaign solutions http://codecombat.com/play/forest
There was only one way the Kithgard Dungeon could end... in fire!
Use explosive charges to demolish the gates and escape the dungeon!
Basic Syntax, Arguments, Strings

Code for plan() method is here:

# Use your buildXY hammer to build two "fire-trap"s near the gate.
# They will detonate when you move back to a safe distance!
# Then, make a run for the forest!

@moveRight()
@moveRight()
@buildXY "fire-trap", 35, 35
@buildXY "fire-trap", 35, 30
@moveLeft()
loop
  @moveRight()
Protect the peasant village of Plainswood from the ogres.
Basic Syntax, Arguments, Strings

Code for plan() method is here:

# Build two fences to keep the villagers safe!
# Hover your mouse over the world to get X,Y coordinates.
@buildXY "fence", 40, 52
@buildXY "fence", 40, 20
Stay alive and navigate through the forest!
Basic Syntax, Arguments, Strings

Code for plan() method is here:

# Go to the end of the path and build a fence there.
# Use your moveXY(x, y) function.

@moveXY 36, 60
@moveXY 37, 13
#@buildXY "fence", 71, 25
@buildXY "fire-trap", 71, 25
@moveXY 71, 26
@moveXY 56, 17
@moveXY 73, 63
Use your best insults–ogres are thick-skinned.
Basic Syntax, Arguments, Strings, If Statements, Arithmetic

Code for plan() method is here:

# The commands below an if statement only run when the if’s condition is true.

if 2 + 2 is 4
  @say "Hey!"
if 2 + 3 is 5
  @say "Yes, you!"

# Change the condition here to make your hero say "Come at me!"
if 3 + 3 is 6  # ∆ Make this true.
  @say "Come at me!"

if 2 + 18 is 20  # ∆ Make this true.
  @say "Hasta la vista, baby!" # Add one more taunt to lure the ogre. Be creative!
Use if-statements to decide: do you want gems, or do you want death?
Basic Syntax, Arguments, If Statements, Arithmetic, Variables

Code for plan() method is here:

# The commands below an if statement only run when the if's condition is true.
# Fix all the if-statements to beat the level.

if 1 + 1 + 1 is 4  # ∆ Make this false.
  @moveXY 5, 15  # Move to the first mines.

if 2 + 2 is 4  # ∆ Make this true.
  @moveXY 15, 40  # Move to the first gem.

if 2 + 2 isnt 5  # ∆ Make this true.
  @moveXY 25, 15  # Move to the second gem.

# < means "is less than".
if 2 + 2 < 5  # ∆ Make this true.
  enemy = @findNearestEnemy()
  @attack enemy

if 2 < 1  # ∆ Make this false.
  @moveXY 40, 55

if not true  # ∆ Make this false.
  @moveXY 50, 10

if not false  # ∆ Make this true.
  @moveXY 55, 25
Defeat ogre patrols with new, selective targeting skills.
Basic Syntax, Arguments, Variables, If Statements

Code for plan() method is here:

# Remember that enemies may not yet exist.
loop
  enemy = @findNearestEnemy()
  # @say "Delete this when your loop isn't infinite."
  if enemy # If there is an enemy, attack it!
    @attack enemy
  else # Else, say something to pass the time.
    @say "I'm waiting for you, baby!"
loop:
enemy = hero.findNearestEnemy()
if(enemy):
hero.attack(enemy)
Defend a village from marauding munchkin mayhem.
Basic Syntax, Arguments, Loops, Variables, If Statements

Code for plan() method is here:

# Patrol the village entrances.
# If you find an enemy, attack it.
loop
  @moveXY 35, 34
  leftEnemy = @findNearestEnemy()
  if leftEnemy
    @attack leftEnemy
    @attack leftEnemy
  @moveXY 60, 31 # Now move to the right entrance.
  rightEnemy = @findNearestEnemy()
  if rightEnemy # Use "if" to attack if there is an enemy.
    @attack rightEnemy
    @attack rightEnemy
# Патрулируй входы в деревню.
# Если нашёл врага, атакуй его.
loop:
hero.moveXY(35, 34)
leftEnemy = shero.findNearestEnemy()
if leftEnemy:
hero.attack(leftEnemy)
hero.attack(leftEnemy)
hero.moveXY(60, 31) # Теперь иди к правому входу.
rightEnemy = hero.findNearestEnemy() # Find the rightEnemy.
# Используй "if" для атаки если это враг.
if rightEnemy:
hero.attack(rightEnemy)
hero.attack(rightEnemy)
Patrol the village entrances, but stay defensive.
Basic Syntax, Arguments, Variables, Loops, If Statements

Code for plan() method is here:

# Stay in the middle and defend!

loop
  # @say "Delete this when your loop isn't infinite."
  enemy = @findNearestEnemy()
  if enemy
    # Either attack the enemy...
    @attack enemy
    @attack enemy
  else
    @moveXY 40, 34 # ... or move back to your defensive position.
Recover stolen treasure from an ogre encampment.
Basic Syntax, Arguments, Strings, Variables, Loops, If Statements

Code for plan() method is here:

# If there is an enemy, attack it.
# Otherwise, attack the chest!

loop
  # Use if/else.
  enemy = @findNearestEnemy()
  if enemy
    @attack enemy
  else
    @attack "Chest"

  # @say "Delete this line when your loop is finite."
Use your new cleave ability to fend off munchkins.
Basic Syntax, Arguments, Strings, Variables, Loops, If Statements

Code for plan() method is here:

# Use your new "cleave" skill as often as you can.

@moveXY 23, 23
loop
  # @say "Delete this when your loop isn't infinite."
  enemy = @findNearestEnemy()
  if @isReady("cleave")
    @cleave enemy # Cleave the enemy!
  else
    @attack enemy # Else (if cleave isn't ready), do your normal attack.
Combine cleave and shield to endure an ogre onslaught.
Basic Syntax, Arguments, Strings, Variables, Loops, If Statements

Code for plan() method is here:

# Survive both waves by shielding and cleaving.
# When "cleave" is not ready, use your shield skill.
# You'll need at least 142 health to survive.

# Note: shield() may not work in CoffeeScript yet, so if it doesn't, try Python or more armor.

loop
  if enemy = @findNearestEnemy()
    if @isReady("cleave")
      @cleave enemy
    else
      @shield()
Stay close to Victor.
Basic Syntax, Arguments, Variables, Loops, If Statements

Code for plan() method is here:

loop
# @say "Delete this when your loop isn't infinite."
enemy = @findNearestEnemy()
distance = @distanceTo enemy
if distance < 10 #if distance < 10
  # Attack if they get too close to the peasant.
  @attack enemy
else # Else, stay close to the peasant! Use else.
  @moveXY 40, 38
Remain centered with nested if-statements.
Basic Syntax, Arguments, Variables, Loops, If Statements

Code for plan() method is here:

# You can put one if-statement within another if-statement.
# However, doing so can be tricky, so you have to pay close attention to how the if statements interact with each other.
# Make sure the indentation is correct!
# Use comments to describe your logic in plain language!
# It's helpful to start with one outer if/else, using comments as placeholders for the inner if/else, like so:
loop
  enemy = @findNearestEnemy()

  # If there is an enemy, then...
  if enemy
    # Create a distance variable with distanceTo.
    distance = @distanceTo(enemy)
    # If the enemy is less than 5 meters away, then attack()
    if distance < 5
      @attack enemy
    # Otherwise (the enemy is far away), then shield()
    else
      @shield()
    # @say "I should attack!"

  # Otherwise (there is no enemy...)
  else
    # ... then move back to the X.
    @moveXY 40, 34
# Вы можете вложить один оператор if в другой оператор if.
# Однако, используя эту хитрость, Вы должны быть внимательны к тому, как операторы if взаимодействуют друг с другом.
# Make sure the indentation is correct!
# Полезно начать с одного внешнего оператора if,
# используя комментарии в качестве "заполнителя" для внутреннего оператора if/else:
loop:
enemy = hero.findNearestEnemy()
# Если рядом есть враг, то...
if enemy:
# Создайте переменную для значения дистанции (с помощью DistanceTo)
distance = hero.distanceTo(enemy)
# Если до врага меньше 5 метров, то атаковать (attack)
if distance < 5:
hero.attack(enemy)
# В противном случае (если враг далеко), использовать щит (shield)
else:
hero.shield()
# Иначе (если нет врагов)
else:
# тогда двигаться обратно к Х
hero.moveXY(40, 34)
// Вы можете вложить один оператор if в другой оператор if.
// Однако, используя эту хитрость, Вы должны быть внимательны к тому, как операторы if взаимодействуют друг с другом.
// Полезно начать с одного внешнего оператора if,
// используя комментарии в качестве "заполнителя" для внутреннего оператора if/else:
loop {
var enemy = hero.findNearestEnemy();
// Если рядом есть враг, то...
if(enemy) {
// Создайте переменную для значения дистанции (с помощью DistanceTo)
var distance = hero.distanceTo(enemy);
// Если до врага меньше 5 метров, то атаковать (attack)
if (distance < 5) hero.attack(enemy);
// В противном случае (если враг далеко), использовать щит (shield)
else hero.shield();
// Иначе (если нет врагов)
} else {
// тогда двигаться обратно к Х
this.moveXY(40, 34);
}
}
Let the enemy close, then strike when the moment is right.
Basic Syntax, Arguments, Strings, Variables, Loops, If Statements

Code for plan() method is here:

loop
  enemy = @findNearestEnemy()
  if enemy
    # null  # Replace this with your own code.
    # Find the distance to the enemy with distanceTo.
    distance = @distanceTo(enemy)
    # If the distance is less than 5 meters...
    if distance < 5
      # ... if "cleave" is ready, cleave!
      if @isReady "cleave"
        @cleave enemy
      # ... else, just attack.
      else
        @attack enemy
        @attack enemy
  # @say "Remove this line once your loop is finite."
  else
    @say "So peaceful."
Start playing in real-time with input flags as you collect gold coins!
Input Handling

Code for plan() method is here:

# Press Submit when you are ready to place flags.
# Flag buttons appear in the lower left after pressing Submit.
loop
  flag = @findFlag()
  if flag
    @pickUpFlag flag
  else
    @say "Place a flag for me to go to."
This level exercises: if/else, object members, variables, flag placement, and collection.
Basic Syntax, Arguments, Variables, Loops, If Statements, Input Handling

Code for plan() method is here:

# Collect all the coins in each meadow.
# Use flags to move between meadows.
# Press Submit when you are ready to place flags.

loop
  flag = @findFlag()
  if flag
    # Pick up the flag.
    #@say "Delete this and pick up the flag instead."
    @pickUpFlag flag
  else
    # Automatically move to the nearest item you see.
    item = @findNearestItem()
    if item
      position = item.pos
      x = position.x
      y = position.y
      @moveXY x, y
    else
      @say "Place a flag for me to go to."
An army of ogres approaches. Use flags to help the defenders!
Basic Syntax, Arguments, Variables, Loops, If Statements, Input Handling

Code for plan() method is here:

# Use flags to join the battle or retreat.
# If you fail, press Submit again for new random enemies and try again!
# You'll want at least 300 health, if not more.
loop
  flag = @findFlag()
  enemy = @findNearestEnemy()
  if flag
    @pickUpFlag flag
  else if enemy
    distance = @distanceTo(enemy)
    if distance < 15 and @isReady('cleave')
      @cleave enemy
    else if distance < 5
      @attack enemy
This level exercises: flag position, object members.
Arguments, Strings, Variables, Loops, If Statements, Input Handling

Code for plan() method is here:

# Put flags where you want to build traps.
# When you're not building traps, pick up coins!

loop
  flag = @findFlag()
  if flag
    # How do we get fx and fy from the flag's pos?
    # (Look below at how to get x and y from items.)
    @buildXY "fire-trap", flag.pos.x, flag.pos.y
    @pickUpFlag flag
  else
    item = @findNearestItem()
    if item
      @moveXY item.pos.x, item.pos.y
    else
      @say "Place a flag for me to go to."
This level exercises: if/elif, collection, combat.
Arguments, Strings, Variables, Loops, If Statements, Input Handling

Code for plan() method is here:

# Use "if" and "else if" to handle any situation.
# Put it all together to defeat enemies and pick up coins!
# Make sure you bought great armor from the item shop! 400 health recommended.

loop
  # @say "Delete this when your loop isn't infinite."
  flag = @findFlag()
  enemy = @findNearestEnemy()
  item = @findNearestItem()
  if flag
    # What happens when I find a flag?
    @pickUpFlag flag
  else if enemy
    # What happens when I find an enemy?
    if @distanceTo(enemy) < 10 and @isReady('cleave')
      @cleave enemy
    else
      @attack enemy
  else if item
    # What happens when I find an item?
    @moveXY item.pos.x, item.pos.y
  else @say "Banzai!"
Gather gleaming gold from ogre-guarded groves in this player-created replayable level by Kevin Holland.
It gets harder (and more lucrative) each time you win! But if you lose, you must wait a day to resubmit.

Code for level 1 plan() method is here:

# Collect 100 gold from two or three groves.
# If you win, it gets harder (and more rewarding).
# If you lose, you must wait a day before you can resubmit.
# Remember, each submission gets a new random seed.
loop
  flag = @findFlag()
  enemy = @findNearestEnemy()
  item = @findNearestItem()
  if flag
    @pickUpFlag flag
  else if enemy
    if @distanceTo(enemy) < 10 and @isReady('cleave')
      @cleave enemy
    else
      @attack enemy
  else if item
    @moveXY item.pos.x, item.pos.y
  else @say "Banzai!"
// Collect 100 gold from two or three groves.
// If you win, it gets harder (and more rewarding).
// If you lose, you must wait a day before you can resubmit.
// Remember, each submission gets a new random seed.
loop {
var flag = hero.findFlag();
var enemy = hero.findNearest(hero.findEnemies());
var item = hero.findNearest(hero.findItems());
if (flag) {
hero.pickUpFlag(flag);
} else if (enemy) {
var enemyIndex = 0;
var enemies = hero.findEnemies();
var thrower = hero.findNearest(hero.findByType("thrower"));
if (thrower) {
enemy = thrower;
}
while (enemy.health > 0) {
hero.attack(enemy);
}
} else if (item) {
hero.move(item.pos);
}
}
The ogres are climbing the cliff to strike the town. Hold them off while the militia assembles!
Created by player Agathanar.
Basic Syntax, Arguments, Variables, Loops, If Statements, Input Handling

Code for plan() method is here:

# Ogres are climbing the cliffs!
# Protect the peasants long enough for the militia to assemble.
loop
  enemy = @findNearest(@findEnemies())
  flag = @findFlag()
  if flag
    @pickUpFlag(flag) # Pick up the flag.
  else if enemy
    if @distanceTo(enemy) < 10 and @isReady('cleave')
      @cleave enemy
    else
      @attack enemy # Else, attack!
  # Use flags to move into position, and cleave if ready.
  else     
    @say "Send me to the central peasant"
Stay alive for one minute in this tranquil forest. It gets harder (and more lucrative) each time you win! But if you lose, you must wait a day to resubmit.

Code for levels 1 and 2 plan() method is here:

# Stay alive for one minute.
# If you win, it gets harder (and more rewarding).
# If you lose, you must wait a day before you can resubmit.
# Remember, each submission gets a new random seed.
loop
  enemy = @findNearest(@findEnemies())
  thrower = @findNearest(@findByType("thrower"))
  if thrower
    enemy = thrower
  if enemy
    if @distanceTo(enemy) < 10 and @isReady('cleave')
      @cleave enemy
    else
      @attack enemy # Else, attack!
  else     
    @say "Banzai!"
// Stay alive for one minute.
// If you win, it gets harder (and more rewarding).
// If you lose, you must wait a day before you can resubmit.
// Remember, each submission gets a new random seed.
loop {
var flag = hero.findFlag();
var enemies = hero.findEnemies();
var enemy = hero.findNearest(enemies);
var thrower = hero.findNearest(hero.findByType("thrower"));
var goalsToCleave = 0;
var enemyIndex = 0;
if (flag) {
hero.pickUpFlag(flag);
}
while (enemyIndex < enemies.length) {
if (hero.distanceTo(enemies[enemyIndex]) < 10) {
goalsToCleave++;
}
enemyIndex++;
}
if (enemy) {
if (hero.isReady('cleave') && (goalsToCleave > 3)) {
hero.cleave(enemy);
} else {
if (thrower) {
enemy = thrower;
}
hero.attack(enemy);
}
}
}
// Stay alive for one minute.
// If you win, it gets harder (and more rewarding).
// If you lose, you must wait a day before you can resubmit.
// Remember, each submission gets a new random seed.
loop {
var flag = hero.findFlag();
var enemies = hero.findEnemies();
var enemy = hero.findNearest(enemies);
var thrower = hero.findNearest(hero.findByType("thrower"));
if (flag) {
hero.pickUpFlag(flag);
}
if (enemy) {
if (thrower) {
enemy = thrower;
}
hero.attack(enemy);
}
}
def moveTo(position, fast = True):
if(self.isReady("jump") and fast):
self.jumpTo(position)
else:
self.move(position)
summonTypes = ['paladin']
def summonTroops():
type = summonTypes[len(self.built)%len(summonTypes)]
if self.gold > self.costOf(type):
self.summon(type)
def commandPaladin(paladin):
enemy = paladin.findNearest(self.findEnemies())
if(paladin.canCast ("heal")):
target = None
if(self.health<self.maxHealth*0.6):
target = self
minHealth = 200
for friend in self.findFriends():
if friend.health < minHealth:
minHealth = friend.health
target = friend
if target:
self.command(paladin, "cast", "heal", target)
if enemy:
self.command(paladin, "attack", enemy)
else:
self.command(paladin, "move", self.pos)
def commandSoldier(soldier):
enemy = self.findNearest(self.findEnemies())
thrower = self.findNearest(self.findByType("thrower"))
if thrower:
enemy = thrower
if enemy:
self.command(soldier, "attack", enemy)
else:
self.command(soldier, "move", self.pos)
def commandTroops():
for friend in self.findFriends():
if friend.type == 'paladin':
commandPaladin(friend)
elif friend.type == 'soldier' or friend.type == 'archer':
commandSoldier(friend)
def attack(target):
#if(not target or self.distanceTo(target)>40):
# self.buildXY('caltrops', self.pos.x, self.pos.y)
#elif self.canCast("chain-lightning", target):
if self.canCast("chain-lightning", target) and self.distanceTo(target)<20:
self.cast("chain-lightning", target)
elif self.distanceTo(target)>10:
moveTo(target.pos)
elif self.isReady("bash"):
self.bash(enemy)
else:
self.attack(target)
loop:
summonTroops()
commandTroops()
enemy = self.findNearest(self.findEnemies())
#thrower = self.findNearest(self.findByType("thrower"))
#if thrower:
# enemy = thrower
if enemy:
attack(enemy)
# Оставайтесь живым одну минуту.
# Если вы победите, этот уровень станет сложнее (и более прибыльным)
# Если вы проиграете, вы должны подождать день, перед следующей попыткой.
# Помните, что каждый раз уровень генерируется по-разному.
enemy_types = {}
# ogres types
enemy_types['shaman'] = {'danger': 10, 'focus': 10}
enemy_types['warlock'] = {'danger': 10, 'focus': 10}
enemy_types['arrow-tower'] = {'danger': 10, 'focus': 10}
enemy_types['burl'] = {'danger': 10, 'focus': 5}
enemy_types['witch'] = {'danger': 8, 'focus': 10}
enemy_types['brawler'] = {'danger': 7, 'focus': 10}
enemy_types['ogre'] = {'danger': 5, 'focus': 10}
enemy_types['chieftain'] = {'danger': 6, 'focus': 10}
enemy_types['fangrider'] = {'danger': 4, 'focus': 22}
enemy_types['skeleton'] = {'danger': 5, 'focus': 22}
enemy_types['scout'] = {'danger': 4, 'focus': 22}
enemy_types['thrower'] = {'danger': 3, 'focus': 22}
enemy_types['munchkin'] = {'danger': 2, 'focus': 15}
if hero.team == 'humans':
team = 'humans'
else:
team = 'ogres'
def findTarget():
danger = 0
enemy_return = None
for type in enemy_types.keys():
if enemy_types[type] and enemy_types[type].danger > danger:
enemy = hero.findNearest(hero.findByType(type))
if enemy and enemy.team != team and hero.distanceTo(enemy) < enemy_types[type].focus:
enemy_return = enemy
danger = enemy_types[type].danger
if enemy_return is None:
enemy_return = hero.findNearest(hero.findEnemies())
return enemy_return
#summonTypes = ['soldier', 'archer', 'griffin-rider', 'archer', 'archer']
summonTypes = [ 'paladin', 'paladin', 'paladin', 'griffin-rider', 'griffin-rider']
def moveTo(position, fast=True):
if (hero.isReady("jump") and hero.distanceTo(position) > 10 and fast):
hero.jumpTo(position)
else:
hero.move(position)
def summonTroops():
type = summonTypes[len(hero.built) % len(summonTypes)]
if hero.gold > hero.costOf(type):
hero.summon(type)
def commandTroops():
for friend in hero.findFriends():
if friend.type == 'paladin':
CommandPaladin(friend)
elif friend.type == 'soldier' or friend.type == 'archer' or friend.type == 'griffin-rider':
CommandSoldier(friend)
elif friend.type == 'peasant':
CommandPeasant(friend)
def CommandSoldier(soldier):
hero.command(soldier, "defend", hero)
def CommandPeasant(soldier):
item = soldier.findNearestItem()
if item:
hero.command(soldier, "move", item.pos)
def CommandPaladin(paladin):
lowestFriend = lowestHealthFriend()
if (paladin.canCast("heal") and hero.health < hero.maxHealth / 5):
hero.command(paladin, "cast", "heal", self)
elif lowestFriend and lowestFriend.health < lowestFriend.maxHealth / 3:
hero.command(paladin, "cast", "heal", lowestFriend)
else:
hero.command(paladin, "defend", hero)
def lowestHealthFriend():
lowestHealth = 99999
lowestFriend = None
friends = hero.findFriends()
for friend in friends:
if friend.health < lowestHealth and friend.health < friend.maxHealth:
lowestHealth = friend.health
lowestFriend = friend
return lowestFriend
def attack(target):
if not target:
target = findTarget()
if target:
if (hero.distanceTo(target) > 20):
moveTo(target.pos)
elif hero.isReady("chain-lightning"):
hero.cast("chain-lightning", target)
elif hero.isReady("bash"):
hero.bash(target)
else:
hero.attack(target)
while True:
summonTroops()
commandTroops()
attack()
Unlock the desert world, if you are strong enough to win this epic battle!
Basic Syntax, Arguments, Variables, Loops, If Statements, Input Handling

Code for plan() method is here:

# Help your friends beat the minions that Thoktar sends against you.
# You'll need great equipment and strategy to win.
# Flags might help, but it's up to you–be creative!
loop
  flag = @findFlag()
  if flag
    @pickUpFlag(flag)
  enemy = @findNearest(@findEnemies())
  thrower = @findNearest(@findByType("thrower"))
  if thrower
    enemy = thrower
  if enemy
    if @distanceTo(enemy) < 10 and @isReady('cleave')
      @cleave enemy
    else
      @attack enemy # Else, attack!
  else     
    @say "Banzai!"
Horses have escaped from the farm. Tame all of the wild horses and return them.

Code for plan() method is here:

loop
  # How do you find the nearest friendly unit?
  # horse = ?
  horse = @findNearest(@findFriends())
  if horse
    x1 = horse.pos.x - 7
    x2 = horse.pos.x + 7
    if x1 >= 1
      # Move to the horse's y position but use x1 for the x position.
      @moveXY x1, horse.pos.y
    else if x2 <= 79
      # Move to the horse's y position but use x2 for the x position.
      @moveXY x2, horse.pos.y
    distance = @distanceTo(horse)
    if distance <= 10
      @say 'Whoa'
      # Move to the red x to return the horse to the farm.
      @moveXY 27, 54
      # Move back out into the pasture to begin looking for the next horse.
      @moveXY 55, 31
loop {
// How do you find the nearest friendly unit?
// horse = ?
var horse = hero.findNearest(hero.findFriends());
if (horse) {
var x1 = horse.pos.x - 7;
var x2 = horse.pos.x + 7;
if (x1 >= 1) {
// Move to the horse's y position but use x1 for the x position.
hero.moveXY(x1, horse.pos.y);
} else if (x2 <= 79) {
// Move to the horse's y position but use x2 for the x position.
hero.moveXY(x2, horse.pos.y);
}
var distance = hero.distanceTo(horse);
if (distance <= 10) {
hero.say("Whoa");
// Move to the red x to return the horse to the farm.
hero.moveXY(27, 54);
// Move back out into the pasture to begin looking for the next horse.
hero.moveXY(55, 31);
}
}
}
A large forest grove: great for practicing your Flower Art skills!
If Statements, Strings, Arithmetic, Object Literals, For Loops, Algorithms

Code for plan() method is here:

#
// This level is a place for making flower art.
// The real goal is to experiment and have fun!
// If you draw something with at least 1000 flowers, you will "succeed" at the level.
// Message Flower Box v1.0
// By Mini Gru
// Write your message with flowers.
// Set your text in "textToWrite" var and pick up a color for each character.
// Advance Config: Text size, text spacing, text area and number of cols and rows.
// Characters suported:
// A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z
// 1, 2, 3, 4, 5, 6, 7, 8, 9, 0
// " ", ".", ",", ?, !, -, +
// Characters in pogress:
// Ñ, Ç
// < , >, ;, :, =, /, *, _, ', "(", ")"
// BASIC CONFIG //
var textToWrite = " I LOVE MY JESUS! HE IS MY LORD! OOO"; // Text to write with flowers.
var charColors = ["pink", "blue", "random", "purple", "red"]; // Flowers Colors. Can be only one color or you can define a loop of colors. Colors: "random", "pink", "red", "blue", "purple", "yellow", or "white".
// ADV CONFIG //
// Text Size. Character width is calculated ([textSize] * [charWidthRatio]).
var textSize = 8; // Default: 8.
var charWidthRatio = 0.65; // Default: 0.65.
// Text Area. Calc the text area with coords corners "A" and "B"
var cornerA = {"x": 153, "y": 123}; // Default for Flower Grove Level: {"x": 153, "y": 123}.
var cornerB = {"x": 16, "y": 23}; // Default for Flower Grove Level: {"x": 16, "y": 23}.
// Number of Cols and Rows
var displayCols = 10; // Default: 10.
var displayRows = 3; // Default: 3.
// Character Spacing
var hSpacing = 0; // Default: 0.
var vSpacing = 5; // Default: 5.
// FUNCTIONS //
// drawCharacter function: Writes the [character] at given [X] and [Y] coords whith "n" size (height)
this.drawCharacter = function(character, x, y, size, color){
var vSize = size;
var hSize = size * charWidthRatio;
var vHalfSize = vSize / 2;
var hHalfSize = hSize / 2;
var vQuarterSize = vSize / 4;
var hQuarterSize = hSize / 4;
var angle = 0;
this.toggleFlowers(false);
this.setFlowerColor(color);
// "A" character
if(character == "A"){
this.moveXY(x - hHalfSize, y - vHalfSize);
this.toggleFlowers(true);
this.moveXY(x, y + vHalfSize);
this.moveXY(x + hHalfSize, y - vHalfSize);
this.toggleFlowers(false);
this.moveXY(x - (hHalfSize), y - (vHalfSize/2));
this.toggleFlowers(true);
this.moveXY(x + (hHalfSize), y - (vHalfSize/2));
}
// "B" character
else if(character == "B"){
this.moveXY(x - hHalfSize, y - vHalfSize);
this.toggleFlowers(true);
this.moveXY(x - hHalfSize, y + vHalfSize);
this.moveXY(x, y + vHalfSize);
angle = Math.PI / 2;
while (angle >= -(Math.PI/2)){
newX = x + ((hHalfSize/2) * Math.cos(angle));
newY = (y + (vHalfSize/2)) + ((vHalfSize/2) * Math.sin(angle));
this.moveXY(newX, newY);
angle -= 0.1;
}
this.moveXY(x - hHalfSize, y);
this.toggleFlowers(false);
this.moveXY(x, y);
this.toggleFlowers(true);
angle = Math.PI / 2;
while (angle >= -(Math.PI/2)){
newX = x + ((hHalfSize) * Math.cos(angle));
newY = (y - (vHalfSize/2)) + ((vHalfSize/2) * Math.sin(angle));
this.moveXY(newX, newY);
angle -= 0.1;
}
this.moveXY(x - hHalfSize, y - vHalfSize);
}
// "C" character
else if(character == "C"){
angle = Math.PI / 4;
this.moveXY(x + ((hHalfSize/2) * Math.cos(angle)), (y + (vHalfSize/2)) + ((vHalfSize/2) * Math.sin(angle)));
this.toggleFlowers(true);
while (angle <= ((3 * Math.PI)/2) + (Math.PI/4) ){
newX = x + ((hHalfSize) * Math.cos(angle));
newY = y + ((vHalfSize) * Math.sin(angle));
this.moveXY(newX, newY);
angle += 0.1;
}
}
// "D" character
else if(character == "D"){
this.moveXY(x - hHalfSize, y - vHalfSize);
this.toggleFlowers(true);
this.moveXY(x - hHalfSize, y + vHalfSize);
this.moveXY(x, y + vHalfSize);
angle = Math.PI / 2;
while (angle >= -(Math.PI/2)){
newX = x + ((hHalfSize) * Math.cos(angle));
newY = y + ((vHalfSize) * Math.sin(angle));
this.moveXY(newX, newY);
angle -= 0.1;
}
this.moveXY(x - hHalfSize, y - vHalfSize);
}
// "E" character
else if(character == "E"){
this.moveXY(x - hHalfSize, y - vHalfSize);
this.toggleFlowers(true);
this.moveXY(x - hHalfSize, y + vHalfSize);
this.moveXY(x + hHalfSize, y + vHalfSize);
this.toggleFlowers(false);
this.moveXY(x - hHalfSize, y);
this.toggleFlowers(true);
this.moveXY(x, y);
this.toggleFlowers(false);
this.moveXY(x - hHalfSize, y - vHalfSize);
this.toggleFlowers(true);
this.moveXY(x + hHalfSize, y - vHalfSize);
}
// "F" character
else if(character == "F"){
this.moveXY(x - hHalfSize, y - vHalfSize);
this.toggleFlowers(true);
this.moveXY(x - hHalfSize, y + vHalfSize);
this.moveXY(x + hHalfSize, y + vHalfSize);
this.toggleFlowers(false);
this.moveXY(x - hHalfSize, y);
this.toggleFlowers(true);
this.moveXY(x, y);
}
// "G" character
else if(character == "G"){
angle = Math.PI / 2;
this.moveXY(x + hHalfSize, y + vHalfSize);
this.toggleFlowers(true);
this.moveXY(x, y + vHalfSize);
while (angle <= 3 * Math.PI / 2){
var newX = x + (hHalfSize * Math.cos(angle));
var newY = y + (vHalfSize * Math.sin(angle));
this.moveXY(newX, newY);
angle += 0.2;
}
this.moveXY(x + hHalfSize, y - vHalfSize);
this.moveXY(x + hHalfSize, y);
this.moveXY(x, y);
}
// "H" character
else if(character == "H"){
this.moveXY(x - hHalfSize, y + vHalfSize);
this.toggleFlowers(true);
this.moveXY(x - hHalfSize, y - vHalfSize);
this.toggleFlowers(false);
this.moveXY(x - hHalfSize, y);
this.toggleFlowers(true);
this.moveXY(x + hHalfSize, y);
this.toggleFlowers(false);
this.moveXY(x + hHalfSize, y + vHalfSize);
this.toggleFlowers(true);
this.moveXY(x + hHalfSize, y - vHalfSize);
}
// "I" character
else if(character == "I"){
this.moveXY(x - hQuarterSize, y - vHalfSize);
this.toggleFlowers(true);
this.moveXY(x + hQuarterSize, y - vHalfSize);
this.toggleFlowers(false);
this.moveXY(x, y - vHalfSize);
this.toggleFlowers(true);
this.moveXY(x, y + vHalfSize);
this.toggleFlowers(false);
this.moveXY(x - hQuarterSize, y + vHalfSize);
this.toggleFlowers(true);
this.moveXY(x + hQuarterSize, y + vHalfSize);
}
// "J" character
else if(character == "J"){
this.moveXY(x - hHalfSize, y);
angle = Math.PI;
this.moveXY(x + (hHalfSize * Math.cos(angle)), y + (vHalfSize * Math.sin(angle)));
this.toggleFlowers(true);
while (angle <= 2 * Math.PI ){
newX = x + ((hHalfSize) * Math.cos(angle));
newY = y + ((vHalfSize) * Math.sin(angle));
this.moveXY(newX, newY);
angle += 0.1;
}
this.moveXY(x + hHalfSize, y + vHalfSize);
}
// "K" character
else if(character == "K"){
this.moveXY(x - hHalfSize, y - vHalfSize);
this.toggleFlowers(true);
this.moveXY(x - hHalfSize, y + vHalfSize);
this.toggleFlowers(false);
this.moveXY(x - hHalfSize, y);
this.toggleFlowers(true);
this.moveXY(x + hHalfSize, y + vHalfSize);
this.toggleFlowers(false);
this.moveXY(x - hHalfSize, y);
this.toggleFlowers(true);
this.moveXY(x + hHalfSize, y - vHalfSize);
}
// "L" character
else if(character == "L"){
this.moveXY(x - hHalfSize, y + vHalfSize);
this.toggleFlowers(true);
this.moveXY(x - hHalfSize, y - vHalfSize);
this.moveXY(x + hHalfSize, y - vHalfSize);
}
// "M" character
else if(character == "M"){
this.moveXY(x - hHalfSize, y - vHalfSize);
this.toggleFlowers(true);
this.moveXY(x - hHalfSize, y + vHalfSize);
this.moveXY(x, y);
this.moveXY(x + hHalfSize, y + vHalfSize);
this.moveXY(x + hHalfSize, y - vHalfSize);
}
// "N" character
else if(character == "N"){
this.moveXY(x - hHalfSize, y - vHalfSize);
this.toggleFlowers(true);
this.moveXY(x - hHalfSize, y + vHalfSize);
this.moveXY(x + hHalfSize, y - vHalfSize);
this.moveXY(x + hHalfSize, y + vHalfSize);
}
// "O" character
else if(character == "O"){
angle = 0;
this.moveXY(x + ((hHalfSize) * Math.cos(angle)), y + ((vHalfSize) * Math.sin(angle)));
this.toggleFlowers(true);
while (angle <= (2 * Math.PI)){
newX = x + ((hHalfSize) * Math.cos(angle));
newY = y + ((vHalfSize) * Math.sin(angle));
this.moveXY(newX, newY);
angle += 0.1;
}
}
// "P" character
else if(character == "P"){
this.moveXY(x - hHalfSize, y - vHalfSize);
this.toggleFlowers(true);
this.moveXY(x - hHalfSize, y + vHalfSize);
this.moveXY(x, y + vHalfSize);
angle = Math.PI / 2;
while (angle >= -(Math.PI/2)){
newX = x + ((hHalfSize) * Math.cos(angle));
newY = y + (vHalfSize/2) + ((vHalfSize/2) * Math.sin(angle));
this.moveXY(newX, newY);
angle -= 0.1;
}
this.moveXY(x - hHalfSize, y);
}
// "Q" character
else if(character == "Q"){
angle = 0;
this.moveXY(x + ((hHalfSize) * Math.cos(angle)), y + ((vHalfSize) * Math.sin(angle)));
this.toggleFlowers(true);
while (angle <= (2 * Math.PI)){
newX = x + ((hHalfSize) * Math.cos(angle));
newY = y + ((vHalfSize) * Math.sin(angle));
this.moveXY(newX, newY);
angle += 0.1;
}
this.toggleFlowers(false);
this.moveXY(x + hQuarterSize, y - vQuarterSize);
this.toggleFlowers(true);
this.moveXY(x + hHalfSize, y - vHalfSize);
}
// "R" character
else if(character == "R"){
this.moveXY(x - hHalfSize, y - vHalfSize);
this.toggleFlowers(true);
this.moveXY(x - hHalfSize, y + vHalfSize);
this.moveXY(x, y + vHalfSize);
angle = Math.PI / 2;
while (angle >= -(Math.PI/2)){
newX = x + ((hHalfSize) * Math.cos(angle));
newY = y + (vHalfSize/2) + ((vHalfSize/2) * Math.sin(angle));
this.moveXY(newX, newY);
angle -= 0.1;
}
this.moveXY(x - hHalfSize, y);
this.toggleFlowers(false);
this.moveXY(x, y);
this.toggleFlowers(true);
this.moveXY(x + hHalfSize, y - vHalfSize);
}
// "S" character
else if(character == "S"){
angle = 0;
this.moveXY(x + ((hHalfSize) * Math.cos(angle)), y + (vHalfSize/2) + ((vHalfSize/2) * Math.sin(angle)));
this.toggleFlowers(true);
while (angle <= (3 * Math.PI)/2){
newX = x + ((hHalfSize) * Math.cos(angle));
newY = y + (vHalfSize/2) + ((vHalfSize/2) * Math.sin(angle));
this.moveXY(newX, newY);
angle += 0.1;
}
angle = Math.PI / 2;
while (angle >= -(Math.PI)){
newX = x + ((hHalfSize) * Math.cos(angle));
newY = y - (vHalfSize/2) + ((vHalfSize/2) * Math.sin(angle));
this.moveXY(newX, newY);
angle -= 0.1;
}
}
// "T" character
else if(character == "T"){
this.moveXY(x - hHalfSize, y + vHalfSize);
this.toggleFlowers(true);
this.moveXY(x + hHalfSize, y + vHalfSize);
this.toggleFlowers(false);
this.moveXY(x, y + vHalfSize);
this.toggleFlowers(true);
this.moveXY(x, y - vHalfSize);
}
// "U" character
else if(character == "U"){
this.moveXY(x - hHalfSize, y + vHalfSize);
this.toggleFlowers(true);
this.moveXY(x - hHalfSize, y - (vHalfSize/2));
angle = Math.PI;
while (angle <= 2 * Math.PI){
newX = x + (hHalfSize * Math.cos(angle));
newY = (y - (vHalfSize/2)) + (vHalfSize/2 * Math.sin(angle));
this.moveXY(newX, newY);
angle += 0.2;
}
this.moveXY(x + hHalfSize , y + vHalfSize);
}
// "V" character
else if(character == "V"){
this.moveXY(x - hHalfSize, y + vHalfSize);
this.toggleFlowers(true);
this.moveXY(x, y - vHalfSize);
this.moveXY(x + hHalfSize, y + vHalfSize);
}
// "W" character
else if(character == "W"){
this.moveXY(x - hHalfSize, y + vHalfSize);
this.toggleFlowers(true);
this.moveXY(x - hQuarterSize, y - vHalfSize);
this.moveXY(x, y);
this.moveXY(x + hQuarterSize, y - vHalfSize);
this.moveXY(x + hHalfSize, y + vHalfSize);
}
// "X" character
else if(character == "X"){
this.moveXY(x - hHalfSize, y - vHalfSize);
this.toggleFlowers(true);
this.moveXY(x + hHalfSize, y + vHalfSize);
this.toggleFlowers(false);
this.moveXY(x - hHalfSize, y + vHalfSize);
this.toggleFlowers(true);
this.moveXY(x + hHalfSize, y - vHalfSize);
}
// "Y" character
else if(character == "Y"){
this.moveXY(x - hHalfSize, y + vHalfSize);
this.toggleFlowers(true);
this.moveXY(x, y);
this.moveXY(x + hHalfSize, y + vHalfSize);
this.toggleFlowers(false);
this.moveXY(x, y);
this.toggleFlowers(true);
this.moveXY(x, y - vHalfSize);
}
// "Z" character
else if(character == "Z"){
this.moveXY(x - hHalfSize, y + vHalfSize);
this.toggleFlowers(true);
this.moveXY(x + hHalfSize, y + vHalfSize);
this.moveXY(x - hHalfSize, y - vHalfSize);
this.moveXY(x + hHalfSize, y - vHalfSize);
}
// "1" character
else if(character == "1"){
this.moveXY(x - hHalfSize, y);
this.toggleFlowers(true);
this.moveXY(x, y + vHalfSize);
this.moveXY(x, y - vHalfSize);
}
// "2" character
else if(character == "2"){
angle = Math.PI;
this.moveXY(x + ((hHalfSize) * Math.cos(angle)), y + (vHalfSize/2) + ((vHalfSize/2) * Math.sin(angle)));
this.toggleFlowers(true);
while (angle >= 0){
newX = x + ((hHalfSize) * Math.cos(angle));
newY = y + (vHalfSize/2) + ((vHalfSize/2) * Math.sin(angle));
this.moveXY(newX, newY);
angle -= 0.1;
}
this.moveXY(x - hHalfSize, y - vHalfSize);
this.moveXY(x + hHalfSize, y - vHalfSize);
}
// "3" character
else if(character == "3"){
angle = Math.PI;
this.moveXY(x + ((hHalfSize) * Math.cos(angle)), y + (vHalfSize/2) + ((vHalfSize/2) * Math.sin(angle)));
this.toggleFlowers(true);
while (angle >= -(Math.PI/2)){
newX = x + ((hHalfSize) * Math.cos(angle));
newY = y + (vHalfSize/2) + ((vHalfSize/2) * Math.sin(angle));
this.moveXY(newX, newY);
angle -= 0.1;
}
angle = Math.PI/2;
while (angle >= -(Math.PI)){
newX = x + ((hHalfSize) * Math.cos(angle));
newY = y - (vHalfSize/2) + ((vHalfSize/2) * Math.sin(angle));
this.moveXY(newX, newY);
angle -= 0.1;
}
}
// "4" character
else if(character == "4"){
this.moveXY(x + hQuarterSize, y - vHalfSize);
this.toggleFlowers(true);
this.moveXY(x + hQuarterSize, y + vHalfSize);
this.moveXY(x - hHalfSize, y - vQuarterSize/2);
this.moveXY(x + hHalfSize, y - vQuarterSize/2);
}
// "5" character
else if(character == "5"){
this.moveXY(x + hHalfSize, y + vHalfSize);
this.toggleFlowers(true);
this.moveXY(x - hHalfSize, y + vHalfSize);
this.moveXY(x - hHalfSize, y + (vQuarterSize/2));
this.moveXY(x, y + (vQuarterSize/2));
angle = Math.PI / 2;
while (angle >= -(Math.PI)){
newX = x + ((hHalfSize) * Math.cos(angle));
newY = y - (vQuarterSize - (vQuarterSize/4)) + ((vQuarterSize + (vQuarterSize/4)) * Math.sin(angle));
this.moveXY(newX, newY);
angle -= 0.1;
}
}
// "6" character
else if(character == "6"){
this.moveXY(x - hHalfSize, y - vQuarterSize);
this.toggleFlowers(true);
angle = Math.PI;
while (angle >= -(Math.PI)){
newX = x + ((hHalfSize) * Math.cos(angle));
newY = y - (vHalfSize/2) + ((vHalfSize/2) * Math.sin(angle));
this.moveXY(newX, newY);
angle -= 0.1;
}
this.moveXY(x - hHalfSize, y + vQuarterSize);
angle = Math.PI;
while (angle >= 0){
newX = x + ((hHalfSize) * Math.cos(angle));
newY = y + (vHalfSize/2) + ((vHalfSize/2) * Math.sin(angle));
this.moveXY(newX, newY);
angle -= 0.1;
}
}
// "7" character
else if(character == "7"){
this.moveXY(x - hHalfSize, y + vHalfSize);
this.toggleFlowers(true);
this.moveXY(x + hHalfSize, y + vHalfSize);
this.moveXY(x, y - vHalfSize);
}
// "8" character
else if(character == "8"){
angle = -(Math.PI/2);
this.moveXY(x, y);
this.toggleFlowers(true);
while (angle <= (3*Math.PI)/2){
newX = x + ((hQuarterSize + hQuarterSize/2) * Math.cos(angle));
newY = y + (vQuarterSize) + ((vQuarterSize) * Math.sin(angle));
this.moveXY(newX, newY);
angle += 0.1;
}
angle = Math.PI/2;
while (angle <= (2*Math.PI)+(Math.PI/2)){
newX = x + ((hHalfSize) * Math.cos(angle));
newY = y - (vQuarterSize) + ((vQuarterSize) * Math.sin(angle));
this.moveXY(newX, newY);
angle += 0.1;
}
}
// "9" character
else if(character == "9"){
this.moveXY(x + hHalfSize, y + vQuarterSize);
this.toggleFlowers(true);
angle = 0;
while (angle <= 2*Math.PI){
newX = x + ((hHalfSize) * Math.cos(angle));
newY = y + (vQuarterSize) + ((vQuarterSize) * Math.sin(angle));
this.moveXY(newX, newY);
angle += 0.1;
}
this.moveXY(x + hHalfSize, y - vQuarterSize);
angle = 0;
while (angle >= -(Math.PI)){
newX = x + ((hHalfSize) * Math.cos(angle));
newY = y - (vQuarterSize) + ((vQuarterSize) * Math.sin(angle));
this.moveXY(newX, newY);
angle -= 0.1;
}
}
// "0" character
else if(character == "0"){
angle = 0;
this.moveXY(x + ((hHalfSize) * Math.cos(angle)), y + ((vHalfSize) * Math.sin(angle)));
this.toggleFlowers(true);
while (angle <= (2 * Math.PI)){
newX = x + ((hHalfSize) * Math.cos(angle));
newY = y + ((vHalfSize) * Math.sin(angle));
this.moveXY(newX, newY);
angle += 0.1;
}
angle = (Math.PI/4);
this.moveXY(x + ((hHalfSize) * Math.cos(angle)), y + ((vHalfSize) * Math.sin(angle)));
angle = (Math.PI/4)+(Math.PI);
this.moveXY(x + ((hHalfSize) * Math.cos(angle)), y + ((vHalfSize) * Math.sin(angle)));
}
// "+" character
else if(character == "+"){
this.moveXY(x - vQuarterSize, y);
this.toggleFlowers(true);
this.moveXY(x + vQuarterSize, y);
this.toggleFlowers(false);
this.moveXY(x, y + vQuarterSize);
this.toggleFlowers(true);
this.moveXY(x, y - vQuarterSize);
}
// "-" character
else if(character == "-"){
this.moveXY(x - vQuarterSize, y);
this.toggleFlowers(true);
this.moveXY(x + vQuarterSize, y);
}
// "?" character
else if(character == "?"){
this.moveXY(x - hHalfSize, y + vQuarterSize);
this.toggleFlowers(true);
angle = Math.PI;
while(angle >= -(Math.PI/2)){
newX = x + ((hHalfSize) * Math.cos(angle));
newY = y + (vQuarterSize) + ((vQuarterSize) * Math.sin(angle));
this.moveXY(newX, newY);
angle -= 0.1;
}
this.moveXY(x, y - vQuarterSize);
this.toggleFlowers(false);
this.moveXY(x, y - (vQuarterSize + vQuarterSize/2));
this.toggleFlowers(true);
this.moveXY(x, y - vHalfSize);
}
// "!" character
else if(character == "!"){
this.moveXY(x, y + vHalfSize);
this.toggleFlowers(true);
this.moveXY(x, y - vQuarterSize);
this.toggleFlowers(false);
this.moveXY(x, y - (vQuarterSize + vQuarterSize/2));
this.toggleFlowers(true);
this.moveXY(x, y - vHalfSize);
}
// "." character
else if(character == "."){
this.moveXY(x, y - vHalfSize);
this.toggleFlowers(true);
angle = -(Math.PI/2);
while(angle <= (3*Math.PI/2)){
newX = x + ((vQuarterSize/4) * Math.cos(angle));
newY = y - (vHalfSize - vQuarterSize/4) + ((vQuarterSize/4) * Math.sin(angle));
this.moveXY(newX, newY);
angle += 0.1;
}
}
// "," character
else if(character == ","){
angle = Math.PI/2;
this.moveXY(x, y - (vQuarterSize + vQuarterSize/4))
this.toggleFlowers(true);
while(angle <= (2*Math.PI) + (Math.PI/2)){
newX = x + ((vQuarterSize/4) * Math.cos(angle));
newY = y - (vQuarterSize + vQuarterSize/4) + ((vQuarterSize/4) * Math.sin(angle));
this.moveXY(newX, newY);
angle += 0.1;
}
angle = Math.PI/2;
while(angle >= -(Math.PI/2)){
newX = x + ((vQuarterSize/4) * Math.cos(angle));
newY = y - (vQuarterSize + vQuarterSize/2) + ((vQuarterSize/2) * Math.sin(angle));
this.moveXY(newX, newY);
angle -= 0.1;
}
}
else {
this.say("ERROR, I CAN'T WRITE THAT CHARACTER!");
}
this.toggleFlowers(false);
};
this.drawHeart = function(x,y,size) {
this.setFlowerColor("red");
var angle = 0;
this.toggleFlowers(false);
while (angle <= Math.PI * 1) {
var newX = x + size + (size * Math.cos(angle));
var newY = y + size + (size * Math.sin(angle));
this.moveXY(newX, newY);
this.toggleFlowers(true);
angle += 0.2;
}
angle = 0;
while (angle <= Math.PI * 1) {
newX = x - size + (size * Math.cos(angle));
newY = y + size + (size * Math.sin(angle));
this.moveXY(newX, newY);
this.toggleFlowers(true);
angle += 0.2;
}
this.moveXY(x, y - size * 2);
this.moveXY(x + size*2, y + size + (size * Math.sin(angle)));
this.toggleFlowers(false);
};
// printText function: Splits the text into an array, and prints each character.
this.printText = function(text){
var splTxt = text.split("");
for(var i=0;i<splTxt.length;i++){
var charToDraw = splTxt[i];
// If character position x it's greater than the space calculated, go to the next row and set initial position for x.
if(charPosX > ((firstCharPosX) + (textSize*(displayCols-1)))){
charPosY -= (textSize + vSpacing);
charPosX = firstCharPosX;
}
// If it is a space " ", increment char x position and continue.
if(charToDraw == " "){
charPosX += textSize;
continue;
} else {
// drawCharacter Function, givin the character to draw, the XY postion, and text size.
var charColor = charColors[i % charColors.length];
this.drawCharacter(charToDraw, charPosX, charPosY, textSize, charColor);
}
charPosX += textSize;
}
this.moveXY(charPosX, charPosY);
};
// Text Area Definition //
if(cornerA.x > cornerB.x){
var maxWidth = cornerA.x - cornerB.x;
} else {
maxWidth = cornerB.x - cornerA.x;
}
if(cornerA.y > cornerB.y){
var maxHeight = cornerA.y - cornerB.y;
} else {
maxHeight = cornerB.y - cornerA.y;
}
var widthNeeded = (textSize*displayCols)+(hSpacing*(displayCols-1));
var heightNeeded = (textSize*displayRows)+(vSpacing*(displayRows-1));
// VERIFICATION //
var errorMsg = [];
var charError = false;
var sizeError = false;
var colorError = false;
var validated = false;
var charList = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", " ", "1", "2", "3", "4", "5", "6", "7", "8", "9", "0", "+", "-", "?", "!", ".", ","];
var colorList = ["random", "pink", "red", "blue", "purple", "yellow", "white"]
var splitText = textToWrite.split("");
// Character verification
for(var k=0;k<splitText.length;k++){
if(charList.indexOf(splitText[k]) == -1){
errorMsg.push("ERROR, I can't write the character: " + splitText[k]);
charError = true;
}
}
// Color verification
for(var c=0;c<charColors.length;c++){
if(colorList.indexOf(charColors[c]) == -1){
errorMsg.push("ERROR, color " + charColors[c] + " dosn't exist. Pick up another color.");
colorError = true;
}
}
// Width and Height verification
if(widthNeeded > maxWidth){
errorMsg.push("ERROR, the calculated width needed is greater than text area. Change the text size or total cols.");
sizeError = true;
}
if(heightNeeded > maxHeight){
errorMsg.push("ERROR, the calculated height needed is greater than text area. Change the text size or total rows.");
sizeError = true;
}
// Validate if there is no error
if(!charError && !sizeError && !colorError){
validated = true;
var centerDisplayX = cornerB.x + (maxWidth/2);
var centerDisplayY = cornerB.y + (maxHeight/2);
var firstCharPosX = centerDisplayX - ((widthNeeded/2)-((textSize * charWidthRatio ) /2));
var firstCharPosY = centerDisplayY + ((heightNeeded/2) - (textSize/2));
var charPosX = firstCharPosX;
var charPosY = firstCharPosY;
}
// PRINT TEXT //
// If text is validated, print text.
if(validated){
this.printText(textToWrite);
} else {
this.say("We've got problems, my lord:");
for(var m=0;m<errorMsg.length;m++){
this.say(errorMsg[m]);
this.wait(1);
}
}
this.say("Finish, my lord.");
// You MUST click on the HELP button to see a detailed description of this level!
// The raven will tell you what to use for your maze parameters!
var SLIDE =8, SWITCH =6, SKIP = 11;
// How many sideSteps north of the Red X you've taken.
var sideSteps = 1;
// How many steps east of the Red X you've taken.
var steps = 1;
// Multiply this with steps to determine your X coordinate. DON'T CHANGE THIS!
var X_PACE_LENGTH = 4;
// Multiply this with sideSteps to determine your Y coordinate. DON'T CHANGE THIS!
var Y_PACE_LENGTH = 6;
var sn = 1;
// The maze is 35 steps along the X axis.
while(steps <= 35) {
// Take the next step:
hero.moveXY(steps * X_PACE_LENGTH, sideSteps * Y_PACE_LENGTH);
if (steps % SWITCH === 0 ) {
sn = -sn;
}
sideSteps += sn;
if (steps % SKIP === 0) {
sideSteps += sn;
}
if (sideSteps < 1) {
sideSteps += SLIDE;
} else if (sideSteps > SLIDE) {
sideSteps -= SLIDE;
}
// Increment steps and sideSteps as appropriate, taking into account the special rules.
steps++;
}
//In this level the evilstone is bad! Avoid them walking the other direction.
while (true) {
evilstone = hero.findNearestItem();
if (evilstone) {
pos = evilstone.pos;
if (pos.x == 34) {
// If the evilstone is on the left, go to the right side.
hero.moveXY(46, 22);
} else {
// If the evilstone is on the right, go to the left side.
hero.moveXY(34, 22);
}
} else {
// If there's no evilstone, go to the middle.
hero.moveXY(40, 22);
}
}
#In this level the evilstone is bad! Avoid them walking the other direction.
while True:
evilstone = hero.findNearest(hero.findItems())
if evilstone:
pos = evilstone.pos
if pos.x == 34:
# If the evilstone is on the left, go to the right side.
hero.moveXY(46, 22)
else:
# If the evilstone is on the right, go to the left side.
hero.moveXY(34, 22)
else:
# If there's no evilstone, go to the middle.
hero.moveXY(40, 22)
// Be the first to 100 gold!
// If you die, you will respawn at 67% gold.
loop {
// Find coins and/or attack the enemy.
// Use flags and your special moves to win!
var flag = hero.findFlag();
var coin = hero.findNearest(hero.findItems());
var enemy = hero.findNearest(hero.findEnemies());
if (flag) {
hero.pickUpFlag(flag);
}
if (enemy) {
hero.attack(enemy);
}
if (coin) {
hero.move(coin.pos);
}
}
// Вы можете использовать флаги, чтобы применять различные тактики.
// На этом уровне, зеленый флаг означает, что вы хотите, двигаться к флагу.
// Черный флаг означает, что на его месте нужно рассекать ('cleave') врагов.
// Целитель вылечит вас, если вы встанете на место красного крестика.
loop {
var green = hero.findFlag("green");
var black = hero.findFlag("black");
var nearest = hero.findNearestEnemy();
if (green) {
hero.pickUpFlag(green);
} else if (black && hero.isReady("cleave")) {
hero.pickUpFlag(black);
// Рассеките!
hero.cleave();
} else if (nearest && hero.distanceTo(nearest) < 10) {
// Атакуйте!
hero.attack(nearest);
}
}
# Вы можете использовать флаги, чтобы применять различные тактики.
# На этом уровне, зеленый флаг означает, что вы хотите, двигаться к флагу.
# Черный флаг означает, что на его месте нужно рассекать ('cleave') врагов.
# Целитель вылечит вас, если вы встанете на место красного крестика.
loop:
green = hero.findFlag("green")
black = hero.findFlag("black")
nearest = hero.findNearestEnemy()
if green:
hero.pickUpFlag(green)
elif black and hero.isReady("cleave"):
hero.pickUpFlag(black)
# Рассеките!
hero.cleave()
elif nearest and hero.distanceTo(nearest) < 10:
# Атакуйте!
hero.attack(nearest)
pass
// These Munchkins are scared of the hero!
// Say something and they'll back off.
// However, once there are enough Munchkins, they will gang up and ambush! Be careful!
// Whenever you can, cleave to clear the mass of enemies.
loop {
// Use isReady to check if the hero can cleave, otherwise say something!
if (hero.isReady("cleave")) {
hero.cleave();
} else hero.say("Dance!");
}
// You can add strings together, and add numbers into strings.
// Sing along, using string concatenation:
// X potions of health on the wall!
// X potions of health!
// Take Y down, pass it around!
// X-Y potions of health on the wall.
var potionsOnTheWall = 10;
var numToTakeDown = 1;
while(true) {
hero.say(potionsOnTheWall + " potions of health on the wall!");
// Sing the next line:
hero.say(potionsOnTheWall + " potions of health!");
// Sing the next line:
hero.say("Take " + numToTakeDown + " down, pass it around!");
potionsOnTheWall -= numToTakeDown;
// Sing the last line:
hero.say(potionsOnTheWall + " potions of health on the wall!");
}
// This defines a function called findAndAttackEnemy
hero.findAndAttackEnemy = function() {
var enemy = hero.findNearestEnemy();
if (enemy) {
hero.attack(enemy);
}
};
// This code is not part of the function.
while(true) {
// Now you can patrol the village using findAndAttackEnemy
hero.moveXY(35, 34);
hero.findAndAttackEnemy();
// Now move to the right entrance.
hero.moveXY(60, 31);
// Use findAndAttackEnemy
hero.findAndAttackEnemy();
}
// Если ты попробуешь атаковать врага, твой герой будет это делать, игнорируя все флаги.
// Ты должен убедиться, что ты атакуешь врагов, которые находятся рядом с тобой!
loop {
var flag = hero.findFlag();
var enemy = hero.findNearestEnemy();
if(flag) {
// Возьми флаг.
hero.pickUpFlag(flag);
//hero.say("Я должен взять флаг.");
} else if(enemy) {
// Атакуй врага, если он находится на расстоянии < 10 метров
if (hero.distanceTo(enemy) < 10) {
hero.attack(enemy);
}
}
}
def cleaveOrAttack(enemy):
# If "cleave" is ready, cleave; otherwise, attack.
if hero.isReady("cleave"):
hero.cleave(enemy)
else:
hero.attack(enemy)
pass
while True:
enemy = hero.findNearest(hero.findEnemies())
if enemy:
distance = hero.distanceTo(enemy)
if distance < 5:
# Call the "cleaveOrAttack" function, defined above.
cleaveOrAttack(enemy)
def enemyInRange(enemy):
# Return true if the enemy is less than 5 units away.
if hero.distanceTo(enemy) < 5:
return True
return False
def cleaveOrAttack(enemy):
if hero.isReady('cleave'):
hero.cleave(enemy)
else:
hero.attack(enemy)
while True:
enemy = hero.findNearest(hero.findEnemies())
if enemy:
# Check the distance of the enemy by calling enemyInRange.
if enemyInRange(enemy):
cleaveOrAttack(enemy)
# Peasants and peons are gathering in the forest.
# Command the peasants to battle and the peons to go away!
while True:
friend = hero.findNearestFriend()
if friend:
hero.say("To battle, " + friend.id + "!")
# Now find the nearest enemy and tell them to go away.
enemy = self.findNearest(self.findEnemies())
if enemy:
hero.say("Go away, " + enemy.id + "!")
# It seems like the Ogre Chieftain is stealing your gems!
# Use the two artillery cannons to defeat your enemies and gather the gems.
while True:
enemy = hero.findNearest(hero.findEnemies())
if enemy:
enemyPos = enemy.pos.x + " " + enemy.pos.y
hero.say("Enemy at: " + enemyPos)
# Now that you have sweet revenge, why not have your cake and eat it, too?
# Find the item's position and say it for your artillery to target.
item = hero.findNearest(hero.findItems())
if item:
itemPos = item.pos.x + " " + item.pos.y
hero.say("Item at: " + itemPos)
# Lure the ogres into a trap.
# But, they are careful.
# These ogres will only follow the hero if they are injured.
# This function checks the hero's health and returns a Boolean value.
def shouldRun():
if hero.health < hero.maxHealth / 2:
return True
else:
return False
while True:
# Run to the X only if the hero shouldRun().
if shouldRun():
hero.moveXY(75, 37)
else:# Otherwise, fight!
enemy = hero.findNearest(hero.findEnemies())
hero.attack(enemy)
# Move to 'Laszlo' and get his secret number.
hero.moveXY(30, 13)
las = hero.findNearestFriend().getSecret()
# Add 7 to 'Laszlo's number to get 'Erzsebet's number.
# Move to 'Erzsebet' and say her magic number.
erz = las + 7
hero.moveXY(17, 26)
hero.say(erz)
# Divide 'Erzsebet's number by 4 to get 'Simonyi's number.
# Go to 'Simonyi' and tell him his number.
sim = erz / 4;
hero.moveXY(30, 39)
hero.say(sim)
# Multiply 'Simonyi's number by 'Laszlo's to get 'Agata's number.
# Go to 'Agata' and tell her her number.
aga = sim * las;
hero.moveXY(43, 26)
hero.say(aga)
# Move to Zsofia and get the secret number from her.
hero.moveXY(18, 20)
secret = hero.findNearest(hero.findFriends()).getSecret()
# Follow Zsofia's instructions to get the magic number!
# Move to Mihaly and say his magic number.
hero.moveXY(30, 15)
hero.say(secret/4)
# Move to Beata and say her magic number.
hero.moveXY(42, 20)
hero.say(secret/4/5)
# Move to Sandor and say his magic number.
hero.moveXY(38, 37)
hero.say(secret/4-secret/4/5)
# Move to Eszter and get the secret number from her.
hero.moveXY(16, 32)
secret = hero.findNearest(hero.findFriends()).getSecret()
# Follow the instructions to get the magic number!
# Remember to use parentheses to do calculations in the right order.
# Move to Tamas and say his magic number.
hero.moveXY(24, 28)
t=secret*3-2
hero.say(t)
# Move to Zsofi and say her magic number.
hero.moveXY(32, 24)
z=(t-1)*4
hero.say(z)
# Move to Istvan and say his magic number.
hero.moveXY(40, 20)
i=(((secret*3-2)-1)*4+secret*3-2)/2
hero.say(i)
# Move to Csilla and say her magic number.
hero.moveXY(48, 16)
hero.say((t+z)*(z-i))
# This shows how to define a function called cleaveWhenClose
# The function defines a parameter called target
def cleaveWhenClose(target):
if hero.distanceTo(target) < 5:
pass
# Put your attack code here
# If cleave is ready, then cleave target
if hero.isReady("cleave"):
hero.cleave()
else:# else, just attack target!
hero.attack(target)
# This code is not part of the function.
while True:
enemy = hero.findNearestEnemy()
if enemy:
# Note that inside cleaveWhenClose, we refer to the enemy as target.
cleaveWhenClose(enemy)
# The function maybeBuildTrap defines TWO parameters!
def maybeBuildTrap(x, y):
# Use x and y as the coordinates to move to.
hero.moveXY(x, y)
enemy = hero.findNearestEnemy()
if enemy:
#pass
# Use buildXY to build a "fire-trap" at the given x and y.
hero.buildXY("fire-trap", x, y)
while True:
# This calls maybeBuildTrap, with the coordinates of the top entrance.
maybeBuildTrap(43, 50)
# Now use maybeBuildTrap at the left entrance!
maybeBuildTrap(25, 34)
# Now use maybeBuildTrap at the bottom entrance!
maybeBuildTrap(43, 20)
# Peons are trying to steal your coins!
# Write a function to squash them before they can take your coins.
def pickUpCoin():
coin = hero.findNearest(hero.findItems())
if coin:
hero.moveXY(coin.pos.x, coin.pos.y)
# Write the attackEnemy function below.
# Find the nearest enemy and attack them if they exist!
def attackEnemy():
enemy = hero.findNearest(hero.findEnemies())
if enemy:
hero.attack(enemy)
while True:
attackEnemy() # ∆ Uncomment this line after you write an attackEnemy function.
pickUpCoin()
Loot a gigantic chest while surrounded by a swarm of ogre munchkins.
Basic Syntax, Arguments, Strings, Variables, Loops, If Statements

Code for plan() method is here:

# Another chest in the field for the hero to break open!
# Attack the chest to break it open.
# Some munchkins won't stand idly by while you attack it!
# Defend yourself when a munchkin gets too close.

loop
  enemy = @findNearestEnemy()
  if @isReady "cleave"
    # First priority is to cleave if it's ready:
    @cleave enemy
  else if @distanceTo enemy < 5
    # Attack the nearest munchkin that gets too close:
    @attack enemy
  else
    # Otherwise, try to break open the chest:
    # Use the name of the chest to attack: "Chest".
    @attack "Chest"
# Another chest in the field for the hero to break open!
# Attack the chest to break it open.
# Some munchkins won't stand idly by while you attack it!
# Defend yourself when a munchkin gets too close.
while True:
enemy = hero.findNearestEnemy()
distance = hero.distanceTo(enemy)
if hero.isReady("cleave"):
# First priority is to cleave if it's ready:
hero.cleave(enemy)
elif distance < 5:
# Attack the nearest munchkin that gets too close:
hero.attack(enemy)
else:
# Otherwise, try to break open the chest:
# Use the name of the chest to attack: "Chest".
hero.attack("Chest")
# <%= use_two_parameters %>
# <%= examine_structure %>
# <%= accessibility %>
def checkAndAttack(x, y):
# <%= first_do_this %>
hero.moveXY(x,y)
# <%= then_do_this %>
enemy = hero.findNearest(self.findEnemies())
# <%= if_enemy %>
if enemy and hero.distanceTo(enemy) < 10:
hero.attack(enemy)
pass
checkAndAttack(24, 42)
checkAndAttack(27, 60)
# <%= navigate %>
checkAndAttack(42, 50)
checkAndAttack(39, 24)
checkAndAttack(55, 29)
# Ogres are attacking a nearby settlement!
# Be careful, though, for the ogres have sown the ground with poison.
# Gather coins and defeat the ogres, but avoid the burls and poison!
while True:
enemy = hero.findNearestEnemy()
if enemy.type == "munchkin" or enemy.type == "thrower":
hero.attack(enemy)
item = hero.findNearestItem()
# Check the item type to make sure the hero doesn't pick up poison!
# Look for types: 'gem' and 'coin'
if item.type == "gem" or item.type == "coin":
hero.move(item.pos)
# The coin field has been seeded with vials of deadly poison.
# Ogres are attacking, while their peons are trying to steal your coins!
# Let the peons pick up the poison, and only gather the coins and gems.
while True:
enemy = hero.findNearestEnemy()
if enemy:
if not enemy.type is "peon":
hero.attack(enemy)
item = hero.findNearest(hero.findItems())
if item:
# Gather the item only if it is not poison.
if item.type != "poison":
hero.move(item.pos)
# Get two secret true/false values from the wizard.
hero.moveXY(14, 24)
secretA = hero.findNearestFriend().getSecretA()
secretB = hero.findNearestFriend().getSecretB()
# If BOTH secretA and secretB are true, take the high path; otherwise, take the low path.
# Check the guide for notes on how to write logical expressions.
secretC = secretA and secretB
if secretC:
hero.moveXY(20, 33)
else:
hero.moveXY(20, 15)
hero.moveXY(26, 24)
# If EITHER secretA or secretB is true, take the high path.
if secretA or secretB:
hero.moveXY(32, 33)
else:
hero.moveXY(32, 15)
hero.moveXY(38, 24)
# Take the OPPOSITE of secretB and follow its path.
if not secretB:
hero.moveXY(44, 33)
else:
hero.moveXY(44, 15)
hero.moveXY(50, 24)
# Move to the wizard and get their secret values.
hero.moveXY(20, 24)
secretA = hero.findNearestFriend().getSecretA()
secretB = hero.findNearestFriend().getSecretB()
secretC = hero.findNearestFriend().getSecretC()
# If ALL three values are true, take the high path. Otherwise, take the low path.
secretD = secretA and secretB and secretC
if secretD:
hero.moveXY(30, 33)
else:
hero.moveXY(30, 15)
# If ANY of the three values are true, take the left path. Otherwise, go right.
if secretA or secretB or secretC:
hero.moveXY(20, 24)
else:
hero.moveXY(40, 24)
# If ALL of the LAST three values are true, take the high path.
if secretA and secretB and secretC:
hero.moveXY(30, 33)
else:
hero.moveXY(30, 15)
// Try to get the best grade (gold) at the magic exam.
// Move to each X mark, then use a spell.
function action() {
var friend = hero.findNearestFriend();
if (friend) {
if (friend.type === 'soldier') {
hero.cast('heal', friend);
} else if (friend.type === 'goliath') {
hero.cast('grow', friend);
} else {
hero.cast('regen', friend);
}
}
var enemy = hero.findNearestEnemy();
if (enemy) {
if (enemy.type === 'ogre') {
hero.cast('force-bolt', enemy);
} else if (enemy.type === 'brawler') {
hero.cast('shrink', enemy);
} else {
hero.cast('poison-cloud', enemy);
}
}
}
hero.moveXY(18, 24);
action();
hero.moveXY(18, 40);
action();
hero.moveXY(34, 24);
action();
hero.moveXY(34, 40);
action();
hero.moveXY(50, 40);
action();
hero.moveXY(50, 24);
action();
hero.moveXY(66, 40);
var item = hero.findNearestItem();
hero.cast('grow', hero);
hero.moveXY(item.pos.x, item.pos.y);
hero.moveXY(66, 24);
var item = hero.findNearestItem();
hero.moveXY(item.pos.x, item.pos.y);
# Try to get the best grade (gold) at the magic exam.
# Move to each X mark, then use a spell.
def action():
friend = hero.findNearestFriend()
if friend:
if friend.type == 'soldier':
hero.cast('heal', friend)
elif friend.type == 'goliath':
hero.cast('grow', friend)
else:
hero.cast('regen', friend)
enemy = hero.findNearestEnemy()
if enemy:
if enemy.type == 'ogre':
hero.cast('force-bolt', enemy)
elif enemy.type == 'brawler':
hero.cast('shrink', enemy)
else:
hero.cast('poison-cloud', enemy)
hero.moveXY(18, 24)
action()
hero.moveXY(18, 40)
action()
hero.moveXY(34, 24)
action()
hero.moveXY(34, 40)
action()
hero.moveXY(50, 40)
action()
hero.moveXY(50, 24)
action()
hero.moveXY(66, 40)
item = hero.findNearestItem()
hero.cast('grow', hero)
hero.moveXY(item.pos.x, item.pos.y)
hero.moveXY(66, 24)
item = hero.findNearestItem()
hero.moveXY(item.pos.x, item.pos.y)
// Пройди до конца тропы и построй забор на отметке X. Либо ловушку, чтобы собрать побольше самоцветов.
// Используй функцию `moveXY(x, y)`.
// Это первый этап пути.
hero.moveXY(36, 59);
// Двигайся к следующим точкам.
hero.moveXY(37, 13);
hero.moveXY(73, 59);
// Построй забор, чтобы остановить огра.
hero.moveXY(68, 22);
hero.buildXY("fence", 72, 25);
# Значением булева типа могут быть либо истина, либо ложь
# Символ == означает "это равно тому?"
# Так, строка "А == B" задает вопрос "A равняется B?"
# Ответ должен быть булевым значением!
# Нажмите кнопку "Помощь", если Вы запутались!
# Вопрос: 2 == 3
# Произнесите правильный ответ:
@say false
# Вопрос: 3 == 3
# Ответьте ложь или истина на вопрос 2:
@say true
# Вопрос: "Three" == 3
# Ответьте ложь или истина на вопрос 3:
@say false
# Вопрос: "Three" == "Three"
# Ответьте ложь или истина на вопрос 4:
@say true
# Вопрос: 1 + 2 == 3
# Ответьте ложь или истина на вопрос 5:
@say true
// Команды, находящиеся в теле if-оператора, написанные ниже будут исполнятся ,только если условие в скобках будет выполнено.
// == обозначает "равно ли", т.е. сравнение.
if (2 + 2 == 4) {
hero.say("Hey!");
}
if (2 + 2 == 5) {
hero.say("Yes, you!");
}
// Измени оператор так , чтобы заставить твоего героя крикнуть: "Иди ко мне!"
if (3 + 3 == 6) { // ∆ Make this true.
hero.say("Come at me!");
}
if (20 == 20) { // ∆ Make this true.
// Добавь еще одну насмешку чтобы приманить огра. Подойди к делу творчески!
hero.say("Победа!");
}
# Команды, находящиеся в теле if-оператора, написанные ниже будут исполнятся ,только если условие в скобках будет выполнено.
# == обозначает "равно ли", т.е. сравнение.
if 2 + 2 == 4:
hero.say("Hey!")
if 2 + 2 == 5:
hero.say("Yes, you!")
# Измени оператор так , чтобы заставить твоего героя крикнуть: "Иди ко мне!"
if 3 + 3 == 6: # ∆ Make this true.
hero.say("Come at me!")
if 20 == 20: # ∆ Make this true.
# Добавь еще одну насмешку чтобы приманить огра. Подойди к делу творчески!
hero.say("Победа!")
// Помните, что врага в данный момент может не быть рядом.
loop {
var enemy = hero.findNearestEnemy();
// Но когда он появится, атакуйте!
if (enemy) hero.attack(enemy);
else hero.say("Лежать, бояться!");
}
# Используй "if" или "else if" для принятия решений в любой ситуации.
# Совмести их чтобы собрать монеты и победить врагов!
# Рекомендовано иметь 400 ед. здоровья. Убедись, что купил хорошую броню.
loop:
flag = hero.findFlag()
enemy = hero.findNearest(self.findEnemies())
item = hero.findNearest(self.findItems())
if flag:
# Что делать когда я вижу флаг?
hero.pickUpFlag(flag)
elif enemy:
# Что делать когда я обнаружу противника?
dist = hero.distanceTo(enemy)
if(dist<10):
if(hero.isReady("cleave")):
hero.cleave(enemy)
else:
hero.attack(enemy)
elif item:
# Что делать когда я нахожу предметы?
hero.moveXY(item.pos.x, item.pos.y)
# Собери 100 золота с двух или трех рощ.
# С каждой победой становится все сложнее и сложнее (но и вознаграждение больше)
# Если проиграешь - будешь ждать сутки до следующей попытки
# Запомни: местность меняется каждый раз.
while True:
flag = hero.findFlag()
enemy = hero.findNearestEnemy()
item = hero.findNearestItem()
if flag:
hero.pickUpFlag(flag)
elif enemy:
if hero.isReady("bash"):
hero.bash(enemy)
elif hero.isReady("cleave") and hero.distanceTo(enemy) < 10:
hero.cleave(enemy)
else:
hero.attack(enemy)
elif item:
if hero.isReady("jump") and hero.distanceTo(item) > 15:
hero.jumpTo(item.pos)
else:
hero.move(item.pos)
# Оставайтесь живым одну минуту.
# Если вы победите, этот уровень станет сложнее (и более прибыльным)
# Если вы проиграете, вы должны подождать день, перед следующей попыткой.
# Помните, что каждый раз уровень генерируется по-разному.
def attack(target):
if target:
if (hero.isReady("jump") and hero.distanceTo > 10):
hero.jumpTo(enemy.pos)
elif (hero.isReady("bash")):
hero.bash(enemy)
elif (hero.isReady("power-up")):
hero.powerUp()
hero.attack(enemy)
elif (hero.isReady("cleave")):
hero.cleave(enemy)
else:
hero.attack(enemy)
summonTypes = ['archer', 'soldier']
def summonTroops():
type = summonTypes[len(hero.built) % len(summonTypes)]
if hero.gold > hero.costOf(type):
hero.summon(type)
def commandSoldiers():
for soldier in hero.findFriends():
hero.command(soldier, "defend", self)
while True:
summonTroops()
commandSoldiers()
enemy = hero.findNearestEnemy()
if enemy:
if hero.distanceTo(enemy) > 20 and hero.isReady("jump"):
hero.jumpTo(enemy)
if hero.isReady("cleave"):
hero.cleave(enemy)
elif hero.isReady("bash"):
hero.bash(enemy)
else:
hero.attack(enemy)
# Оставайтесь живым одну минуту.
# Если вы победите, этот уровень станет сложнее (и более прибыльным)
# Если вы проиграете, вы должны подождать день, перед следующей попыткой.
# Помните, что каждый раз уровень генерируется по-разному.
summonTypes = ['soldier', 'archer', 'griffin-rider', 'archer', 'archer']
def moveTo(position, fast=True):
if (hero.isReady("jump") and hero.distanceTo(position) > 10 and fast):
hero.jumpTo(position)
else:
hero.move(position)
def summonTroops():
type = summonTypes[len(hero.built) % len(summonTypes)]
if hero.gold > hero.costOf(type):
hero.summon(type)
def commandTroops():
for soldier in hero.findFriends():
if enemy:
hero.command(soldier, "attack", enemy)
#hero.command(soldier, "defend", self)
def attack(target):
if (hero.distanceTo(target) > 20):
moveTo(target.pos)
elif hero.isReady("chain-lightning"):
hero.cast("chain-lightning", target)
elif hero.isReady("bash"):
hero.bash(target)
else:
hero.attack(target)
while True:
summonTroops()
commandTroops()
enemy = hero.findNearest(hero.findEnemies())
if (enemy):
attack(enemy)
// Злой Камень на этом уровне - это зло! Спасайтесь от него убегая в противоположную сторону.
while (true) {
var evilstone = hero.findNearestItem();
if (evilstone) {
var pos = evilstone.pos;
if (pos.x == 34) { // == значит "равно"
// Если Злой Камень слева - бегите вправо.
hero.moveXY(46, pos.y);
} else {
// Если Злой Камень справа - бегите влево.
hero.moveXY(34, pos.y);
}
} else {
// Если Злого Камня нет - бегите на середину.
hero.moveXY(40, pos.y);
}
}
// Используй функцию `checkAndAttack`, чтобы сделать код более читаемым.
// Эта функция имеет параметр.
// Параметр - способ передать данные в функцию.
function checkAndAttack(target) {
// Параметр `target` - это просто переменная!
// В него передаётся значение аргумента при вызове функции.
if(target) {
hero.attack(target);
}
hero.moveXY(43, 34);
}
while(true) {
hero.moveXY(58, 52);
var topEnemy = hero.findNearestEnemy();
// Using the checkAndAttack function with the topEnemy variable.
checkAndAttack(topEnemy);
// Иди к нижней отметке Х.
hero.moveXY(58, 16);
// Создай переменную `bottomEnemy` и найди ближайшего врага.
var bottomEnemy = hero.findNearestEnemy();
// Используй функцию `checkAndAttack` с аргументом `bottomEnemy`.
checkAndAttack(bottomEnemy);
}
# Вы можете добавлять строки вместе и добавлять числа в строки.
# Подпевайте используя строковую конкатенацию (объединение строк)
# X potions of health on the wall!
# X potions of health!
# Take Y down, pass it around!
# X-Y potions of health on the wall.
potionsOnTheWall = 10
numToTakeDown = 1
while True:
hero.say(potionsOnTheWall + " potions of health on the wall!")
# Спойте следующую строку:
hero.say(potionsOnTheWall + " potions of health!")
# Спойте следующую строку:
hero.say("Take " + numToTakeDown + " down, pass it around!")
potionsOnTheWall -= numToTakeDown
# Спойте последнюю строку:
hero.say(potionsOnTheWall + " potions of health on the wall!")
// Это определяет функцию с именем `findAndAttackEnemy`
function findAndAttackEnemy() {
var enemy = hero.findNearestEnemy();
if (enemy) {
hero.attack(enemy);
}
}
// Этот код не является частью функции.
while(true) {
// Теперь ты можешь патрулировать деревню, используя `findAndAttackEnemy`
hero.moveXY(35, 34);
findAndAttackEnemy();
// Теперь иди к правому входу.
hero.moveXY(60, 31);
// Используй `findAndAttackEnemy`
findAndAttackEnemy();
}
// Крестьяне и батраки собираются в лесу.
// Прикажи крестьянам готовиться к бою, а батракам уходить прочь!
while(true) {
var friend = hero.findNearestFriend();
if(friend) {
hero.say("To battle, " + friend.id + "!");
}
// Теперь найди ближайшего врага и прикажи ему уходить (`go away`).
var enemy = hero.findNearestEnemy();
if (enemy) {
hero.say("Go away, " + enemy.id + "!");
}
}
// Подойди к 'Laszlo' и узнай его секретное число.
hero.moveXY(30, 13);
var las = hero.findNearestFriend().getSecret();
// Прибавь 7 к числу 'Laszlo', чтобы получить число 'Erzsebet'.
// Подойди к 'Erzsebet' и скажи её волшебное число.
var erz = las + 7;
hero.moveXY(17, 26);
hero.say(erz);
// Раздели число 'Erzsebet' на 4, чтобы получить число 'Simonyi'.
// Подойди к 'Simonyi' и скажи его число.
var sim = erz / 4;
hero.moveXY(30, 39);
hero.say(sim);
// Умножь число 'Simonyi' на число 'Laszlo', чтобы получить число 'Agata'.
// Подойди к 'Agata' и скажи её число.
var aga = sim * las;
hero.moveXY(43, 26);
hero.say(aga);
// Двигайся по следам монет к красной отметке X у выхода.
while (true) {
// Найди ближайший предмет.
var item = hero.findNearestItem();
if (item) {
// Сохраняет позицию предмета в переменную.
var itemPosition = item.pos;
// Помести координаты X и Y предмета в переменные.
var itemX = itemPosition.x;
var itemY = itemPosition.y;
// Теперь используй `moveXY`, чтобы двигаться на `itemX` и `itemY`:
hero.moveXY(itemX, itemY);
}
}
// Здесь показано, как определить функцию `cleaveWhenClose`
// Функция определяет параметр `target`
function cleaveWhenClose(target) {
if(hero.distanceTo(target) < 5) {
// Помести сюда вызов `attack`
// Если готов рубить, то рубить цель
if (hero.isReady("cleave")) {
hero.cleave(target);
} else { // иначе просто атаковать цель!
hero.attack(target);
}
}
}
// Этот код не входит в функцию.
while(true) {
var enemy = hero.findNearestEnemy();
if(enemy) {
// Заметь, что внутри `cleaveWhenClose` мы ссылаемся на врага с помощью переменной `target`.
cleaveWhenClose(enemy);
}
}
// Ещё один сундук на поле ждет героя!
// Атакуй сундук, чтобы взломать его.
// Некоторые манчкины не будут спокойно ждать, пока ты атакуешь его!
// Защищай себя, если манчкин подберётся слишком близко.
while(true) {
var enemy = hero.findNearestEnemy();
var distance = hero.distanceTo(enemy);
if(hero.isReady("cleave")) {
// Приоритет способности `cleave`, если она готова:
hero.cleave(enemy);
} else if(distance < 5) {
// Атакуй ближайшего манчкина, который подберётся близко:
hero.attack(enemy);
} else {
// В противном случае, пытайтся взломать сундук.
// Используйте название сундука "Chest" как цель атаки.
hero.attack("Chest");
}
}
Убивай огров в лесу, но остерегайся громыхающих чудовищ.
Булева равность, Условные операторы, Доступ к свойствам, Строки, Переменные, Циклы "while"

Code for plan() method is here:

# Атакуй врагов только с типами "munchkin" и "thrower".
# Не атакуй бурлов. Убегай, если встретишь огра.

loop
    enemy = @findNearestEnemy()
    #
    # Помни, не атакуй врагов с типом "burl"!
    if enemy.type is "burl"
        @say "Я не атакую этого бурла!"
        @moveXY 21, 25

    # Свойство "type" говорит тебе о типе существа.
    if enemy.type is "munchkin"
        @attack enemy

    # Используй `if`, чтобы атаковать "thrower".
    if enemy.type is "thrower"
        @attack enemy

    # Убегай (`moveXY`) к воротам деревни, как только увидишь огра.
    if enemy.type is "ogre"
        @moveXY 21, 41
// Соберите все драгоценные камни в 4 moveXY или меньше!
// Программистам нужно мыслить творчески!
hero.moveXY(32, 48);
hero.moveXY(70, 48);
hero.moveXY(32, 10);
hero.moveXY(32, 36);
Собери все девять самоцветов, используя не более четырех команд moveXY.
Базовый синтаксис, Читать документацию

Code for plan() method is here:

# Соберите все драгоценные камни в 4 moveXY или меньше!
# Программистам нужно мыслить творчески!
@moveXY 32, 48
@moveXY 70, 48
@moveXY 32, 10
@moveXY 32, 36
Огры такие разные.
Булева равность, Условные операторы, Доступ к свойствам, Строки, Переменные, Циклы "while"

Code for plan() method is here:

# Атакуйте манчкинов, провоцируйте драчунов и игнорируйте бурлов.
# Эта функция определяет поведение героя по отношению к врагам.

dealEnemy = (enemy) ->
    # Если enemy.type равен "munchkin":
    # Тогда атакуй его.
    # Если тип противника "brawler":
    # Тогда скажи что-нибудь, чтобы спровоцировать драчуна двигаться к тебе:
    if enemy.type is "munchkin"
        hero.attack enemy
    if enemy.type is "brawler"
        hero.say "Jesus"
    return

loop
    enemy = @findNearestEnemy()
    if enemy
        dealEnemy enemy
    else
        hero.moveXY 30, 34
// Пройди через лес, но будь начеку!
// Эти лесные закоулки могут быть полны огров!
hero.moveXY(19, 33);
var enemy = hero.findNearestEnemy();
// Выражение `if` проверит, является ли переменная огром.
if(enemy) {
hero.attack(enemy);
hero.attack(enemy);
}
hero.moveXY(49, 51);
var enemy = hero.findNearestEnemy();
if(enemy) {
// Атакуй противника здесь:
hero.attack(enemy);
hero.attack(enemy);
}
hero.moveXY(58, 14);
var enemy = hero.findNearestEnemy();
// Используй выражение `if`, чтобы проверить существование врага
if(enemy) {
// Если враг здесь, атакуй его:
hero.attack(enemy);
hero.attack(enemy);
}
// Победи огров в их собственном лагере!
while(true) {
var enemy = hero.findNearestEnemy();
// Используй выражение `if`, чтобы проверить наличие врага:
if (enemy) {
// Атакуй, если рядом враг:
hero.attack(enemy);
}
}
// Победи столько огров, сколько сможешь.
// Используй 'cast' и 'canCast' для заклинаний.
var index = 0;
var plan = ["lightning-bolt", 'attack', 'attack', 'attack', 'attack', 'attack', "lightning-bolt", "chain-lightning",
"regen", 'attack', "regen", "lightning-bolt", "chain-lightning", 'attack', 'attack', "lightning-bolt", 'attack',
"regen", "lightning-bolt", 'say', "away", 'armagedon'];
while (true) {
var currentPlan = plan[index % plan.length];
if (currentPlan === 'regen') {
if (hero.isReady("regen")) {
hero.cast("regen", hero);
index++;
} else {
hero.moveXY(8, 30);
}
} else if (currentPlan === 'away') {
hero.moveXY(18, 41);
index++;
} else if (currentPlan === 'say') {
hero.say("booring");
index++;
} else if (currentPlan === 'armagedon'){
hero.moveXY(7, 41);
index++;
} else {
var enemy = hero.findNearestEnemy();
if (enemy) {
if (enemy && enemy.health > 0) {
var dist = hero.distanceTo(enemy);
if (currentPlan === 'attack') {
hero.attack(enemy);
} else if (currentPlan === "chain-lightning" && hero.isReady("chain-lightning")) {
hero.cast("chain-lightning", enemy);
} else if (currentPlan === "lightning-bolt" && hero.isReady("lightning-bolt")) {
hero.cast("lightning-bolt", enemy);
}
}
if (enemy.health <= 0) {
index++;
}
} else {
hero.moveXY(8, 30);
}
}
}
# Победи столько огров, сколько сможешь.
# Используй 'cast' и 'canCast' для заклинаний.
index = 0
plan = ["lightning-bolt", 'attack', 'attack', 'attack', 'attack', 'attack', "lightning-bolt", "chain-lightning",
"regen", 'attack', "regen", "lightning-bolt", "chain-lightning", 'attack', 'attack', "lightning-bolt", 'attack',
"regen", "lightning-bolt", 'say', "away", 'armagedon']
while True:
current_plan = plan[index % len(plan)]
if (current_plan == 'regen'):
if hero.isReady("regen"):
hero.cast("regen", hero)
index += 1
else:
hero.moveXY(8, 30)
elif (current_plan == 'away'):
hero.moveXY(18, 41)
index += 1
elif (current_plan == 'say'):
hero.say("booring")
index += 1
elif (current_plan == 'armagedon'):
hero.moveXY(7, 41)
index += 1
else:
enemy = hero.findNearestEnemy()
if (enemy):
if (enemy and enemy.health > 0):
dist = hero.distanceTo(enemy)
if (current_plan == 'attack'):
hero.attack(enemy)
elif (current_plan == "chain-lightning" and hero.isReady("chain-lightning")):
hero.cast("chain-lightning", enemy)
elif current_plan == "lightning-bolt" and hero.isReady("lightning-bolt"):
hero.cast("lightning-bolt", enemy)
if (enemy.health <= 0):
index += 1
else:
hero.moveXY(8, 30)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment