148k views
2 votes
2.12.6: Right vs. Left Square

Write a program that has Karel place balls in a square formation.

If Karel is facing North to start, balls should be placed in a square using right turns only [(put ball, move, turn right) x4]. You should write a function called makeRightSquare to accomplish this.
If Karel is facing East to start, balls should be placed in a square using left turns only [(put ball, move, turn left) x4]. You should write a function called makeLeftSquare to accomplish this.
In both scenarios, Karel should end facing the starting direction.

Practice using an if/else statement in your code. You should also use a for loop in your solution!

1 Answer

4 votes

hope that helps.!

Explanation: ``python def makeRightSquare(): for i in range(4): put_ball() move() turn_right() turn_right() def makeLeftSquare(): for i in range(4): put_ball() move() turn_left() turn_left() # Check Karel's starting direction if facing_north(): makeRightSquare() elif facing_east(): makeLeftSquare() ``` In this program, we have two functions: `makeRightSquare()` and `makeLeftSquare()`. These functions use a for loop to repeat the actions of putting a ball, moving forward, and turning either right or left depending on the starting direction of Karel. Based on Karel's starting direction, we use an if/else statement to call the appropriate function (`makeRightSquare()` or `makeLeftSquare()`). If Karel is facing north, `makeRightSquare()` is called, which uses right turns to create the square formation. If Karel is facing east, `makeLeftSquare()` is called, which uses left turns. At the end of each function, Karel turns back to the starting direction so that the final position matches the initial direction. Remember to replace the `put_ball()`, `move()`, `turn_right()`, `turn_left()`, `facing_north()`, and `facing_east()` with the actual functions and conditions specific to the programming environment or language you are using.What would you like to do next?

User Hamit
by
7.5k points

Related questions

Welcome to QAmmunity.org, where you can ask questions and receive answers from other members of our community.