{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": "# First programs: drive a pod in a square\n\nA pod on a virtual table, driven by your code. You will drive it straight,\nturn it, make it draw a square, find out why the square does not close,\nand fix that with feedback.\n\nDistances are metres, angles radians, speeds metres and radians per second.\nThe table is 3 m by 2 m; the walls stop a pod that drives into them."
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": "# Get the Plato Pod client from the server (once per session) and its one dependency.\nimport os\nimport subprocess\nimport sys\nimport urllib.request\n\nSERVER = \"https://arena.platopod.com\"\nos.makedirs(\"platopod\", exist_ok=True)\nfor f in (\"__init__.py\", \"arena.py\", \"pod.py\"):\n    urllib.request.urlretrieve(f\"{SERVER}/sdk/platopod/{f}\", f\"platopod/{f}\")\nsubprocess.run([sys.executable, \"-m\", \"pip\", \"install\", \"-q\", \"websockets>=12\"], check=True)\nprint(\"ready\")"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": "## Join the room\n\nChoose a name: the same name gets the same pod back next time. The room's code is\n**TLQGNR** (Problem solving: first programs in Python). Run the next cell, then open the link it prints to watch your pod."
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": "from platopod import Arena\n\nROOM_CODE = \"TLQGNR\"\nMY_NAME = \"your name here\"          # letters, digits and spaces\n\narena, pod = Arena.join_room(ROOM_CODE, MY_NAME)\nprint(\"You are pod\", pod.robot_id, \"at\", pod.pose)\nprint(\"Watch it:\", f\"{arena.url}/view3d.html#key={arena.key}\")"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": "## 1. Straight ahead\n\n`pod.drive_for(speed, turn_rate, seconds)` holds a speed for a while, then stops.\nAt 0.1 m/s for 3 s the pod should cover 30 cm. Does it?\n\nFirst the pod turns to face the middle of the table, so it drives into open floor\nand not into a wall (your name keeps your pod where you last left it)."
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": "import math\nimport time\n\n\ndef wrap(angle):\n    \"\"\"An angle in -pi..pi.\"\"\"\n    return (angle + math.pi) % (2 * math.pi) - math.pi\n\ndef face_the_middle():\n    \"\"\"Turn, by time, towards the middle of the 3 m x 2 m table.\"\"\"\n    p = pod.pose\n    error = wrap(math.atan2(1.0 - p.y, 1.5 - p.x) - p.theta)\n    pod.drive_for(0.0, math.copysign(0.8, error), abs(error) / 0.8)\n\nface_the_middle()\ntime.sleep(0.5)\nstart = pod.pose\npod.drive_for(0.1, 0.0, 3.0)\ntime.sleep(0.5)\nend = pod.pose\nprint(f\"moved {math.dist((start.x, start.y), (end.x, end.y)):.3f} m\")"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": "## 2. A quarter turn\n\nTurning at 0.8 rad/s, a quarter turn (\u03c0/2 rad) takes \u03c0/2 / 0.8 seconds.\n`LEFT` is +1 (anticlockwise) or -1 (clockwise): `choose_turn()` picks the way a\nsquare from here stays on the table, and first drives the pod into the open if\nneither way does."
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": "def square_fits(turn, side=0.35, margin=0.12):\n    \"\"\"Whether a square from here, turning this way, keeps clear of the walls.\"\"\"\n    x, y, heading = pod.pose.x, pod.pose.y, pod.pose.theta\n    for _ in range(4):\n        x, y = x + side * math.cos(heading), y + side * math.sin(heading)\n        if not (margin < x < 3.0 - margin and margin < y < 2.0 - margin):\n            return False\n        heading += turn * math.pi / 2\n    return True\n\ndef choose_turn():\n    global LEFT\n    for _ in range(6):\n        for turn in (1, -1):\n            if square_fits(turn):\n                LEFT = turn\n                return\n        face_the_middle()                  # no room either way: into the open first\n        pod.drive_for(0.1, 0.0, 2.0)\n        time.sleep(0.5)\n    raise RuntimeError(\"no room for a square: is the table crowded?\")\n\nchoose_turn()\n\ndef turn_quarter():\n    pod.drive_for(0.0, LEFT * 0.8, (math.pi / 2) / 0.8)\n\nbefore = pod.pose.theta\nturn_quarter()\ntime.sleep(0.5)\nprint(f\"turned {math.degrees(pod.pose.theta - before):.1f} degrees\")"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": "## 3. A square, by time\n\nFour sides, four turns. Where does the pod end up, compared with where it started?"
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": "def square_by_time(side=0.3, speed=0.1):\n    choose_turn()\n    start = pod.pose\n    for _ in range(4):\n        pod.drive_for(speed, 0.0, side / speed)\n        turn_quarter()\n    time.sleep(0.5)\n    end = pod.pose\n    print(f\"missed the start by {100 * math.dist((start.x, start.y), (end.x, end.y)):.1f} cm, \"\n          f\"heading off by {math.degrees(end.theta - start.theta):.1f} degrees\")\n\nsquare_by_time()"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": "## 4. Why it misses, and feedback\n\nTiming assumes every command arrives on time and the pod does exactly what it is\ntold. Over the internet commands arrive late and unevenly, and the pod speeds up and\nslows down. Instead of trusting the clock, *look* at the pod: turn until the heading\nis right, drive until the distance is right. That is feedback.\n\nA loop that waits for something must also notice when it will never happen: a pod\nagainst a wall never covers the distance. `forward` gives up when the pod has not\nmoved for 2 s, and `turn_to` after 10 s."
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": "def turn_to(heading, tolerance=0.02):\n    give_up = time.monotonic() + 10.0\n    while True:\n        error = wrap(heading - pod.pose.theta)\n        if abs(error) < tolerance:\n            break\n        if time.monotonic() > give_up:\n            print(\"turn_to gave up: the pod is not turning (another pod in the way?)\")\n            break\n        pod.drive(0.0, max(-1.0, min(1.0, 2.0 * error)))   # slower as it gets close\n        time.sleep(0.1)\n    pod.stop()\n\ndef forward(distance, speed=0.1):\n    start = pod.pose\n    last, last_moved = pod.pose, time.monotonic()\n    while math.dist((start.x, start.y), (pod.pose.x, pod.pose.y)) < distance:\n        here = pod.pose\n        if math.dist((last.x, last.y), (here.x, here.y)) > 0.01:\n            last, last_moved = here, time.monotonic()\n        elif time.monotonic() - last_moved > 2.0:\n            print(\"forward gave up: the pod is not moving (a wall or another pod?)\")\n            break\n        pod.drive(speed, 0.0)\n        time.sleep(0.1)\n    pod.stop()\n\ndef square_by_feedback(side=0.3):\n    choose_turn()\n    start = pod.pose\n    heading = start.theta\n    for _ in range(4):\n        forward(side)\n        heading = wrap(heading + LEFT * math.pi / 2)\n        turn_to(heading)\n    time.sleep(0.5)\n    end = pod.pose\n    print(f\"missed the start by {100 * math.dist((start.x, start.y), (end.x, end.y)):.1f} cm\")\n\nsquare_by_feedback()"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": "## 5. Your turn\n\n1. Write `polygon(n, side)`: a triangle, a pentagon, a hexagon. What angle does each turn need?\n2. A spiral: each side a little longer than the last.\n3. A five-pointed star (each turn is 144\u00b0).\n4. Go back to where you started, whatever you drew: work out the heading and distance\n   from the pod's pose, turn, and drive.\n\nA start for the first one:"
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": "def polygon(n, side=0.25):\n    heading = pod.pose.theta\n    for _ in range(n):\n        forward(side)\n        heading = wrap(heading + LEFT * 2 * math.pi / n)\n        turn_to(heading)\n\npolygon(3)"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": "When you are done, give the pod back (your name keeps it for 20 minutes)."
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": "arena.close()"
  }
 ],
 "nbformat": 4,
 "nbformat_minor": 5,
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python"
  }
 }
}
