Greenfoot Kara ZigZag code wont work properly

59 Views Asked by At

I wanted to write a code for Greenfoot Kara, but my code wont work properly. Please help me debugg it, since im trying it now for 3 Hours straight, but cant get it to work.

Heres my code:

public class MyKara extends Kara {
 int evenodd=2;


 public void act() {
  turnRight();
 
  while(true){
   if(treeLeft() && !treeRight()){
     move();
     turnLeft();
     move();
    }
    else if(treeRight() && !treeLeft()){
      move();
      turnRight();
      move();
    }
    else if(treeLeft() && treeRight()){
     evenodd = evenodd++;
    
     if((evenodd % 2) == 0){
        evenodd = evenodd++;
        move();
        turnRight();
        move();
     }
     else if((evenodd % 2) != 0){
        evenodd = evenodd++;
        move();
        turnLeft();
        move();
     }
    }   
   }
  }
 }
1

There are 1 best solutions below

0
On

You can not use a while loop inside the act() method. The view is updated only when act() returns.

Use a member variable to store the state of your Kara, and react accordingly inside act(). Use a switch or a chain of if - else if, whatever you understand better.