from controller import Robot, Motor, DistanceSensor, Camera, Compass

# إعداد الروبوت والمحركات
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)

# إعداد المستشعرات
ir_sensors = []
for i in range(8):  # افترض أن هناك 8 مستشعرات IR
    sensor = robot.getDevice('ir' + str(i))
    sensor.enable(timestep)
    ir_sensors.append(sensor)

camera = robot.getDevice('camera')
camera.enable(timestep)

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

# إعداد السرعات الأساسية
MAX_SPEED = 6.28

# دوال مساعدة
def move_forward(speed=MAX_SPEED):
    left_motor.setVelocity(speed)
    right_motor.setVelocity(speed)

def turn_left(speed=MAX_SPEED/2):
    left_motor.setVelocity(-speed)
    right_motor.setVelocity(speed)

def turn_right(speed=MAX_SPEED/2):
    left_motor.setVelocity(speed)
    right_motor.setVelocity(-speed)

def stop():
    left_motor.setVelocity(0)
    right_motor.setVelocity(0)

def ball_in_sight():
    # مثال: استخدام الكاميرا للكشف عن الكرة
    # أضف خوارزمية التعرف على اللون أو الشكل حسب المحاكاة
    image = camera.getImage()
    # ضع هنا شرط الكشف عن الكرة
    return False

def obstacle_detected():
    # تحقق من أي مستشعر IR إذا كان قريبًا جدًا من عقبة
    threshold = 1000  # اضبط حسب المحاكاة
    for sensor in ir_sensors:
        if sensor.getValue() > threshold:
            return True
    return False

def move_towards_ball():
    if obstacle_detected():
        avoid_obstacle()
    else:
        move_forward()

def avoid_obstacle():
    # خوارزمية بسيطة لتجنب العقبات
    turn_left()
    move_forward(MAX_SPEED / 2)

def search_for_ball():
    # تدوير ببطء للبحث عن الكرة
    turn_right(MAX_SPEED / 3)

def kick_ball():
    # افترض أن الضرب يتم بتحريك الروبوت للأمام عند الكرة
    move_forward(MAX_SPEED)
    # يمكن إضافة توقيت لضرب الكرة بدقة
    pass

# الحلقة الأساسية
while robot.step(timestep) != -1:
    if ball_in_sight():
        move_towards_ball()
        # تحقق إذا كان قريبًا من الهدف للتسديد
        kick_ball()
    else:
        search_for_ball()