Hazırlayanlar: Eric Roberts'ın ders notlarını temel alır, Zach Birnholz ve Lisa Yan tarafından güncellenmiştir
Çeviren: Ceren Kocaoğullar
Handouts: Karel Reference
File: banish_winter.py
Karel, Stanford / CTU / Koç kampüsünde yürümek ve bahar için biraz bahçe işleri yapmak istiyor. Bahar başladı, ancak kampüs ağaçları henüz bunu fark edemedi ve hala yapraksızlar. Karel, batıdan doğuya doğru kampüs boyunca yürümeli, tüm ağaçları yapay yapraklarla süslemeli ve kampüsü şu şekilde dönüştürmeli:
Sorun karmaşık çünkü Karel her ağacın ne kadar uzun olduğunu ya da ağaçlar arasındaki mesafeleri bilmiyor. Ancak beeper çantasında tüm ağaçları süslemeye başlayan yeterince beeper olduğunu ve dünyanın (CTU kampüsü) 9 boşluk genişliğinde olduğunu biliyor. Yukarıdaki iki anlık görüntüye bakarak program gereksinimini anlamaya çalışın (dünya dosyasının adı banish_winter.w
.) Programınız yalnızca bu dünyada değil, aşağıdaki dünya için de çalışmalıdır (banish_winter2.w
):
Yukarıdaki gereksinimleri karşılayan herhangi bir dünyada çalışan bir programı nasıl yazabiliriz?
from karel.stanfordkarel import *"""File: banish_winter.py------------------------Karel should add leaves to the top of each tree in the worldfrom left to right to spruce up campus for the spring.The world is of width 9, but it may have any number of treesof any height."""def main():# world is 9 spaces wide, we start on 1for i in range(8):if front_is_clear():move()else:fix_tree()def fix_tree():"""Karel climbs to the top of one tree, adds leaves, and descends theother side of tree. When this function is called, Karel is assumed tobe facing east towards the bottom of the tree to fix, and when the functionis done Karel will be facing east immediately after the tree which hasnow been fixed."""turn_left()climb_tree()turn_right()place_leaves()turn_right()move_to_wall()turn_left()def move_to_wall():"""Moves in a straight line in the direction Karel is facing until a wall."""while front_is_clear():move()def climb_tree():"""Karel climbs a tree by moving as long as its right is blocked.After this function finishes, Karel will be facing the same directionas it was originally, but will be one space past the last square whereits right was blocked."""while right_is_blocked():move()def place_leaves():"""Adds four leaves, in a square pattern to the top of a tree.Assumes Karel is facing east in the bottom left corner of the squareit wants to make with beepers. When the function finishes, Karelwill be one square to the east facing east, standing on the bottom rightcorner of a newly-created square of beepers."""for i in range(4):put_beeper()move()turn_left()move()def turn_right():"""Karel turns right - e.g. if Karel is facing east, now Karel will facesouth. If Karel is facing north, Karel will now face east."""for i in range(3):turn_left()# There is no need to edit code beyond this pointif __name__ == "__main__":run_karel_program()