from controller import Robot

robot = Robot()
timeStep = 64

# المحركات
left_motor = robot.getDevice("left wheel motor")
right_motor = robot.getDevice("right wheel motor")

left_motor.setPosition(float('inf'))
right_motor.setPosition(float('inf'))
left_motor.setVelocity(0.0)
right_motor.setVelocity(0.0)

# الحساسات
ball_sensor = robot.getDevice("ball_sensor")
ball_sensor.enable(timeStep)

compass = robot.getDevice("compass")
compass.enable(timeStep)

sonar = robot.getDevice("sonar")
sonar.enable(timeStep)

gps = robot.getDevice("gps")
gps.enable(timeStep)

# حركات بسيطة
def forward():
    left_motor.setVelocity(5.0)
    right_motor.setVelocity(5.0)

def turn_left():
    left_motor.setVelocity(-2.0)
    right_motor.setVelocity(2.0)

def turn_right():
    left_motor.setVelocity(2.0)
    right_motor.setVelocity(-2.0)

def stop():
    left_motor.setVelocity(0.0)
    right_motor.setVelocity(0.0)

# حلقة التكرار
while robot.step(timeStep) != -1:
    ball = ball_sensor.getValue()
    comp = compass.getValues()
    obst = sonar.getValue()
    pos = gps.getValues()
    
    # لو فيه عائق قدامي
    if obst < 800:
        turn_left()
    
    # لو الكرة موجودة
    elif ball > 0:
        # إذا الكرة واضحة قدامي
        if ball > 200:
            forward()
        else:
            # إذا لسه بعيدة شوي، نلف عشان نوجّه الروبوت
            turn_right()
    
    # لو ما فيه كرة
    else:
        turn_left()
