from controller import Robot, Compass, GPS

robot = Robot()
timestep = int(robot.getBasicTimeStep())

# المحركات
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_sensors = []
for i in range(7):
    sensor = robot.getDevice("IRsensor" + str(i))
    sensor.enable(timestep)
    ball_sensors.append(sensor)

compass = robot.getDevice("compass")
compass.enable(timestep)

gps = robot.getDevice("gps")
gps.enable(timestep)

sonar = robot.getDevice("sonar")
sonar.enable(timestep)

# السرعات
MAX_SPEED = 6.0

while robot.step(timestep) != -1:
    # قراءة مستشعر الكرة
    ball_values = [s.getValue() for s in ball_sensors]
    ball_detected = max(ball_values)
    ball_index = ball_values.index(ball_detected)

    # قراءة السونار
    distance = sonar.getValue()

    # تجنب الاصطدام
    if distance < 0.25:
        left_motor.setVelocity(-0.5 * MAX_SPEED)
        right_motor.setVelocity(0.5 * MAX_SPEED)
        continue

    # إذا اكتشف الكرة
    if ball_detected > 0:
        if ball_index < 3:  # الكرة على اليسار
            left_motor.setVelocity(0.5 * MAX_SPEED)
            right_motor.setVelocity(1.0 * MAX_SPEED)
        elif ball_index > 3:  # الكرة على اليمين
            left_motor.setVelocity(1.0 * MAX_SPEED)
            right_motor.setVelocity(0.5 * MAX_SPEED)
        else:  # الكرة في الوسط
            left_motor.setVelocity(MAX_SPEED)
            right_motor.setVelocity(MAX_SPEED)
    else:
        # لو ما في كرة، يبحث بدوران
        left_motor.setVelocity(0.5 * MAX_SPEED)
        right_motor.setVelocity(-0.5 * MAX_SPEED)
