hi. i’m having trouble with this level. can someone help me? tell me what is wrong with my code:
def heroDefend(x, y):
hero.moveXY(x, y)
enemy = hero.findNearestEnemy()
if enemy:
hero.attack(enemy)
else:
hero.moveXY(x, y)
for x in range(8, 73, 16):
hero.moveXY(x, 22)
peasant = hero.findNearest(hero.findFriends())
message = peasant.message
if message:
words = message.split(" ")
for i in range(len(words)):
wordA = words[len(words)]
if wordA:
hero.summon(wordA)
for i in range(len(hero.built)):
unit = hero.built[i]
hero.command(unit, "defend", unit.pos)
while True:
x = 72
y = 22
heroDefend(x, y)
if message:
words = message.split(" ")
for i in range(len(words)):
wordA = words[len(words)]
if wordA:
hero.summon(wordA)
You define ‘words’ as an array of the message components…the split function divides the message in to its individual pieces. Your task is now to define the last component, as this is the unit type you need:
# "words" is an array of words from the "message".
# Get the last word. It's the required unit type.
(A strong suggestion here…I would highly recommend not deleting the comments, as these can help keep you on track, or focused…but 'tis only a suggestion.)
You are attempting to use a for loop to parse thru the array (not a bad idea), but since we know the array is fixed in size and we know exactly where (which element) we need to look, there is a much simpler way…and yes, it does involve using the len() method.
I will show you that method, but want to give you a chance at figuring it out for yourself, first.
# Ogres are hiding in woods. Protect the peasants.
# The last word in the peasants' messages are a hint.
def heroDefend(x, y):
hero.moveXY(x, y)
enemy = hero.findNearestEnemy()
if enemy:
hero.attack(enemy)
else:
hero.moveXY(x, y)
for x in range(8, 73, 16):
hero.moveXY(x, 22)
# Peasants know whom to summon.
peasant = hero.findNearest(hero.findFriends())
message = peasant.message
if message:
# Words are seaparated by whitespaces.
words = message.split(" ")
# "words" is an array of words from the "message".
# Get the last word. It's the required unit type.
for i in words:
wordA = words[len(words)]
# Summon the required unit type.
if wordA:
hero.summon(wordA)
for i in range(len(hero.built)):
unit = hero.built[i]
# Command the unit to defend the unit's position.
hero.command(unit, "defend", unit.pos)
# Defend the last point yourself:
while True:
x = 72
y = 22
heroDefend(x, y)