{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "21c8be3f-c57b-439c-8ca8-5991dd0da465",
   "metadata": {},
   "source": [
    "# 夺旗赛 Capture The Flag"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0dfeabca-44d9-4906-abc6-cba1e4fc8a35",
   "metadata": {},
   "source": [
    "## 初始化 (使用上排目录栏的的 ▶️ 运行，▪️停止， ⟳ 重启）"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "098c5853-135d-4eb8-ab51-bbf660fc09e9",
   "metadata": {},
   "outputs": [],
   "source": [
    "import importlib\n",
    "import lib.game_engine\n",
    "\n",
    "# Force the reload manually\n",
    "importlib.reload(lib.game_engine)\n",
    "\n",
    "# Re-import the specific classes/functions\n",
    "from lib.game_engine import GameMap, run_game_server\n",
    "\n",
    "# Now initialize your objects\n",
    "world = GameMap()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e9437ef2-777a-4694-b1b2-428e654be4ab",
   "metadata": {},
   "outputs": [],
   "source": [
    "from IPython.display import clear_output\n",
    "import os\n",
    "import json\n",
    "import random"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a1d9d9f6-3644-41bf-a60d-0148a74140c4",
   "metadata": {},
   "source": [
    "## 以下是你要编写的代码。 \n",
    "- start_game：初始化游戏。\n",
    "- game_over：游戏结束。\n",
    "- plan_next_actions：每一时刻，告诉你目前小人们的位置。\n",
    "  \n",
    "每次代码更新，一定要使用上排目录栏的的 ▶️ 运行"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "021ea24a-9a8f-4a4d-a086-f3b80b882c95",
   "metadata": {},
   "outputs": [],
   "source": [
    "## 这是你要编写的策略\n",
    "def start_game(req):\n",
    "    \"\"\"Called when the game begins.\"\"\"\n",
    "    world.init(req)\n",
    "    print(f\"Map initialized: {world.width}x{world.height}\")\n",
    "\n",
    "def game_over(req):\n",
    "    \"\"\"Called when the game ends.\"\"\"\n",
    "    print(\"Game Over!\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "22e04cb6-87cb-486d-a580-a1ae5fbe3a98",
   "metadata": {},
   "outputs": [],
   "source": [
    "## 这是你要编写的策略。以下always_move_right和walk_to_first_flag_and_return是两个例子\n",
    "def plan_next_actions(req):\n",
    "    \"\"\"\n",
    "    Called every tick. \n",
    "    Return a dictionary: {\"playerName\": \"direction\"}\n",
    "    direction is \"up\", \"down\", \"right\", \"left, \"\" . \"\" means the player should stand still.\n",
    "    \"\"\"\n",
    "    world.update(req)    \n",
    "    world.show() \n",
    "    actions = dict()\n",
    "    # TODO:请在这里写下你的代码来控制小人\n",
    "    \n",
    "    return actions\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "a8561aec-4246-40dc-b833-1d2b8991edd3",
   "metadata": {},
   "outputs": [],
   "source": [
    "## 这是一个超简单策略：即把所有的小人都向右移动\n",
    "## Python小测试 - 将以下程序改成：如果是L team，就往右走；如果是R team，就往左走。\n",
    "def always_move_right(req):\n",
    "    \"\"\"\n",
    "    Called every tick. \n",
    "    Return a dictionary: {\"playerName\": \"direction\"}\n",
    "    direction is \"up\", \"down\", \"right\", \"left, \"\" . \"\" means the player should stand still.\n",
    "    \"\"\"\n",
    "    if not world.update(req):\n",
    "        return\n",
    "\n",
    "    world.show() \n",
    "\n",
    "    # List all players that can move freely (set `hasFlag=True`)\n",
    "    my_players = world.list_players(mine=True, inPrison=False, hasFlag=None)\n",
    "\n",
    "    actions = dict()\n",
    "    for p in my_players:\n",
    "        actions[p[\"name\"]] = \"right\"\n",
    "\n",
    "    return actions"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "e4b51cda-514b-4264-b8af-53acc4a76120",
   "metadata": {},
   "outputs": [],
   "source": [
    "## 这是一个超简单策略：所有小人都向着第一个小旗子走\n",
    "## Python小测试 - 将以下程序改成：如果在对方的领地里，将对方的player位置设为extra_obstacles\n",
    "\n",
    "def walk_to_first_flag_and_return(req):\n",
    "    \"\"\"\n",
    "    Called every tick. \n",
    "    Return a dictionary: {\"playerName\": \"direction\"}\n",
    "    direction is \"up\", \"down\", \"right\", \"left, \"\" . \"\" means the player should stand still.\n",
    "    \"\"\"\n",
    "    if not world.update(req):\n",
    "        return\n",
    "\n",
    "    # world.show() always show targets and prisons, regardless whether flags and players are not there or not\n",
    "    world.show(flag_over_target=True, player_over_prison=True) \n",
    "\n",
    "    # List all players that can move freely (set `hasFlag=True`)\n",
    "    my_players_go = world.list_players(mine=True, inPrison=False, hasFlag=False)\n",
    "    my_players_return = world.list_players(mine=True, inPrison=False, hasFlag=True)\n",
    "    # List a\n",
    "    opponents = world.list_players(mine=False, inPrison=False, hasFlag=None)\n",
    "    enemy_flags = world.list_flags(mine=False, canPickup=None)\n",
    "    \n",
    "    actions = {}\n",
    "    \n",
    "    # Everyone wo/ a flag rushes the first flag\n",
    "    if enemy_flags:\n",
    "        target_flag = enemy_flags[0]\n",
    "        dest = (target_flag[\"posX\"], target_flag[\"posY\"])\n",
    "        for p in my_players_go:\n",
    "            start = (p[\"posX\"], p[\"posY\"])\n",
    "            path = world.route_to(start, dest, extra_obstacles=[])\n",
    "            \n",
    "            if len(path) > 1:\n",
    "                # Convert the next coordinate in path to a direction string\n",
    "                next_step = path[1]\n",
    "                actions[p[\"name\"]] = GameMap.get_direction(start, next_step)\n",
    "    # Everyone w/ a flag returns the target zone\n",
    "    target_zone = list(world.list_targets(mine=True))[0]\n",
    "    for p in my_players_return:\n",
    "        start = (p[\"posX\"], p[\"posY\"])\n",
    "        path = world.route_to(start, target_zone, extra_obstacles=[])\n",
    "        if len(path) > 1:\n",
    "            # Convert the next coordinate in path to a direction string\n",
    "            next_step = path[1]\n",
    "            actions[p[\"name\"]] = GameMap.get_direction(start, next_step)\n",
    "    return actions"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "322772ab-a0b8-4da3-906f-212926ad24fb",
   "metadata": {},
   "source": [
    "## 运行以下cell启动你的server (使用上排目录栏的的 ▶️ 运行，使用▪️停止）\n",
    "[*] 表示cell正在运行中"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e0898ab6-bd6e-4bf1-9a29-d802933dd91a",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Change the port to match your game settings\n",
    "import os\n",
    "\n",
    "PORT_ID = 2 # 或者 2\n",
    "PORT = \"CTF_PORT_BACKEND\" + str(PORT_ID)\n",
    "\n",
    "try:\n",
    "    PORT_VALUE = os.environ[PORT]\n",
    "    print(f\"PORT: {PORT_VALUE}\")\n",
    "except KeyError:\n",
    "    print(\"Error: PORT environment variable not set.\")\n",
    "try:\n",
    "    # 将`plan_fn=`改成你的plan_next_actions，如always_move_right, walk_to_first_flag_and_return 等等\n",
    "    await run_game_server(PORT_VALUE, start_fn=start_game, plan_fn=walk_to_first_flag_and_return, end_fn=game_over)\n",
    "except Exception as e:\n",
    "    print(f\"Server stopped: {e}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b869dde3-cf94-4d25-8fe8-25096bab1f37",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.13.11"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
