summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--.gitignore10
-rw-r--r--COPYING674
-rw-r--r--Makefile44
-rw-r--r--README209
-rw-r--r--maps/README.md77
-rw-r--r--maps/challenger/01_the_impossible_dream.txt189
-rw-r--r--maps/easy/01_linear_path.txt11
-rw-r--r--maps/easy/02_simple_fork.txt14
-rw-r--r--maps/easy/03_basic_capacity.txt11
-rw-r--r--maps/hard/01_maze_nightmare.txt52
-rw-r--r--maps/hard/02_capacity_hell.txt51
-rw-r--r--maps/hard/03_ultimate_challenge.txt98
-rw-r--r--maps/medium/01_dead_end_trap.txt15
-rw-r--r--maps/medium/02_circular_loop.txt18
-rw-r--r--maps/medium/03_priority_puzzle.txt18
-rw-r--r--requirements.txt2
-rw-r--r--src/drone.py77
-rw-r--r--src/graph.py131
-rw-r--r--src/main.py52
-rw-r--r--src/models.py90
-rw-r--r--src/parser.py564
-rw-r--r--src/pathfinder.py176
-rw-r--r--src/scheduler.py285
23 files changed, 2868 insertions, 0 deletions
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..a3ff841
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,10 @@
+*tar.gz
+tags
+*swp
+__pycache__
+*bak
+output.json
+output
+.venv
+test.map
+visualiser.py
diff --git a/COPYING b/COPYING
new file mode 100644
index 0000000..f288702
--- /dev/null
+++ b/COPYING
@@ -0,0 +1,674 @@
+ GNU GENERAL PUBLIC LICENSE
+ Version 3, 29 June 2007
+
+ Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+ Preamble
+
+ The GNU General Public License is a free, copyleft license for
+software and other kinds of works.
+
+ The licenses for most software and other practical works are designed
+to take away your freedom to share and change the works. By contrast,
+the GNU General Public License is intended to guarantee your freedom to
+share and change all versions of a program--to make sure it remains free
+software for all its users. We, the Free Software Foundation, use the
+GNU General Public License for most of our software; it applies also to
+any other work released this way by its authors. You can apply it to
+your programs, too.
+
+ When we speak of free software, we are referring to freedom, not
+price. Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+them if you wish), that you receive source code or can get it if you
+want it, that you can change the software or use pieces of it in new
+free programs, and that you know you can do these things.
+
+ To protect your rights, we need to prevent others from denying you
+these rights or asking you to surrender the rights. Therefore, you have
+certain responsibilities if you distribute copies of the software, or if
+you modify it: responsibilities to respect the freedom of others.
+
+ For example, if you distribute copies of such a program, whether
+gratis or for a fee, you must pass on to the recipients the same
+freedoms that you received. You must make sure that they, too, receive
+or can get the source code. And you must show them these terms so they
+know their rights.
+
+ Developers that use the GNU GPL protect your rights with two steps:
+(1) assert copyright on the software, and (2) offer you this License
+giving you legal permission to copy, distribute and/or modify it.
+
+ For the developers' and authors' protection, the GPL clearly explains
+that there is no warranty for this free software. For both users' and
+authors' sake, the GPL requires that modified versions be marked as
+changed, so that their problems will not be attributed erroneously to
+authors of previous versions.
+
+ Some devices are designed to deny users access to install or run
+modified versions of the software inside them, although the manufacturer
+can do so. This is fundamentally incompatible with the aim of
+protecting users' freedom to change the software. The systematic
+pattern of such abuse occurs in the area of products for individuals to
+use, which is precisely where it is most unacceptable. Therefore, we
+have designed this version of the GPL to prohibit the practice for those
+products. If such problems arise substantially in other domains, we
+stand ready to extend this provision to those domains in future versions
+of the GPL, as needed to protect the freedom of users.
+
+ Finally, every program is threatened constantly by software patents.
+States should not allow patents to restrict development and use of
+software on general-purpose computers, but in those that do, we wish to
+avoid the special danger that patents applied to a free program could
+make it effectively proprietary. To prevent this, the GPL assures that
+patents cannot be used to render the program non-free.
+
+ The precise terms and conditions for copying, distribution and
+modification follow.
+
+ TERMS AND CONDITIONS
+
+ 0. Definitions.
+
+ "This License" refers to version 3 of the GNU General Public License.
+
+ "Copyright" also means copyright-like laws that apply to other kinds of
+works, such as semiconductor masks.
+
+ "The Program" refers to any copyrightable work licensed under this
+License. Each licensee is addressed as "you". "Licensees" and
+"recipients" may be individuals or organizations.
+
+ To "modify" a work means to copy from or adapt all or part of the work
+in a fashion requiring copyright permission, other than the making of an
+exact copy. The resulting work is called a "modified version" of the
+earlier work or a work "based on" the earlier work.
+
+ A "covered work" means either the unmodified Program or a work based
+on the Program.
+
+ To "propagate" a work means to do anything with it that, without
+permission, would make you directly or secondarily liable for
+infringement under applicable copyright law, except executing it on a
+computer or modifying a private copy. Propagation includes copying,
+distribution (with or without modification), making available to the
+public, and in some countries other activities as well.
+
+ To "convey" a work means any kind of propagation that enables other
+parties to make or receive copies. Mere interaction with a user through
+a computer network, with no transfer of a copy, is not conveying.
+
+ An interactive user interface displays "Appropriate Legal Notices"
+to the extent that it includes a convenient and prominently visible
+feature that (1) displays an appropriate copyright notice, and (2)
+tells the user that there is no warranty for the work (except to the
+extent that warranties are provided), that licensees may convey the
+work under this License, and how to view a copy of this License. If
+the interface presents a list of user commands or options, such as a
+menu, a prominent item in the list meets this criterion.
+
+ 1. Source Code.
+
+ The "source code" for a work means the preferred form of the work
+for making modifications to it. "Object code" means any non-source
+form of a work.
+
+ A "Standard Interface" means an interface that either is an official
+standard defined by a recognized standards body, or, in the case of
+interfaces specified for a particular programming language, one that
+is widely used among developers working in that language.
+
+ The "System Libraries" of an executable work include anything, other
+than the work as a whole, that (a) is included in the normal form of
+packaging a Major Component, but which is not part of that Major
+Component, and (b) serves only to enable use of the work with that
+Major Component, or to implement a Standard Interface for which an
+implementation is available to the public in source code form. A
+"Major Component", in this context, means a major essential component
+(kernel, window system, and so on) of the specific operating system
+(if any) on which the executable work runs, or a compiler used to
+produce the work, or an object code interpreter used to run it.
+
+ The "Corresponding Source" for a work in object code form means all
+the source code needed to generate, install, and (for an executable
+work) run the object code and to modify the work, including scripts to
+control those activities. However, it does not include the work's
+System Libraries, or general-purpose tools or generally available free
+programs which are used unmodified in performing those activities but
+which are not part of the work. For example, Corresponding Source
+includes interface definition files associated with source files for
+the work, and the source code for shared libraries and dynamically
+linked subprograms that the work is specifically designed to require,
+such as by intimate data communication or control flow between those
+subprograms and other parts of the work.
+
+ The Corresponding Source need not include anything that users
+can regenerate automatically from other parts of the Corresponding
+Source.
+
+ The Corresponding Source for a work in source code form is that
+same work.
+
+ 2. Basic Permissions.
+
+ All rights granted under this License are granted for the term of
+copyright on the Program, and are irrevocable provided the stated
+conditions are met. This License explicitly affirms your unlimited
+permission to run the unmodified Program. The output from running a
+covered work is covered by this License only if the output, given its
+content, constitutes a covered work. This License acknowledges your
+rights of fair use or other equivalent, as provided by copyright law.
+
+ You may make, run and propagate covered works that you do not
+convey, without conditions so long as your license otherwise remains
+in force. You may convey covered works to others for the sole purpose
+of having them make modifications exclusively for you, or provide you
+with facilities for running those works, provided that you comply with
+the terms of this License in conveying all material for which you do
+not control copyright. Those thus making or running the covered works
+for you must do so exclusively on your behalf, under your direction
+and control, on terms that prohibit them from making any copies of
+your copyrighted material outside their relationship with you.
+
+ Conveying under any other circumstances is permitted solely under
+the conditions stated below. Sublicensing is not allowed; section 10
+makes it unnecessary.
+
+ 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
+
+ No covered work shall be deemed part of an effective technological
+measure under any applicable law fulfilling obligations under article
+11 of the WIPO copyright treaty adopted on 20 December 1996, or
+similar laws prohibiting or restricting circumvention of such
+measures.
+
+ When you convey a covered work, you waive any legal power to forbid
+circumvention of technological measures to the extent such circumvention
+is effected by exercising rights under this License with respect to
+the covered work, and you disclaim any intention to limit operation or
+modification of the work as a means of enforcing, against the work's
+users, your or third parties' legal rights to forbid circumvention of
+technological measures.
+
+ 4. Conveying Verbatim Copies.
+
+ You may convey verbatim copies of the Program's source code as you
+receive it, in any medium, provided that you conspicuously and
+appropriately publish on each copy an appropriate copyright notice;
+keep intact all notices stating that this License and any
+non-permissive terms added in accord with section 7 apply to the code;
+keep intact all notices of the absence of any warranty; and give all
+recipients a copy of this License along with the Program.
+
+ You may charge any price or no price for each copy that you convey,
+and you may offer support or warranty protection for a fee.
+
+ 5. Conveying Modified Source Versions.
+
+ You may convey a work based on the Program, or the modifications to
+produce it from the Program, in the form of source code under the
+terms of section 4, provided that you also meet all of these conditions:
+
+ a) The work must carry prominent notices stating that you modified
+ it, and giving a relevant date.
+
+ b) The work must carry prominent notices stating that it is
+ released under this License and any conditions added under section
+ 7. This requirement modifies the requirement in section 4 to
+ "keep intact all notices".
+
+ c) You must license the entire work, as a whole, under this
+ License to anyone who comes into possession of a copy. This
+ License will therefore apply, along with any applicable section 7
+ additional terms, to the whole of the work, and all its parts,
+ regardless of how they are packaged. This License gives no
+ permission to license the work in any other way, but it does not
+ invalidate such permission if you have separately received it.
+
+ d) If the work has interactive user interfaces, each must display
+ Appropriate Legal Notices; however, if the Program has interactive
+ interfaces that do not display Appropriate Legal Notices, your
+ work need not make them do so.
+
+ A compilation of a covered work with other separate and independent
+works, which are not by their nature extensions of the covered work,
+and which are not combined with it such as to form a larger program,
+in or on a volume of a storage or distribution medium, is called an
+"aggregate" if the compilation and its resulting copyright are not
+used to limit the access or legal rights of the compilation's users
+beyond what the individual works permit. Inclusion of a covered work
+in an aggregate does not cause this License to apply to the other
+parts of the aggregate.
+
+ 6. Conveying Non-Source Forms.
+
+ You may convey a covered work in object code form under the terms
+of sections 4 and 5, provided that you also convey the
+machine-readable Corresponding Source under the terms of this License,
+in one of these ways:
+
+ a) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by the
+ Corresponding Source fixed on a durable physical medium
+ customarily used for software interchange.
+
+ b) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by a
+ written offer, valid for at least three years and valid for as
+ long as you offer spare parts or customer support for that product
+ model, to give anyone who possesses the object code either (1) a
+ copy of the Corresponding Source for all the software in the
+ product that is covered by this License, on a durable physical
+ medium customarily used for software interchange, for a price no
+ more than your reasonable cost of physically performing this
+ conveying of source, or (2) access to copy the
+ Corresponding Source from a network server at no charge.
+
+ c) Convey individual copies of the object code with a copy of the
+ written offer to provide the Corresponding Source. This
+ alternative is allowed only occasionally and noncommercially, and
+ only if you received the object code with such an offer, in accord
+ with subsection 6b.
+
+ d) Convey the object code by offering access from a designated
+ place (gratis or for a charge), and offer equivalent access to the
+ Corresponding Source in the same way through the same place at no
+ further charge. You need not require recipients to copy the
+ Corresponding Source along with the object code. If the place to
+ copy the object code is a network server, the Corresponding Source
+ may be on a different server (operated by you or a third party)
+ that supports equivalent copying facilities, provided you maintain
+ clear directions next to the object code saying where to find the
+ Corresponding Source. Regardless of what server hosts the
+ Corresponding Source, you remain obligated to ensure that it is
+ available for as long as needed to satisfy these requirements.
+
+ e) Convey the object code using peer-to-peer transmission, provided
+ you inform other peers where the object code and Corresponding
+ Source of the work are being offered to the general public at no
+ charge under subsection 6d.
+
+ A separable portion of the object code, whose source code is excluded
+from the Corresponding Source as a System Library, need not be
+included in conveying the object code work.
+
+ A "User Product" is either (1) a "consumer product", which means any
+tangible personal property which is normally used for personal, family,
+or household purposes, or (2) anything designed or sold for incorporation
+into a dwelling. In determining whether a product is a consumer product,
+doubtful cases shall be resolved in favor of coverage. For a particular
+product received by a particular user, "normally used" refers to a
+typical or common use of that class of product, regardless of the status
+of the particular user or of the way in which the particular user
+actually uses, or expects or is expected to use, the product. A product
+is a consumer product regardless of whether the product has substantial
+commercial, industrial or non-consumer uses, unless such uses represent
+the only significant mode of use of the product.
+
+ "Installation Information" for a User Product means any methods,
+procedures, authorization keys, or other information required to install
+and execute modified versions of a covered work in that User Product from
+a modified version of its Corresponding Source. The information must
+suffice to ensure that the continued functioning of the modified object
+code is in no case prevented or interfered with solely because
+modification has been made.
+
+ If you convey an object code work under this section in, or with, or
+specifically for use in, a User Product, and the conveying occurs as
+part of a transaction in which the right of possession and use of the
+User Product is transferred to the recipient in perpetuity or for a
+fixed term (regardless of how the transaction is characterized), the
+Corresponding Source conveyed under this section must be accompanied
+by the Installation Information. But this requirement does not apply
+if neither you nor any third party retains the ability to install
+modified object code on the User Product (for example, the work has
+been installed in ROM).
+
+ The requirement to provide Installation Information does not include a
+requirement to continue to provide support service, warranty, or updates
+for a work that has been modified or installed by the recipient, or for
+the User Product in which it has been modified or installed. Access to a
+network may be denied when the modification itself materially and
+adversely affects the operation of the network or violates the rules and
+protocols for communication across the network.
+
+ Corresponding Source conveyed, and Installation Information provided,
+in accord with this section must be in a format that is publicly
+documented (and with an implementation available to the public in
+source code form), and must require no special password or key for
+unpacking, reading or copying.
+
+ 7. Additional Terms.
+
+ "Additional permissions" are terms that supplement the terms of this
+License by making exceptions from one or more of its conditions.
+Additional permissions that are applicable to the entire Program shall
+be treated as though they were included in this License, to the extent
+that they are valid under applicable law. If additional permissions
+apply only to part of the Program, that part may be used separately
+under those permissions, but the entire Program remains governed by
+this License without regard to the additional permissions.
+
+ When you convey a copy of a covered work, you may at your option
+remove any additional permissions from that copy, or from any part of
+it. (Additional permissions may be written to require their own
+removal in certain cases when you modify the work.) You may place
+additional permissions on material, added by you to a covered work,
+for which you have or can give appropriate copyright permission.
+
+ Notwithstanding any other provision of this License, for material you
+add to a covered work, you may (if authorized by the copyright holders of
+that material) supplement the terms of this License with terms:
+
+ a) Disclaiming warranty or limiting liability differently from the
+ terms of sections 15 and 16 of this License; or
+
+ b) Requiring preservation of specified reasonable legal notices or
+ author attributions in that material or in the Appropriate Legal
+ Notices displayed by works containing it; or
+
+ c) Prohibiting misrepresentation of the origin of that material, or
+ requiring that modified versions of such material be marked in
+ reasonable ways as different from the original version; or
+
+ d) Limiting the use for publicity purposes of names of licensors or
+ authors of the material; or
+
+ e) Declining to grant rights under trademark law for use of some
+ trade names, trademarks, or service marks; or
+
+ f) Requiring indemnification of licensors and authors of that
+ material by anyone who conveys the material (or modified versions of
+ it) with contractual assumptions of liability to the recipient, for
+ any liability that these contractual assumptions directly impose on
+ those licensors and authors.
+
+ All other non-permissive additional terms are considered "further
+restrictions" within the meaning of section 10. If the Program as you
+received it, or any part of it, contains a notice stating that it is
+governed by this License along with a term that is a further
+restriction, you may remove that term. If a license document contains
+a further restriction but permits relicensing or conveying under this
+License, you may add to a covered work material governed by the terms
+of that license document, provided that the further restriction does
+not survive such relicensing or conveying.
+
+ If you add terms to a covered work in accord with this section, you
+must place, in the relevant source files, a statement of the
+additional terms that apply to those files, or a notice indicating
+where to find the applicable terms.
+
+ Additional terms, permissive or non-permissive, may be stated in the
+form of a separately written license, or stated as exceptions;
+the above requirements apply either way.
+
+ 8. Termination.
+
+ You may not propagate or modify a covered work except as expressly
+provided under this License. Any attempt otherwise to propagate or
+modify it is void, and will automatically terminate your rights under
+this License (including any patent licenses granted under the third
+paragraph of section 11).
+
+ However, if you cease all violation of this License, then your
+license from a particular copyright holder is reinstated (a)
+provisionally, unless and until the copyright holder explicitly and
+finally terminates your license, and (b) permanently, if the copyright
+holder fails to notify you of the violation by some reasonable means
+prior to 60 days after the cessation.
+
+ Moreover, your license from a particular copyright holder is
+reinstated permanently if the copyright holder notifies you of the
+violation by some reasonable means, this is the first time you have
+received notice of violation of this License (for any work) from that
+copyright holder, and you cure the violation prior to 30 days after
+your receipt of the notice.
+
+ Termination of your rights under this section does not terminate the
+licenses of parties who have received copies or rights from you under
+this License. If your rights have been terminated and not permanently
+reinstated, you do not qualify to receive new licenses for the same
+material under section 10.
+
+ 9. Acceptance Not Required for Having Copies.
+
+ You are not required to accept this License in order to receive or
+run a copy of the Program. Ancillary propagation of a covered work
+occurring solely as a consequence of using peer-to-peer transmission
+to receive a copy likewise does not require acceptance. However,
+nothing other than this License grants you permission to propagate or
+modify any covered work. These actions infringe copyright if you do
+not accept this License. Therefore, by modifying or propagating a
+covered work, you indicate your acceptance of this License to do so.
+
+ 10. Automatic Licensing of Downstream Recipients.
+
+ Each time you convey a covered work, the recipient automatically
+receives a license from the original licensors, to run, modify and
+propagate that work, subject to this License. You are not responsible
+for enforcing compliance by third parties with this License.
+
+ An "entity transaction" is a transaction transferring control of an
+organization, or substantially all assets of one, or subdividing an
+organization, or merging organizations. If propagation of a covered
+work results from an entity transaction, each party to that
+transaction who receives a copy of the work also receives whatever
+licenses to the work the party's predecessor in interest had or could
+give under the previous paragraph, plus a right to possession of the
+Corresponding Source of the work from the predecessor in interest, if
+the predecessor has it or can get it with reasonable efforts.
+
+ You may not impose any further restrictions on the exercise of the
+rights granted or affirmed under this License. For example, you may
+not impose a license fee, royalty, or other charge for exercise of
+rights granted under this License, and you may not initiate litigation
+(including a cross-claim or counterclaim in a lawsuit) alleging that
+any patent claim is infringed by making, using, selling, offering for
+sale, or importing the Program or any portion of it.
+
+ 11. Patents.
+
+ A "contributor" is a copyright holder who authorizes use under this
+License of the Program or a work on which the Program is based. The
+work thus licensed is called the contributor's "contributor version".
+
+ A contributor's "essential patent claims" are all patent claims
+owned or controlled by the contributor, whether already acquired or
+hereafter acquired, that would be infringed by some manner, permitted
+by this License, of making, using, or selling its contributor version,
+but do not include claims that would be infringed only as a
+consequence of further modification of the contributor version. For
+purposes of this definition, "control" includes the right to grant
+patent sublicenses in a manner consistent with the requirements of
+this License.
+
+ Each contributor grants you a non-exclusive, worldwide, royalty-free
+patent license under the contributor's essential patent claims, to
+make, use, sell, offer for sale, import and otherwise run, modify and
+propagate the contents of its contributor version.
+
+ In the following three paragraphs, a "patent license" is any express
+agreement or commitment, however denominated, not to enforce a patent
+(such as an express permission to practice a patent or covenant not to
+sue for patent infringement). To "grant" such a patent license to a
+party means to make such an agreement or commitment not to enforce a
+patent against the party.
+
+ If you convey a covered work, knowingly relying on a patent license,
+and the Corresponding Source of the work is not available for anyone
+to copy, free of charge and under the terms of this License, through a
+publicly available network server or other readily accessible means,
+then you must either (1) cause the Corresponding Source to be so
+available, or (2) arrange to deprive yourself of the benefit of the
+patent license for this particular work, or (3) arrange, in a manner
+consistent with the requirements of this License, to extend the patent
+license to downstream recipients. "Knowingly relying" means you have
+actual knowledge that, but for the patent license, your conveying the
+covered work in a country, or your recipient's use of the covered work
+in a country, would infringe one or more identifiable patents in that
+country that you have reason to believe are valid.
+
+ If, pursuant to or in connection with a single transaction or
+arrangement, you convey, or propagate by procuring conveyance of, a
+covered work, and grant a patent license to some of the parties
+receiving the covered work authorizing them to use, propagate, modify
+or convey a specific copy of the covered work, then the patent license
+you grant is automatically extended to all recipients of the covered
+work and works based on it.
+
+ A patent license is "discriminatory" if it does not include within
+the scope of its coverage, prohibits the exercise of, or is
+conditioned on the non-exercise of one or more of the rights that are
+specifically granted under this License. You may not convey a covered
+work if you are a party to an arrangement with a third party that is
+in the business of distributing software, under which you make payment
+to the third party based on the extent of your activity of conveying
+the work, and under which the third party grants, to any of the
+parties who would receive the covered work from you, a discriminatory
+patent license (a) in connection with copies of the covered work
+conveyed by you (or copies made from those copies), or (b) primarily
+for and in connection with specific products or compilations that
+contain the covered work, unless you entered into that arrangement,
+or that patent license was granted, prior to 28 March 2007.
+
+ Nothing in this License shall be construed as excluding or limiting
+any implied license or other defenses to infringement that may
+otherwise be available to you under applicable patent law.
+
+ 12. No Surrender of Others' Freedom.
+
+ If conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License. If you cannot convey a
+covered work so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you may
+not convey it at all. For example, if you agree to terms that obligate you
+to collect a royalty for further conveying from those to whom you convey
+the Program, the only way you could satisfy both those terms and this
+License would be to refrain entirely from conveying the Program.
+
+ 13. Use with the GNU Affero General Public License.
+
+ Notwithstanding any other provision of this License, you have
+permission to link or combine any covered work with a work licensed
+under version 3 of the GNU Affero General Public License into a single
+combined work, and to convey the resulting work. The terms of this
+License will continue to apply to the part which is the covered work,
+but the special requirements of the GNU Affero General Public License,
+section 13, concerning interaction through a network will apply to the
+combination as such.
+
+ 14. Revised Versions of this License.
+
+ The Free Software Foundation may publish revised and/or new versions of
+the GNU General Public License from time to time. Such new versions will
+be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+ Each version is given a distinguishing version number. If the
+Program specifies that a certain numbered version of the GNU General
+Public License "or any later version" applies to it, you have the
+option of following the terms and conditions either of that numbered
+version or of any later version published by the Free Software
+Foundation. If the Program does not specify a version number of the
+GNU General Public License, you may choose any version ever published
+by the Free Software Foundation.
+
+ If the Program specifies that a proxy can decide which future
+versions of the GNU General Public License can be used, that proxy's
+public statement of acceptance of a version permanently authorizes you
+to choose that version for the Program.
+
+ Later license versions may give you additional or different
+permissions. However, no additional obligations are imposed on any
+author or copyright holder as a result of your choosing to follow a
+later version.
+
+ 15. Disclaimer of Warranty.
+
+ THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
+APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
+HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
+OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
+THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
+IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
+ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+ 16. Limitation of Liability.
+
+ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
+THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
+GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
+USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
+DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
+PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
+EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
+SUCH DAMAGES.
+
+ 17. Interpretation of Sections 15 and 16.
+
+ If the disclaimer of warranty and limitation of liability provided
+above cannot be given local legal effect according to their terms,
+reviewing courts shall apply local law that most closely approximates
+an absolute waiver of all civil liability in connection with the
+Program, unless a warranty or assumption of liability accompanies a
+copy of the Program in return for a fee.
+
+ END OF TERMS AND CONDITIONS
+
+ How to Apply These Terms to Your New Programs
+
+ If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+ To do so, attach the following notices to the program. It is safest
+to attach them to the start of each source file to most effectively
+state the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+ <one line to give the program's name and a brief idea of what it does.>
+ Copyright (C) <year> <name of author>
+
+ This program is free software: you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see <https://www.gnu.org/licenses/>.
+
+Also add information on how to contact you by electronic and paper mail.
+
+ If the program does terminal interaction, make it output a short
+notice like this when it starts in an interactive mode:
+
+ <program> Copyright (C) <year> <name of author>
+ This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
+ This is free software, and you are welcome to redistribute it
+ under certain conditions; type `show c' for details.
+
+The hypothetical commands `show w' and `show c' should show the appropriate
+parts of the General Public License. Of course, your program's commands
+might be different; for a GUI interface, you would use an "about box".
+
+ You should also get your employer (if you work as a programmer) or school,
+if any, to sign a "copyright disclaimer" for the program, if necessary.
+For more information on this, and how to apply and follow the GNU GPL, see
+<https://www.gnu.org/licenses/>.
+
+ The GNU General Public License does not permit incorporating your program
+into proprietary programs. If your program is a subroutine library, you
+may consider it more useful to permit linking proprietary applications with
+the library. If this is what you want to do, use the GNU Lesser General
+Public License instead of this License. But first, please read
+<https://www.gnu.org/licenses/why-not-lgpl.html>.
diff --git a/Makefile b/Makefile
new file mode 100644
index 0000000..1c42ac7
--- /dev/null
+++ b/Makefile
@@ -0,0 +1,44 @@
+.PHONY: install run debug clean lint lint-strict
+
+MAIN = src/main.py
+VENV_DIR = .venv
+PYTHON = python3
+VENV_PYTHON = $(VENV_DIR)/bin/python3
+VENV_PIP = $(VENV_DIR)/bin/pip
+
+install: env
+ $(VENV_PYTHON) -m pip install -r requirements.txt
+
+env:
+ $(PYTHON) -m venv $(VENV_DIR)
+
+run:
+ @if [ ! -d "$(VENV_DIR)" ]; then \
+ echo "Error: Virtual environment not found. Run 'make install' first." >&2; \
+ exit 1; \
+ fi
+ $(VENV_PYTHON) $(MAIN) $(MAP)
+
+debug:
+ $(PYTHON) -m pdb $(MAIN) $(MAP)
+
+clean:
+ rm -fr $(VENV_DIR)
+ rm -fr .mypy_cache
+ rm -fr __pycache__
+
+lint:
+ flake8 .
+ mypy . \
+ --warn-return-any \
+ --warn-unused-ignores \
+ --ignore-missing-imports \
+ --disallow-untyped-defs \
+ --check-untyped-defs
+
+lint-strict:
+ flake8 .
+ mypy . --strict
+
+tags:
+ ctags src/*py
diff --git a/README b/README
new file mode 100644
index 0000000..7d9a109
--- /dev/null
+++ b/README
@@ -0,0 +1,209 @@
+## Description
+
+This a Multi-Agent Path Finding (MAPF) algorithm.
+
+An exercise I did at school to learn about MAPF.
+
+The aim is to route agents through nodes from 'start' to 'goal'.
+
+Nodes can be of type NORMAL, RESTRICTED, PRIORITY or BLOCKED.
+
+See 'Algorithm explanation' for more details.
+
+## Algorithm explanation
+
+- the program first computes the shortest path using Djikstra algorithm
+- then, starts sending agents through the shortest-path
+- if an agent cannot move to its next node, then the program recomputes a
+ shortest-path for that specific agent
+- if no shortest path is possible, the program skips to next agent
+
+### RESTRICTED node
+
+If a node is RESTRICTED:
+
+- the agent checks whether connection between two nodes has capacity and
+ whether the RESTRICTED node is `reserved`
+- if so:
+ - the agent reserves the RESTRICTED node and moves to the connection
+ between two nodes
+ - on the following turn, the agent moves to the RESTRICTED node and
+ unreserve the node
+
+### PRIORITY node
+
+The algorithm that computes the shortest path counts each PRIORITY node, and
+choose the path with the highest number of PRIORITY node at the end.
+
+### BLOCKED node
+
+BLOCKED node are skipped when computing the shortest path.
+
+## Instructions
+
+Create a virtual environment:
+
+ $ make env
+
+Install dependencies:
+
+ $ make install
+
+Run the program:
+
+ $ make run MAP=path/to/map
+
+also:
+
+ $ ./main.py path/to/map
+
+Clean:
+
+ $ make clean
+
+Debug:
+
+ $ make debug MAP=path/to/map
+
+Lint:
+
+ $ make lint
+
+and:
+
+ $ make lint-strict
+
+### About passing arguments to 'make run'
+
+Right now I use the variable $ARG.
+
+Another option is to use $(filter-out $@,$(MAKECMDGOALS)). What is this?
+
+The make file uses 'MAKECMDGOALS' to pass arguments to the program.
+
+However, 'MAKECMDGOALS' prepends the argument with the target. In our case that
+is 'run', which we don't want.
+
+So we want to filter the target, 'run', out.
+
+To do so we use 'filter-out', i.e. $(filter-out pattern, list)
+
+In Make the target is represented by the variable '$@'.
+
+So to remove the target we can write: $(filter-out $@,$(MAKECMDGOALS))
+
+Source: https://www.gnu.org/software/make/manual/html_node/Goals.html
+
+### About ctags in Vim
+
+If you want to use ctags with Vim, you can create a tag table file with:
+
+ $ make tags
+
+## Visual representation
+
+ ``` D1-waypoint1 D1-waypoint2 D2-waypoint1 D1-goal D2-waypoint2 D2-goal
+```
+
+The syntax is `D<drone_id>-<zone>|<connection>`, with color when provided.
+
+## Explanation of the network zone files
+
+### Input Format
+
+- The first line defines the number of drones (agents) using `nb_drones`:
+
+ ``` nb_drones: <number> ```
+
+- Zones are defined one per line using the following type prefixes:
+
+ ``` start_hub: <name> <x> <y> [metadata] end_hub: <name> <x> <y> [metadata]
+hub: <name> <x> <y> [metadata] ```
+
+ - `start_hub` marks the starting zone.
+ - `end_hub` marks the end zone.
+ - `hub` defines a regular zone.
+ - The connection syntax forbids dashes (`-`) in zone names.
+
+### Zone Metadata
+
+All metadata is optional and enclosed in square brackets (`[...]`). Metadata
+has the following default values:
+
+- `zone=<type>` — Default: `normal`
+- `color=<value>` — Default: `none`
+- `max_drones=<number>` — Default: `1`. The maximum number of drones that can
+ occupy the zone simultaneously.
+
+Tags inside brackets can appear in any order.
+
+### Zone Types
+
+- `normal` — Standard zone with a movement cost of 1 turn. This is the default.
+- `blocked` — Inaccessible zone. Drones must not enter or pass through this
+ zone. Any path using it is invalid.
+- `restricted` — Sensitive or dangerous zone. Movement to this zone costs 2
+ turns.
+- `priority` — Preferred zone. Movement to this zone costs 1 turn but should be
+ prioritized during pathfinding.
+
+### Colors
+
+- Colors are optional and can be used for visual representation, such as
+ terminal output or graphical displays.
+- Any valid single-word string can be used as a color value, for example:
+ - `red`
+ - `blue`
+ - `gray`
+- There is no fixed list of allowed colors.
+- When colors are specified, the implementation should provide visual feedback
+ through colored terminal output or a graphical representation.
+
+### Connections
+
+Connections are defined using the following syntax:
+
+``` connection: <name1>-<name2> [metadata] ```
+
+- Connections define a bidirectional edge between two zones.
+- The connection syntax forbids dashes (`-`) in zone names.
+- Optional metadata can be specified in square brackets (`[...]`):
+
+ - `max_link_capacity=<number>` — Default: `1`. The maximum number of drones
+ that can traverse the connection simultaneously.
+
+### Comments
+
+Comments start with `#` and are ignored:
+
+## Resources
+
+- the Wikipedia pages of Dijkstra and multi-agent pathfinding (MAPF)
+- on silencing prints in Make file:
+ https://www.gnu.org/software/make/manual/make.html#Echoing
+- on naming methods:
+ https://peps.python.org/pep-0008/#descriptive-naming-styles
+- on hashable objects: https://docs.python.org/3/glossary.html#term-hashable
+- on color syntax, escape char etc:
+ https://en.wikipedia.org/wiki/ANSI_escape_code
+- on 256-color: https://tintin.mudhalla.net/info/256color/
+- Xterm 256-color palette with
+ code://upload.wikimedia.org/wikipedia/commons/f/f5/Xterm-256color.svg
+
+## To improve
+
+- rewrite models.py without Pydantics (no dependencies)
+- move `colors` to their own class and file
+- optimize program for high number of drones
+
+### Misc.
+
+Command to get the list of colors from all maps:
+
+ grep -oiP 'color=\K[a-z]+' maps/**/*.txt | sort | uniq
+
+- -o, don't print the line, only the match
+- -i ignore case
+- \K look ahead, keep 'color=' but don't print it, -P (perl necessary)
+- [a-z]+ match or more lower case otherwise stop
+- sort to prepare for uniq
diff --git a/maps/README.md b/maps/README.md
new file mode 100644
index 0000000..11342f5
--- /dev/null
+++ b/maps/README.md
@@ -0,0 +1,77 @@
+# Fly-In: Drone Simulation Challenge Maps
+
+This collection contains carefully crafted maps designed to test different aspects of drone pathfinding algorithms, from basic navigation to complex optimization challenges.
+
+## Map Categories
+
+### 🟢 Easy Maps
+**Target**: Beginners, basic algorithm testing
+- `01_linear_path.txt` - Simple linear progression (2 drones)
+- `02_simple_fork.txt` - Basic path splitting (4 drones)
+- `03_basic_capacity.txt` - Introduction to capacity constraints (4 drones)
+
+### 🟡 Medium Maps
+**Target**: Intermediate challenges, algorithm optimization
+- `01_dead_end_trap.txt` - Dead ends that can trap naive algorithms (5 drones)
+- `02_circular_loop.txt` - Circular paths with restricted zones (6 drones)
+- `03_priority_puzzle.txt` - Optimal path selection with priority zones (5 drones)
+
+### 🔴 Hard Maps
+**Target**: Advanced algorithms, stress testing
+- `01_maze_nightmare.txt` - Complex maze with multiple traps and loops (8 drones)
+- `02_capacity_hell.txt` - Extreme capacity constraints requiring careful timing (12 drones)
+- `03_ultimate_challenge.txt` - **THE ULTIMATE TEST** - All challenges combined (15 drones)
+
+### ⚫ Challenger Maps
+**Target**: Research and algorithmic limits exploration
+- `01_the_impossible_dream.txt` - **THE IMPOSSIBLE DREAM** - Quasi-unsolvable challenge (25 drones)
+
+> ⚠️ **WARNING**: Challenger maps are designed to push algorithmic limits and may not be solvable by most implementations. They are intended for research, stress testing, and algorithmic exploration rather than validation. The goal is to challenge the boundaries of what's possible, not to pass evaluation criteria.
+
+> 🏆 **CHALLENGE RECORD**: The reference implementation solves "The Impossible Dream" in **45 turns**. Can you beat this record? This serves as a benchmark for algorithmic optimization and provides a concrete goal for advanced implementations.
+
+## Challenge Types Covered
+
+### 🎯 **Dead End Traps**
+Maps contain paths that lead nowhere, testing if algorithms can backtrack or avoid getting stuck.
+
+### 🔄 **Circular Loops**
+Cycles in the graph that can cause infinite loops in poorly designed algorithms.
+
+### ⚡ **Capacity Constraints**
+- Zone capacity limits (max_drones)
+- Connection capacity limits (max_link_capacity)
+- Timing-based bottlenecks
+
+### 🚀 **Zone Type Optimization**
+- `normal`: Standard 1-turn movement
+- `restricted`: 2-turn movement (slow but sometimes necessary)
+- `priority`: 1-turn movement but should be preferred
+- `blocked`: Completely inaccessible
+
+### 🧩 **Complex Topology**
+- Multiple valid paths with different costs
+- Convergence points requiring coordination
+- Multi-layer challenges
+
+## Testing Strategy
+
+1. **Start with Easy**: Ensure basic functionality works
+2. **Progress to Medium**: Test algorithm robustness
+3. **Challenge with Hard**: Stress test optimization and edge cases
+4. **Ultimate Test**: `03_ultimate_challenge.txt` combines all difficulties
+
+## Expected Behavior
+
+All maps are designed to be solvable with a well-implemented algorithm. However:
+
+- **Easy maps**: Should solve quickly with any reasonable approach
+- **Medium maps**: May require backtracking, path optimization, or capacity management
+- **Hard maps**: Demand sophisticated algorithms with proper conflict resolution and optimization
+
+## Performance Benchmarks
+
+- **Easy**: < 10 simulation turns typically
+- **Medium**: 10-30 simulation turns depending on optimization
+- **Hard**: 30+ simulation turns, focus on finding valid solutions
+- **Challenger**: **Record to beat: 45 turns** for "The Impossible Dream" - designed for algorithmic research
diff --git a/maps/challenger/01_the_impossible_dream.txt b/maps/challenger/01_the_impossible_dream.txt
new file mode 100644
index 0000000..b15afe0
--- /dev/null
+++ b/maps/challenger/01_the_impossible_dream.txt
@@ -0,0 +1,189 @@
+# CHALLENGER LEVEL: THE IMPOSSIBLE DREAM
+# WARNING: This map is designed to be extremely challenging and may not be solvable
+# by most algorithms. It's intended as a stress test and research challenge.
+# The goal is NOT to validate this map but to push algorithmic limits.
+
+nb_drones: 25
+
+# === LAYER 0: The Nightmare Begins ===
+start_hub: start 0 0 [color=green]
+
+# Single-file entry gates (extreme bottleneck)
+hub: gate_hell1 2 0 [color=red max_drones=1]
+hub: gate_hell2 3 0 [color=red max_drones=1]
+hub: gate_hell3 4 0 [color=red max_drones=1]
+hub: gate_hell4 5 0 [color=red max_drones=1]
+hub: gate_hell5 6 0 [color=red max_drones=1]
+
+# === LAYER 1: The Maze of Despair ===
+# Multiple interconnected dead ends and loops
+hub: maze_trap_a1 2 1 [color=purple]
+hub: maze_trap_a2 3 1 [color=purple]
+hub: maze_trap_a3 4 1 [color=purple]
+hub: maze_dead_a 5 1 [color=black]
+
+hub: maze_trap_b1 2 -1 [color=purple]
+hub: maze_trap_b2 3 -1 [color=purple]
+hub: maze_trap_b3 4 -1 [color=purple]
+hub: maze_dead_b 5 -1 [color=black]
+
+hub: maze_loop1 2 2 [zone=restricted color=brown]
+hub: maze_loop2 3 2 [zone=restricted color=brown]
+hub: maze_loop3 4 2 [zone=restricted color=brown]
+hub: maze_loop4 5 2 [zone=restricted color=brown]
+hub: maze_loop5 6 2 [zone=restricted color=brown]
+hub: maze_loop6 6 1 [zone=restricted color=brown]
+
+# === LAYER 2: The Capacity Nightmare ===
+hub: micro_gate1 7 0 [color=orange max_drones=1]
+hub: micro_gate2 8 0 [color=orange max_drones=1]
+hub: micro_gate3 9 0 [color=orange max_drones=1]
+
+# Overflow areas with terrible costs
+hub: overflow_hell1 7 1 [zone=restricted color=maroon max_drones=2]
+hub: overflow_hell2 8 1 [zone=restricted color=maroon max_drones=2]
+hub: overflow_hell3 9 1 [zone=restricted color=maroon max_drones=2]
+hub: overflow_hell4 7 -1 [zone=restricted color=maroon max_drones=2]
+hub: overflow_hell5 8 -1 [zone=restricted color=maroon max_drones=2]
+hub: overflow_hell6 9 -1 [zone=restricted color=maroon max_drones=2]
+
+# === LAYER 3: The False Hope Section ===
+# Priority zones that lead to more traps
+hub: false_hope1 10 0 [zone=priority color=gold max_drones=3]
+hub: false_hope2 11 0 [zone=priority color=gold max_drones=2]
+hub: false_hope3 12 0 [zone=priority color=gold max_drones=1]
+
+# More dead ends disguised as good paths
+hub: priority_trap1 10 1 [zone=priority color=gold]
+hub: priority_trap2 11 1 [zone=priority color=gold]
+hub: priority_dead 12 1 [color=black]
+
+hub: priority_trap3 10 -1 [zone=priority color=gold]
+hub: priority_trap4 11 -1 [zone=priority color=gold]
+hub: priority_dead2 12 -1 [color=black]
+
+# === LAYER 4: The Convergence Hell ===
+# Multiple restricted paths that must merge
+hub: conv_restricted1 13 2 [zone=restricted color=darkred max_drones=1]
+hub: conv_restricted2 14 2 [zone=restricted color=darkred max_drones=1]
+hub: conv_restricted3 15 2 [zone=restricted color=darkred max_drones=1]
+
+hub: conv_restricted4 13 0 [zone=restricted color=darkred max_drones=1]
+hub: conv_restricted5 14 0 [zone=restricted color=darkred max_drones=1]
+hub: conv_restricted6 15 0 [zone=restricted color=darkred max_drones=1]
+
+hub: conv_restricted7 13 -2 [zone=restricted color=darkred max_drones=1]
+hub: conv_restricted8 14 -2 [zone=restricted color=darkred max_drones=1]
+hub: conv_restricted9 15 -2 [zone=restricted color=darkred max_drones=1]
+
+# === LAYER 5: The Final Gauntlet of Doom ===
+hub: final_merge 16 0 [color=violet max_drones=5]
+hub: final_torture1 17 0 [color=crimson max_drones=2]
+hub: final_torture2 18 0 [color=crimson max_drones=1]
+hub: final_torture3 19 0 [color=crimson max_drones=1]
+hub: final_torture4 20 0 [color=crimson max_drones=1]
+hub: final_torture5 21 0 [color=crimson max_drones=1]
+
+# The ultimate goal
+end_hub: impossible_goal 23 0 [color=rainbow]
+
+# === CONNECTIONS: The Web of Suffering ===
+
+# Layer 0 connections (bottleneck hell)
+connection: start-gate_hell1 [max_link_capacity=1]
+connection: gate_hell1-gate_hell2 [max_link_capacity=1]
+connection: gate_hell2-gate_hell3 [max_link_capacity=1]
+connection: gate_hell3-gate_hell4 [max_link_capacity=1]
+connection: gate_hell4-gate_hell5 [max_link_capacity=1]
+
+# Layer 1 connections (maze of despair)
+connection: gate_hell1-maze_trap_a1
+connection: gate_hell2-maze_trap_b1
+connection: gate_hell3-maze_loop1
+
+connection: maze_trap_a1-maze_trap_a2
+connection: maze_trap_a2-maze_trap_a3
+connection: maze_trap_a3-maze_dead_a
+
+connection: maze_trap_b1-maze_trap_b2
+connection: maze_trap_b2-maze_trap_b3
+connection: maze_trap_b3-maze_dead_b
+
+connection: maze_loop1-maze_loop2
+connection: maze_loop2-maze_loop3
+connection: maze_loop3-maze_loop4
+connection: maze_loop4-maze_loop5
+connection: maze_loop5-maze_loop6
+connection: maze_loop6-maze_loop1
+
+# Escape routes from maze (very limited)
+connection: maze_trap_a2-micro_gate1
+connection: maze_trap_b2-micro_gate1
+connection: maze_loop3-micro_gate2
+
+# Layer 2 connections (capacity nightmare)
+connection: gate_hell5-micro_gate1
+connection: micro_gate1-micro_gate2
+connection: micro_gate2-micro_gate3
+
+# Overflow hell connections
+connection: micro_gate1-overflow_hell1
+connection: micro_gate2-overflow_hell2
+connection: micro_gate3-overflow_hell3
+connection: micro_gate1-overflow_hell4
+connection: micro_gate2-overflow_hell5
+connection: micro_gate3-overflow_hell6
+
+connection: overflow_hell1-overflow_hell2
+connection: overflow_hell2-overflow_hell3
+connection: overflow_hell4-overflow_hell5
+connection: overflow_hell5-overflow_hell6
+
+connection: overflow_hell3-false_hope1
+connection: overflow_hell6-false_hope1
+
+# Layer 3 connections (false hope)
+connection: micro_gate3-false_hope1
+connection: false_hope1-false_hope2
+connection: false_hope2-false_hope3
+
+# False hope traps
+connection: false_hope1-priority_trap1
+connection: false_hope2-priority_trap2
+connection: false_hope3-priority_dead
+
+connection: false_hope1-priority_trap3
+connection: false_hope2-priority_trap4
+connection: false_hope3-priority_dead2
+
+connection: priority_trap1-priority_trap2
+connection: priority_trap3-priority_trap4
+
+# Layer 4 connections (convergence hell)
+connection: false_hope3-conv_restricted1
+connection: false_hope3-conv_restricted4
+connection: false_hope3-conv_restricted7
+
+connection: conv_restricted1-conv_restricted2
+connection: conv_restricted2-conv_restricted3
+connection: conv_restricted4-conv_restricted5
+connection: conv_restricted5-conv_restricted6
+connection: conv_restricted7-conv_restricted8
+connection: conv_restricted8-conv_restricted9
+
+connection: conv_restricted3-final_merge
+connection: conv_restricted6-final_merge
+connection: conv_restricted9-final_merge
+
+# Layer 5 connections (final gauntlet)
+connection: final_merge-final_torture1
+connection: final_torture1-final_torture2
+connection: final_torture2-final_torture3
+connection: final_torture3-final_torture4
+connection: final_torture4-final_torture5
+connection: final_torture5-impossible_goal
+
+# Emergency bypass routes (extremely expensive)
+connection: overflow_hell1-conv_restricted1
+connection: overflow_hell4-conv_restricted7
+connection: priority_trap1-conv_restricted4
diff --git a/maps/easy/01_linear_path.txt b/maps/easy/01_linear_path.txt
new file mode 100644
index 0000000..04588cf
--- /dev/null
+++ b/maps/easy/01_linear_path.txt
@@ -0,0 +1,11 @@
+# Easy Level 1: Simple linear path
+nb_drones: 2
+
+start_hub: start 0 0 [color=green]
+hub: waypoint1 1 0 [color=blue]
+hub: waypoint2 2 0 [color=blue]
+end_hub: goal 3 0 [color=red]
+
+connection: start-waypoint1
+connection: waypoint1-waypoint2
+connection: waypoint2-goal
diff --git a/maps/easy/02_simple_fork.txt b/maps/easy/02_simple_fork.txt
new file mode 100644
index 0000000..06f1eb1
--- /dev/null
+++ b/maps/easy/02_simple_fork.txt
@@ -0,0 +1,14 @@
+# Easy Level 2: Simple fork with two paths
+nb_drones: 4
+
+start_hub: start 0 0 [color=green]
+hub: junction 1 0 [color=yellow max_drones=2]
+hub: path_a 2 1 [color=blue]
+hub: path_b 2 -1 [color=blue]
+end_hub: goal 3 0 [color=red]
+
+connection: start-junction [max_link_capacity=2]
+connection: junction-path_a
+connection: junction-path_b
+connection: path_a-goal
+connection: path_b-goal
diff --git a/maps/easy/03_basic_capacity.txt b/maps/easy/03_basic_capacity.txt
new file mode 100644
index 0000000..ccc3003
--- /dev/null
+++ b/maps/easy/03_basic_capacity.txt
@@ -0,0 +1,11 @@
+# Easy Level 3: Basic capacity management
+nb_drones: 4
+
+start_hub: start 0 0 [color=green]
+hub: bottleneck 1 0 [color=orange max_drones=2]
+hub: wide_area 2 0 [color=blue max_drones=3]
+end_hub: goal 3 0 [color=red]
+
+connection: start-bottleneck [max_link_capacity=4]
+connection: bottleneck-wide_area [max_link_capacity=4]
+connection: wide_area-goal [max_link_capacity=4]
diff --git a/maps/hard/01_maze_nightmare.txt b/maps/hard/01_maze_nightmare.txt
new file mode 100644
index 0000000..b32ce73
--- /dev/null
+++ b/maps/hard/01_maze_nightmare.txt
@@ -0,0 +1,52 @@
+# Hard Level 1: Complex maze with multiple dead ends and loops
+nb_drones: 8
+
+start_hub: start 0 0 [color=green]
+hub: maze_a1 1 0 [color=blue max_drones=2]
+hub: maze_a2 2 0 [color=blue]
+hub: maze_b1 1 1 [color=blue]
+hub: maze_b2 2 1 [color=blue max_drones=2]
+hub: maze_c1 1 2 [color=blue]
+hub: maze_c2 3 1 [color=blue max_drones=2]
+hub: dead_end1 0 1 [color=red max_drones=2]
+hub: dead_end2 0 2 [color=red]
+hub: dead_end3 2 -1 [color=red]
+hub: trap_loop1 4 0 [zone=restricted color=orange]
+hub: trap_loop2 4 2 [zone=restricted color=orange]
+hub: bottleneck 5 1 [color=yellow max_drones=2]
+hub: final_stretch1 6 0 [zone=priority color=cyan]
+hub: final_stretch2 6 1 [zone=priority color=cyan]
+hub: final_stretch3 6 2 [zone=priority color=cyan]
+end_hub: goal 7 1 [color=green]
+
+# Main path connections
+connection: start-maze_a1 [max_link_capacity=2]
+connection: maze_a1-maze_a2
+connection: maze_a1-maze_b1
+connection: maze_b1-maze_b2
+connection: maze_b2-maze_c2
+connection: maze_c2-maze_a2
+connection: maze_c2-bottleneck
+
+# Dead end traps
+connection: start-dead_end1 [max_link_capacity=2]
+connection: dead_end1-dead_end2
+connection: maze_a2-dead_end3
+
+# Trap loops
+connection: maze_a2-trap_loop1
+connection: trap_loop1-trap_loop2
+connection: trap_loop2-maze_c1
+
+# Alternative paths
+connection: maze_b1-maze_c1
+connection: maze_c1-maze_b2
+connection: maze_b2-maze_a2
+
+# Final stretch
+connection: bottleneck-final_stretch1
+connection: bottleneck-final_stretch2
+connection: bottleneck-final_stretch3
+connection: final_stretch1-goal
+connection: final_stretch2-goal
+connection: final_stretch3-goal
diff --git a/maps/hard/02_capacity_hell.txt b/maps/hard/02_capacity_hell.txt
new file mode 100644
index 0000000..a7d8856
--- /dev/null
+++ b/maps/hard/02_capacity_hell.txt
@@ -0,0 +1,51 @@
+# Hard Level 2: Extreme capacity constraints with timing challenges
+nb_drones: 12
+
+start_hub: start 0 -1 [color=green]
+hub: gate1 1 0 [color=orange max_drones=1]
+hub: gate2 2 0 [color=orange max_drones=1]
+hub: gate3 3 0 [color=orange max_drones=1]
+hub: waiting_area1 1 1 [color=blue max_drones=4]
+hub: waiting_area2 2 1 [color=blue max_drones=4]
+hub: waiting_area3 3 1 [color=blue max_drones=4]
+hub: restricted_tunnel1 4 0 [zone=restricted color=red max_drones=2]
+hub: restricted_tunnel2 5 0 [zone=restricted color=red max_drones=2]
+hub: restricted_tunnel3 6 0 [zone=restricted color=red max_drones=2]
+hub: priority_bypass1 3 2 [zone=priority color=cyan max_drones=3]
+hub: priority_bypass2 4 2 [zone=priority color=cyan max_drones=3]
+hub: convergence 7 0 [color=yellow max_drones=6]
+hub: final_bottleneck 8 0 [color=orange max_drones=3]
+end_hub: goal 9 0 [color=green]
+
+# Sequential gates (major bottleneck)
+connection: start-gate1 [max_link_capacity=1]
+connection: start-gate2 [max_link_capacity=1]
+connection: start-gate3 [max_link_capacity=1]
+connection: gate1-gate2 [max_link_capacity=1]
+connection: gate2-gate3 [max_link_capacity=1]
+
+# Waiting areas for queue management
+connection: gate1-waiting_area1
+connection: gate2-waiting_area2
+connection: gate3-waiting_area3
+connection: waiting_area1-waiting_area2
+connection: waiting_area2-waiting_area3
+
+# Restricted tunnel path (slow but more capacity)
+connection: gate3-restricted_tunnel1
+connection: restricted_tunnel1-restricted_tunnel2
+connection: restricted_tunnel2-restricted_tunnel3
+connection: restricted_tunnel3-convergence
+
+# Priority bypass (fast but limited capacity)
+connection: waiting_area1-priority_bypass1
+connection: waiting_area2-priority_bypass2
+connection: priority_bypass1-priority_bypass2
+connection: priority_bypass2-convergence [max_link_capacity=2]
+
+# Final challenge
+connection: convergence-final_bottleneck [max_link_capacity=3]
+connection: final_bottleneck-goal
+
+# Emergency overflow paths
+connection: waiting_area3-convergence
diff --git a/maps/hard/03_ultimate_challenge.txt b/maps/hard/03_ultimate_challenge.txt
new file mode 100644
index 0000000..6dea02f
--- /dev/null
+++ b/maps/hard/03_ultimate_challenge.txt
@@ -0,0 +1,98 @@
+# Hard Level 3: THE ULTIMATE CHALLENGE - All tricks combined
+nb_drones: 15
+
+start_hub: start 0 0 [color=green]
+
+# Layer 1: Initial distribution nightmare
+hub: dist_gate1 1 -1 [color=orange]
+hub: dist_gate2 1 1 [color=orange]
+hub: dist_gate3 1 0 [color=orange]
+
+# Layer 2: Dead end maze with loops
+hub: maze_trap1 1 2 [color=red]
+hub: maze_trap2 2 2 [color=red max_drones=3]
+hub: maze_loop1 2 1 [color=purple max_drones=3]
+hub: maze_loop2 3 1 [color=purple max_drones=3]
+hub: maze_loop3 4 1 [color=purple max_drones=3]
+hub: maze_loop4 3 2 [color=purple max_drones=3]
+hub: maze_correct 2 0 [color=blue max_drones=3]
+
+# Layer 3: Capacity nightmare section
+hub: bottleneck1 3 0 [color=yellow max_drones=2]
+hub: bottleneck2 4 0 [color=yellow max_drones=1]
+hub: overflow1 3 -1 [zone=restricted color=orange max_drones=3]
+hub: overflow2 4 -1 [zone=restricted color=orange max_drones=3]
+
+# Layer 4: Priority puzzle with traps
+hub: priority_hub 5 0 [zone=priority color=cyan max_drones=4]
+hub: priority_trap1 5 1 [zone=priority color=cyan]
+hub: priority_trap2 6 1 [zone=priority color=cyan]
+hub: priority_dead_end 6 2 [color=red]
+hub: priority_correct 6 0 [zone=priority color=cyan max_drones=3]
+
+# Layer 5: Multi-path convergence hell
+hub: conv_restricted1 7 0 [zone=restricted color=brown max_drones=2]
+hub: conv_restricted2 8 0 [zone=restricted color=brown max_drones=2]
+hub: conv_normal1 7 -1 [color=blue max_drones=3]
+hub: conv_normal2 8 -1 [color=blue max_drones=3]
+hub: conv_priority1 7 1 [zone=priority color=lime max_drones=2]
+hub: conv_priority2 8 1 [zone=priority color=lime max_drones=2]
+
+# Layer 6: Final gauntlet
+hub: final_merge 9 0 [color=magenta max_drones=8]
+hub: final_gate1 10 0 [color=orange max_drones=3]
+hub: final_gate2 11 0 [color=orange max_drones=2]
+hub: final_gate3 12 0 [color=orange max_drones=1]
+
+end_hub: goal 13 0 [color=gold]
+
+# Layer 1 connections
+connection: start-dist_gate1
+connection: start-dist_gate2 [max_link_capacity=2]
+connection: start-dist_gate3
+
+# Layer 2 connections - maze with traps
+connection: dist_gate1-maze_correct
+connection: dist_gate2-maze_trap1 [max_link_capacity=2]
+connection: dist_gate3-maze_loop1
+connection: maze_trap1-maze_trap2 [max_link_capacity=2]
+connection: maze_loop1-maze_loop2
+connection: maze_loop2-maze_loop3
+connection: maze_loop3-maze_loop4
+connection: maze_loop4-maze_loop1
+connection: maze_loop2-maze_correct
+
+# Layer 3 connections - capacity nightmare
+connection: maze_correct-bottleneck1 [max_link_capacity=2]
+connection: bottleneck1-bottleneck2
+connection: bottleneck1-overflow1
+connection: overflow1-overflow2 [max_link_capacity=2]
+connection: overflow2-bottleneck2
+
+# Layer 4 connections - priority puzzle
+connection: bottleneck2-priority_hub
+connection: priority_hub-priority_trap1
+connection: priority_hub-priority_correct
+connection: priority_trap1-priority_trap2
+connection: priority_trap2-priority_dead_end
+connection: priority_correct-conv_restricted1
+connection: priority_correct-conv_normal1
+connection: priority_correct-conv_priority1
+
+# Layer 5 connections - multi-path convergence
+connection: conv_restricted1-conv_restricted2
+connection: conv_normal1-conv_normal2
+connection: conv_priority1-conv_priority2 [max_link_capacity=2]
+connection: conv_restricted2-final_merge
+connection: conv_normal2-final_merge
+connection: conv_priority2-final_merge [max_link_capacity=2]
+
+# Layer 6 connections - final gauntlet
+connection: final_merge-final_gate1 [max_link_capacity=3]
+connection: final_gate1-final_gate2 [max_link_capacity=2]
+connection: final_gate2-final_gate3 [max_link_capacity=2]
+connection: final_gate3-goal [max_link_capacity=2]
+
+# Emergency bypass (very expensive)
+connection: overflow2-conv_normal1
+connection: priority_hub-conv_priority1
diff --git a/maps/medium/01_dead_end_trap.txt b/maps/medium/01_dead_end_trap.txt
new file mode 100644
index 0000000..c90a3b6
--- /dev/null
+++ b/maps/medium/01_dead_end_trap.txt
@@ -0,0 +1,15 @@
+# Medium Level 1: Dead end trap - drones might get stuck
+nb_drones: 5
+
+start_hub: start 0 0 [color=green]
+hub: junction 1 0 [color=yellow max_drones=2]
+hub: dead_end 1 1 [color=red]
+hub: correct_path 2 0 [color=blue]
+hub: intermediate 3 0 [color=blue]
+end_hub: goal 4 0 [color=green]
+
+connection: start-junction [max_link_capacity=2]
+connection: junction-dead_end
+connection: junction-correct_path
+connection: correct_path-intermediate
+connection: intermediate-goal
diff --git a/maps/medium/02_circular_loop.txt b/maps/medium/02_circular_loop.txt
new file mode 100644
index 0000000..794909c
--- /dev/null
+++ b/maps/medium/02_circular_loop.txt
@@ -0,0 +1,18 @@
+# Medium Level 2: Circular loop with restricted zones
+nb_drones: 6
+
+start_hub: start 0 0 [color=green]
+hub: loop_a 1 0 [color=orange max_drones=2]
+hub: loop_b 2 0 [color=orange max_drones=2]
+hub: loop_c 2 1 [color=orange max_drones=2]
+hub: loop_d 1 1 [color=orange max_drones=2]
+hub: exit_point 3 0 [zone=restricted color=blue]
+end_hub: goal 4 0 [color=red]
+
+connection: start-loop_a [max_link_capacity=2]
+connection: loop_a-loop_b [max_link_capacity=2]
+connection: loop_b-loop_c [max_link_capacity=2]
+connection: loop_c-loop_d [max_link_capacity=2]
+connection: loop_d-loop_a [max_link_capacity=2]
+connection: loop_b-exit_point
+connection: exit_point-goal
diff --git a/maps/medium/03_priority_puzzle.txt b/maps/medium/03_priority_puzzle.txt
new file mode 100644
index 0000000..04f35f8
--- /dev/null
+++ b/maps/medium/03_priority_puzzle.txt
@@ -0,0 +1,18 @@
+# Medium Level 3: Priority zones create optimal path challenges
+nb_drones: 5
+
+start_hub: start 0 0 [color=green]
+hub: slow_path1 1 -1 [zone=restricted color=red]
+hub: slow_path2 2 -1 [color=red]
+hub: fast_junction 1 0 [zone=priority color=blue max_drones=2]
+hub: fast_path 2 0 [zone=priority color=blue]
+hub: merge_point 3 0 [color=yellow max_drones=3]
+end_hub: goal 4 0 [color=green]
+
+connection: start-slow_path1
+connection: start-fast_junction
+connection: slow_path1-slow_path2
+connection: slow_path2-merge_point
+connection: fast_junction-fast_path
+connection: fast_path-merge_point
+connection: merge_point-goal [max_link_capacity=2]
diff --git a/requirements.txt b/requirements.txt
new file mode 100644
index 0000000..11ba482
--- /dev/null
+++ b/requirements.txt
@@ -0,0 +1,2 @@
+pydantic>=2.0,<3.0
+pygame>=2.6.1
diff --git a/src/drone.py b/src/drone.py
new file mode 100644
index 0000000..d47a08a
--- /dev/null
+++ b/src/drone.py
@@ -0,0 +1,77 @@
+"""Class and methods for a drone"""
+
+from dataclasses import dataclass, field
+from typing import List
+from graph import Graph
+from models import Zone, Connection
+from pathfinder import PathResult
+
+
+@dataclass
+class Drone:
+ """
+ Represent one drone travelling along a fixed path
+ Initialize path as an empty list using the default factory of
+ library dataclass.
+ """
+
+ id_: int
+ path: List[str] = field(default_factory=list)
+ path_index: int = 0
+ delivered: bool = False
+ in_transit: bool = False
+
+ # read-only, no parentheses needed to call
+ @property
+ def current_zone(self) -> str:
+ """Return the drone's current zone."""
+ return self.path[self.path_index]
+
+ @property
+ def next_zone(self) -> str | None:
+ """Return the next zone, or None if the drone is delivered."""
+ next_index = self.path_index + 1
+
+ if next_index >= len(self.path):
+ return None
+
+ return self.path[next_index]
+
+ def move(self) -> str | None:
+ """Move the drone to its next zone."""
+ dest = self.next_zone
+
+ if dest is None:
+ self.delivered = True
+ return None
+
+ self.path_index += 1
+
+ if self.path_index == len(self.path) - 1:
+ self.delivered = True
+
+ return dest
+
+ def leave_transit(self, src: Zone, dest: Zone, graph: Graph) -> None:
+ """Leave transit to restricted zone"""
+ self.move()
+ connection = graph.get_connection(src, dest)
+ connection.congested = False
+ dest.congested = False
+ connection.link_occupancy -=1
+ dest.occupancy += 1
+ dest.reservation -= 1
+ self.in_transit = False
+
+ def update_path(self, path_result: PathResult) -> None:
+ """ Update drone's path"""
+ self.path = path_result.path
+ self.path_index = 0
+
+ def update_dest(self, graph: Graph) -> Zone:
+ """"Return drone's destination"""
+ if self.next_zone is None:
+ raise KeyError("That is it! No next zone")
+ dest_name: str = self.next_zone
+ dest: Zone = graph.get_zone(dest_name)
+ return dest
diff --git a/src/graph.py b/src/graph.py
new file mode 100644
index 0000000..c986c16
--- /dev/null
+++ b/src/graph.py
@@ -0,0 +1,131 @@
+"""Converts map info into a graph"""
+
+from models import MapData, Zone, Connection
+from typing import List
+
+
+class Graph:
+ """Represents zone connectivity for a drone map."""
+
+ def __init__(
+ self,
+ drone_map: MapData
+ ) -> None:
+ self._zones: dict[str, Zone] = {}
+ # a list of adjacent zones per zone
+ self._adjacency: dict[str, List[Zone]] = {}
+ # a list of connections per zone
+ self._connections: dict[str, List[Connection]] = {}
+ self._build(drone_map)
+
+ def _build(
+ self,
+ drone_map: MapData
+ ) -> None:
+ """Build a bidirectional adjacency list.
+
+ There is no duplicate connection i.e. only a-b and no b-a
+ so when we append a connection to a zone, we also need to
+ append the reverse connection to its destination.
+ """
+ all_zones = [
+ drone_map.start,
+ drone_map.end,
+ *drone_map.zones,
+ ]
+
+ # create dictionaries' keys
+ for zone in all_zones:
+ self._zones[zone.name] = zone
+ self._adjacency[zone.name] = []
+ self._connections[zone.name] = []
+
+ for connection in drone_map.connections:
+ src = connection.src
+ dest = connection.dest
+
+ self._adjacency[src.name].append(dest)
+ self._adjacency[dest.name].append(src)
+
+ self._connections[src.name].append(connection)
+ reverse = Connection(
+ src=dest,
+ dest=src,
+ link_capacity=connection.link_capacity
+ )
+ self._connections[dest.name].append(reverse)
+
+ def neighbours(
+ self,
+ zone_name: str
+ ) -> List[Zone]:
+ """Return zones directly connected to the given zone."""
+ if zone_name not in self._adjacency:
+ raise KeyError(f"Unknown zone: {zone_name}")
+
+ return self._adjacency[zone_name]
+
+ def get_link_capacity(
+ self,
+ src: Zone,
+ dest: Zone
+ ) -> int:
+ """Return the max capacity for a link between two zones."""
+ if src.name not in self._adjacency:
+ raise KeyError(f"Unknown zone: {src.name}")
+ if dest.name not in self._adjacency:
+ raise KeyError(f"Unknown zone: {dest.name}")
+ connection = self.get_connection(src, dest)
+ return connection.link_capacity
+
+ def get_link_occupancy(
+ self,
+ src: Zone,
+ dest: Zone
+ ) -> int:
+ """Return the occupancy for a link between two zones."""
+ if src.name not in self._adjacency:
+ raise KeyError(f"Unknown zone: {src.name}")
+ if dest.name not in self._adjacency:
+ raise KeyError(f"Unknown zone: {dest.name}")
+ connection = self.get_connection(src, dest)
+ return connection.link_occupancy
+
+ def get_zone(
+ self,
+ zone_name: str
+ ) -> Zone:
+ """Return a zone by name."""
+ return self._zones[zone_name]
+
+ def get_start(self) -> Zone:
+ """Return the end zone"""
+ zones = self._zones
+ for zone in zones.values():
+ if zone.is_start is True:
+ return zone
+ raise KeyError(f"No zone {zone}")
+
+ def get_end(self) -> Zone:
+ """Return the start zone"""
+ zones = self._zones
+ for zone in zones.values():
+ if zone.is_end is True:
+ return zone
+ raise KeyError(f"No zone {zone}")
+
+ def get_connection(
+ self,
+ src: Zone,
+ dest: Zone
+ ) -> Connection:
+ if src.name not in self._adjacency:
+ raise KeyError(f"Unknown zone: {src.name}")
+ if dest.name not in self._adjacency:
+ raise KeyError(f"Unknown zone: {dest.name}")
+ """Return the connection between two zones"""
+ connections = self._connections[src.name]
+ for connection in connections:
+ if connection.dest.name == dest.name:
+ return connection
+ raise KeyError(f"No connection between {src} and {dest}")
diff --git a/src/main.py b/src/main.py
new file mode 100644
index 0000000..faa7e96
--- /dev/null
+++ b/src/main.py
@@ -0,0 +1,52 @@
+#!/usr/bin/env python3
+from graph import Graph
+from parser import Parser
+from pathfinder import Pathfinder
+from scheduler import Scheduler
+import sys
+from visualiser import Visualiser
+
+
+def main() -> None:
+ """Parse a map,
+ create a graph,
+ find the shortest path,
+ run the simulation through the scheduler
+ """
+ if len(sys.argv) != 2:
+ print("Usage: './main.py <map_file>' or 'make run MAP=path/to/map'")
+ return
+
+ try:
+ parser = Parser()
+
+ drone_map = parser.parse_map()
+
+ graph = Graph(drone_map)
+
+ pathfinder = Pathfinder(graph)
+
+ result = pathfinder.find_path(
+ drone_map.start.name,
+ drone_map.end.name,
+ )
+
+ if result is None:
+ print("No valid path found.")
+ return
+
+ scheduler = Scheduler(
+ graph=graph,
+ path=result.path,
+ number_of_drones=drone_map.nb_drones,
+ )
+
+ scheduler.run()
+# Visualiser(graph, drone_map, scheduler).run()
+
+ except Exception as e:
+ print(e)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/src/models.py b/src/models.py
new file mode 100644
index 0000000..6af4d65
--- /dev/null
+++ b/src/models.py
@@ -0,0 +1,90 @@
+"""Classes for Zone, Connections and the map"""
+from enum import Enum
+from typing_extensions import Self
+
+from pydantic import BaseModel, Field, model_validator
+
+
+class ZoneType(str, Enum):
+ """Valid zone types."""
+
+ NORMAL = "normal"
+ BLOCKED = "blocked"
+ RESTRICTED = "restricted"
+ PRIORITY = "priority"
+
+
+class Zone(BaseModel):
+ """Represents a zone in the drone network."""
+
+ name: str = Field(min_length=1)
+ x: int
+ y: int
+ zone_type: ZoneType = Field(default=ZoneType.NORMAL)
+ color: str | None = None
+ max_drones: int = Field(default=1, ge=1)
+ is_start: bool = Field(default=False)
+ is_end: bool = Field(default=False)
+ connections: list[str] = Field(default_factory=list)
+ occupancy: int = Field(default=0, ge=0)
+ congested: bool = Field(default=False)
+ reservation: int = Field(default=0, ge=0)
+
+ @model_validator(mode="after")
+ def validate_name(self) -> Self:
+
+ # checking for space here is not so useful because parsing fails anyway
+ if " " in self.name or "-" in self.name:
+ raise ValueError("zone names must not contain spaces or dashes")
+
+ if self.zone_type != ZoneType.BLOCKED and self.max_drones == 0:
+ raise ValueError("A non-blocked zone type must have capacity of "
+ "at least one drone.")
+
+ return self
+
+
+class Connection(BaseModel):
+ """Represents bidirectional link between two connection."""
+
+ src: Zone
+ dest: Zone
+ link_capacity: int = Field(default=1, ge=0)
+ link_occupancy: int = Field(default=0, ge=0)
+ congested: bool = Field(default=False)
+
+ @model_validator(mode="after")
+ def validate_connection(self) -> Self:
+
+ if self.src == self.dest:
+ raise ValueError("a connection cannot connect a zone to itself")
+
+ if self.src.zone_type != ZoneType.BLOCKED \
+ and self.dest.zone_type != ZoneType.BLOCKED \
+ and self.link_capacity == 0:
+ raise ValueError("A connection to a non-blocked zone"
+ "must have a capacity of at least one drone.")
+
+ return self
+
+
+class MapData(BaseModel):
+ """All data needed to run a simulation."""
+
+ nb_drones: int = Field(gt=0)
+ start: Zone
+ end: Zone
+ zones: list[Zone]
+ connections: list[Connection]
+
+ @model_validator(mode="after")
+ def post_validate(self) -> Self:
+
+ same_name = self.start.name == self.end.name
+ same_position = (self.start.x == self.end.x
+ and self.start.y == self.end.y)
+
+ if self.start == self.end or same_name or same_position:
+ raise ValueError("Start and end zones cannot overlap.")
+
+ return self
diff --git a/src/parser.py b/src/parser.py
new file mode 100644
index 0000000..dffba84
--- /dev/null
+++ b/src/parser.py
@@ -0,0 +1,564 @@
+#!/usr/bin/env python3
+""" Parser for the file with specification for the map"""
+import argparse
+from argparse import Namespace
+from pathlib import Path
+
+from models import Connection, MapData, Zone, ZoneType
+
+
+class ParseError(Exception):
+ """Parsing errors"""
+ pass
+
+
+class Parser:
+ """Parse a drone map file into a MapData instance."""
+
+ VALID_KEYS = {
+ "nb_drones",
+ "start_hub",
+ "end_hub",
+ "hub",
+ "connection",
+ }
+
+ def __init__(self) -> None:
+ self.args = self.parse_args()
+
+ def parse_map(self) -> MapData:
+ """Parse the input file and return a validated MapData."""
+
+ lines = self._read_file()
+ lines = self._clean_lines(lines)
+
+ self._check_keys_valid(lines)
+
+ nb_drones = self._parse_nb_drones(lines)
+
+ start = self._parse_start_end_zone(
+ lines,
+ nb_drones,
+ is_start=True,
+ )
+
+ end = self._parse_start_end_zone(
+ lines,
+ nb_drones,
+ is_start=False,
+ )
+
+ zones = self._parse_zones(
+ lines,
+ nb_drones,
+ start,
+ end,
+ )
+
+ connections = self._parse_connections(
+ lines,
+ zones,
+ start,
+ end,
+ )
+ return MapData(
+ nb_drones=nb_drones,
+ start=start,
+ end=end,
+ zones=zones,
+ connections=connections,
+ )
+
+ def parse_args(self) -> Namespace:
+ """Parse command-line arguments and return a
+ 'method that runs the parser and places the
+ extracted data in a 'argparse.Namespace'
+ object' see argparse documention.
+ """
+
+ parser = argparse.ArgumentParser()
+ parser.add_argument(
+ "filename",
+ type=Path,
+ help="Path to the map file"
+ )
+ return parser.parse_args()
+
+ def _read_file(self) -> list[str]:
+ """Read all lines from the input file.
+ Returns a list of lines.
+ """
+
+ filename: Path = self.args.filename
+
+ if not filename.exists():
+ raise FileNotFoundError(
+ f"Map file not found: {filename}"
+ )
+
+ if not filename.is_file():
+ raise ValueError(
+ f"Not a regular file: {filename}"
+ )
+
+ try:
+ lines = filename.read_text().splitlines()
+ except PermissionError:
+ raise PermissionError(
+ f"Check the permission of file: {filename}"
+ )
+ except OSError:
+ raise OSError(
+ f"Unable to read map file: {filename}"
+ )
+
+ if not lines:
+ raise ValueError(
+ f"Map file is empty: {filename}"
+ )
+
+ return lines
+
+ def _clean_lines(self, lines: list[str]) -> list[str]:
+ """
+ Remove blank lines and comments.
+ Inline comments are also removed.
+ Returns a list of 'cleaned' lines.
+ """
+
+ cleaned: list[str] = []
+
+ for line in lines:
+ if line.startswith('#'):
+ continue
+
+ if line:
+ cleaned.append(line)
+
+ return cleaned
+
+ def _check_keys_valid(self, lines: list[str]) -> None:
+ """Check that every line starts with a supported map key.
+ The start_hub, end_hub, and nb_drones keys may each appear only once.
+ init seen_keys
+ add key to seen_keys
+ check whether new key is already in seen_keys
+
+ Second arg of split is 'maxsplit'.
+
+ See top of the file for VALID_KEYS.
+ """
+
+ unique_keys = {"start_hub", "end_hub", "nb_drones"}
+ seen_keys: set[str] = set()
+
+ for line in lines:
+ if ":" not in line:
+ raise ValueError(
+ f"Invalid line; expected '<key>: ...': {line}"
+ )
+
+ key = line.split(":", 1)[0].strip()
+
+ if key not in self.VALID_KEYS:
+ raise ValueError(
+ f"Unknown map key '{key}' in line: {line}"
+ )
+
+ if key in unique_keys:
+ if key in seen_keys:
+ raise ValueError(
+ f"Duplicate map key '{key}': {line}"
+ )
+
+ seen_keys.add(key)
+
+ def _parse_nb_drones(self, lines: list[str]) -> int:
+ """Extract and validate the number of drones."""
+
+ if not lines[0].startswith("nb_drones"):
+ raise ParseError(
+ "ParseError: The first line does not define"
+ "the number of drones."
+ )
+
+ value = lines[0].split(":", 1)[1].strip()
+
+ try:
+ nb_drones = int(value)
+ except ValueError:
+ raise ValueError(
+ f"Invalid number of drones: {value!r}"
+ )
+
+ if nb_drones <= 0:
+ raise ValueError(
+ "The number of drones must be greater than zero."
+ )
+
+ return nb_drones
+
+ def _parse_start_end_zone(
+ self,
+ lines: list[str],
+ nb_drones: int,
+ is_start: bool = False,
+ ) -> Zone:
+ """Check whether zone is start or end.
+ Extract the line.
+ Extract and process the start or end zone."""
+
+ zone_key = "start_hub" if is_start else "end_hub"
+
+ line = self._get_line(lines, zone_key)
+
+ return self._process_zone_line(
+ line=line,
+ nb_drones=nb_drones,
+ zone=zone_key,
+ is_start=is_start,
+ is_end=not is_start,
+ )
+
+ def _get_line(
+ self,
+ lines: list[str],
+ zone: str,
+ ) -> str:
+ """Return the unique start_hub or end_hub line.
+ Raise an error if start_* or end_hub is not defined.
+ Raise an error if multiple start_* or end_hub are defined.
+ """
+
+ count = 0
+ for line in lines:
+ if line.startswith(zone):
+ count += 1
+ matching_line = line
+
+ if count == 0:
+ raise ParseError(
+ f"ParseError: No {zone} defined."
+ )
+ elif count > 1:
+ raise ParseError(
+ f"ParseError: Multiple {zone}s defined."
+ )
+
+ return matching_line
+
+ def _process_zone_line(
+ self,
+ line: str,
+ nb_drones: int,
+ zone: str = "zone",
+ is_start: bool = False,
+ is_end: bool = False,
+ ) -> Zone:
+ """
+ Parse a zone line and return a zone object.
+
+ Supported format:
+
+ hub: name x y [zone=restricted color=blue max_drones=3]
+ hub: name x y [color=blue max_drones=3]
+ hub: name x y [color=blue]
+ start_hub: name x y [color=green]
+ end_hub: name x y [color=red]
+
+ About split(): If maxsplit is given, at most maxsplit
+ splits are done (thus, the list will have at most
+ maxsplit+1 elements).
+ """
+
+ expected_prefix = f"{zone}:"
+
+ if not line.startswith(expected_prefix):
+ raise ValueError(
+ f"Expected a '{zone}' line, got: {line}"
+ )
+
+ after_column = line[len(expected_prefix):].strip()
+
+ # zone_type is default if unspecified
+ zone_type: ZoneType = ZoneType.NORMAL
+ color: str | None = None
+ max_drones = nb_drones if is_start or is_end else 1
+
+ parts = after_column.split(maxsplit=3)
+
+ # without metadata
+ if len(parts) == 3:
+ name, x_value, y_value = parts
+
+ # with metadata
+ elif len(parts) == 4 \
+ and parts[3].startswith('[') \
+ and parts[3].endswith(']'):
+ name, x_value, y_value, metadata = parts
+ metadata = metadata.strip("[]")
+ pairs = metadata.split(" ")
+
+ for pair in pairs:
+ try:
+ # split metadata pairs
+ key, value = pair.split("=", 1)
+ except ValueError:
+ raise ValueError(
+ f"Invalid metadata: '{pair}' "
+ f"for zone '{name}'. "
+ f"Must be 'key=value'."
+ )
+ key = key.strip().lower()
+ value = value.strip()
+
+ if key == "color":
+ color = value
+ elif key == "zone":
+ try:
+ zone_type = ZoneType[value.upper()] # Enum lookup
+ except KeyError:
+ raise ParseError(
+ f"ParseError: Invalid zone type '{value}' "
+ f"for zone '{name}'."
+ )
+ elif key == "max_drones":
+ try:
+ max_drones = int(value)
+ except ValueError:
+ raise ValueError(
+ f"Invalid max_drones value: '{value}'"
+ f"for zone '{name}'. "
+ f"Must be an integer."
+ )
+ else:
+ raise ValueError(
+ f"Invalid key: '{key}'"
+ )
+ else:
+ raise ValueError(
+ f"Invalid syntax for line: '{line}'. "
+ f"Should be <zone>: <name> <x> <y> [...]. "
+ f"<name> should not have spaces or dashes."
+ )
+ try:
+ x = int(x_value)
+ y = int(y_value)
+ except ValueError:
+ raise ValueError(
+ f"Zone coordinates must be integers: {line}"
+ )
+
+ return Zone(
+ name=name,
+ x=x,
+ y=y,
+ color=color,
+ zone_type=zone_type,
+ max_drones=max_drones,
+ is_start=is_start,
+ is_end=is_end,
+ )
+
+ def _parse_zones(
+ self,
+ lines: list[str],
+ nb_drones: int,
+ start: Zone,
+ end: Zone,
+ ) -> list[Zone]:
+ """Parse all ordinary zone lines."""
+
+ zones: list[Zone] = []
+
+ for line in lines:
+ if not line.startswith("hub:"):
+ continue
+
+ zone = self._process_zone_line(
+ line=line,
+ nb_drones=nb_drones,
+ zone="hub",
+ )
+
+ zones.append(zone)
+
+ self._verify_unique_zone(zones, start, end)
+
+ return zones
+
+ def _verify_unique_zone(
+ self,
+ zones: list[Zone],
+ start: Zone,
+ end: Zone,
+ ) -> bool:
+ """Ensure that all zone names and coordinates are unique."""
+
+ all_zones = [start, end, *zones]
+
+ names = [zone.name for zone in all_zones]
+
+ if len(names) != len(set(names)):
+ raise ValueError(
+ "Zone names must be unique."
+ )
+
+ coordinates = [
+ (zone.x, zone.y)
+ for zone in all_zones
+ ]
+
+ if len(coordinates) != len(set(coordinates)):
+ raise ValueError(
+ "Zone coordinates must be unique."
+ )
+
+ return True
+
+ def _parse_connections(
+ self,
+ lines: list[str],
+ zones: list[Zone],
+ start: Zone,
+ end: Zone,
+ ) -> list[Connection]:
+ """Parse all connection lines."""
+
+ connections: list[Connection] = []
+
+ for line in lines:
+ if not line.startswith("connection:"):
+ continue
+
+ connection = self._process_conn_line(
+ line=line,
+ zones=zones,
+ start=start,
+ end=end,
+ )
+
+ connections.append(connection)
+
+ if self._check_duplicated_connections(connections):
+ raise ParseError("ParseError: Duplicated connections.")
+
+ return connections
+
+ def _process_conn_line(
+ self,
+ line: str,
+ zones: list[Zone],
+ start: Zone,
+ end: Zone,
+ ) -> Connection:
+ """Parse a connection line."""
+
+ prefix = "connection:"
+
+ if not line.startswith(prefix):
+ raise ValueError(
+ f"Invalid connection line: {line}"
+ )
+
+ value = line[len(prefix):].strip()
+ link_capacity_raw: str | None = None
+ link_capacity_value: int = 1
+
+ if len(value.split(" ")) > 1:
+ conn_pair, link_capacity_raw = value.split(" ")
+ else:
+ conn_pair = value
+
+ if conn_pair.count("-") != 1:
+ raise ValueError(
+ f"Invalid connection definition: {line}. "
+ "Expected 'connection: zone1-zone2'."
+ )
+
+ src_name, dest_name = [
+ part.strip()
+ for part in conn_pair.split("-", 1)
+ ]
+
+ all_zones = [start, end, *zones]
+ zone_by_name = {
+ zone.name: zone
+ for zone in all_zones
+ }
+
+ if src_name not in zone_by_name:
+ raise ValueError(
+ f"Unknown source zone '{src_name}' in: {line}"
+ )
+
+ if dest_name not in zone_by_name:
+ raise ValueError(
+ f"Unknown destination zone '{dest_name}' in: {line}"
+ )
+
+ src = zone_by_name[src_name]
+ dest = zone_by_name[dest_name]
+
+ # Store the connection name on both endpoint zones.
+ connection_name = f"{src.name}-{dest.name}"
+
+ if connection_name not in src.connections:
+ src.connections.append(connection_name)
+
+ reverse_name = f"{dest.name}-{src.name}"
+
+ if reverse_name not in dest.connections:
+ dest.connections.append(reverse_name)
+
+ if link_capacity_raw:
+ try:
+ link_capacity_pair = link_capacity_raw.strip("[]")
+ key, link_capacity_value_str = link_capacity_pair.split("=")
+ # convert to a str to make mypy happy
+ link_capacity_value = int(link_capacity_value_str)
+ except ValueError:
+ raise ValueError(
+ f"Capacity must be an int: {link_capacity_value}"
+ )
+
+ return Connection(
+ src=src,
+ dest=dest,
+ link_capacity=link_capacity_value
+ )
+
+ def _check_duplicated_connections(
+ self,
+ connections: list[Connection],
+ ) -> bool:
+ """Ensure that a connection is not defined more than once
+ Use frozenset() so that pairs of endpoints are hashable.
+ A -> B and B -> A produce the same key.
+ See README for more info.
+ """
+ seen: set[frozenset[str]] = set()
+
+ for connection in connections:
+ key = frozenset({
+ connection.src.name,
+ connection.dest.name,
+ })
+
+ if key in seen:
+ raise ValueError(
+ "Duplicated connection found: "
+ f"{connection.src.name}-{connection.dest.name}"
+ )
+
+ seen.add(key)
+
+ return False
+
+
+if __name__ == "__main__":
+ try:
+ drone_map = Parser().parse_map()
+ print(drone_map.model_dump_json(indent=2))
+ except (ValueError, FileNotFoundError, OSError) as err:
+ raise SystemExit(f"Error: {err}")
diff --git a/src/pathfinder.py b/src/pathfinder.py
new file mode 100644
index 0000000..4464e5a
--- /dev/null
+++ b/src/pathfinder.py
@@ -0,0 +1,176 @@
+"""Pathfinding algorithm for maps."""
+
+from dataclasses import dataclass
+from heapq import heappop, heappush
+from typing import Dict, List, Optional, Tuple
+from graph import Graph
+from models import Zone, ZoneType
+
+
+@dataclass(frozen=True)
+class PathResult:
+ """Store the result of a shortest-path search.
+
+ Use frozen=True since paths won't change.
+ """
+
+ cost: int
+ path: list[str]
+
+ def get_path(self) -> list[str]:
+ return self.path
+
+
+class Pathfinder:
+ """Find the lowest-cost path through a zone graph."""
+
+ def __init__(self, graph: Graph) -> None:
+ """Initialize the pathfinder."""
+ self.graph = graph
+
+ def find_path(
+ self,
+ start_name: str,
+ goal_name: str
+ ) -> Optional[PathResult]:
+ """Find the cheapest path, preferring priority zones on ties.
+
+ Movement cost is the primary criterion. If two paths have the same
+ movement cost, the path entering more priority zones is preferred.
+ """
+ self._validate_zone_name(start_name)
+ self._validate_zone_name(goal_name)
+
+ # Maps a zone to its best comparison value:
+ # (movement_cost, negative_priority_count)
+ best_values: Dict[str, Tuple[int, int]] = {
+ start_name: (0, 0),
+ }
+
+ previous: Dict[str, Optional[str]] = {
+ start_name: None,
+ }
+
+ # The negative count makes more priority zones preferable because
+ # heapq always removes the smallest tuple.
+ queue: List[Tuple[int, int, str]] = [
+ (0, 0, start_name),
+ ]
+
+ while queue:
+ # pop the smallest/ child, lowest cost
+ # negative priority = lower is better
+ current_cost, negative_priority_count, current_name = (
+ heappop(queue)
+ )
+
+ current_value = (
+ current_cost,
+ negative_priority_count,
+ )
+
+ if current_value != best_values.get(current_name):
+ continue
+
+ if current_name == goal_name:
+ path = self._reconstruct_path(
+ previous,
+ start_name,
+ goal_name,
+ )
+
+ return PathResult(
+ cost=current_cost,
+ path=path,
+ )
+
+ for neighbour in self.graph.neighbours(current_name):
+ if neighbour.zone_type == ZoneType.BLOCKED:
+ continue
+
+ # when a drone is recomputing the shortest path
+ # we skip the zone that is congested
+ if neighbour.congested:
+ continue
+
+ # when a drone is recomputing the shortest path
+ # we skip the connection that is congested
+ current = self.graph.get_zone(current_name)
+ connection = self.graph.get_connection(
+ current,
+ neighbour
+ )
+ if connection.congested is True:
+ continue
+
+ movement_cost = self._movement_cost(neighbour)
+ enters_priority = (
+ neighbour.zone_type == ZoneType.PRIORITY
+ )
+
+ new_cost = current_cost + movement_cost
+ new_negative_priority_count = (
+ negative_priority_count
+ - int(enters_priority)
+ )
+
+ new_value = (
+ new_cost,
+ new_negative_priority_count,
+ )
+
+ neighbour_name = neighbour.name
+ old_value = best_values.get(neighbour_name)
+
+ if old_value is None or new_value < old_value:
+ best_values[neighbour_name] = new_value
+ previous[neighbour_name] = current_name
+
+ heappush(
+ queue,
+ (
+ new_cost,
+ new_negative_priority_count,
+ neighbour_name,
+ ),
+ )
+
+ return None
+
+ @staticmethod
+ def _movement_cost(destination: Zone) -> int:
+ """Return the cost of entering a destination zone."""
+ if destination.zone_type == ZoneType.RESTRICTED:
+ return 2
+
+ return 1
+
+ def _validate_zone_name(self, zone_name: str) -> None:
+ """Validate that a zone exists in the graph."""
+ try:
+ self.graph.get_zone(zone_name)
+ except KeyError:
+ raise ValueError(
+ f"Unknown zone: {zone_name}"
+ )
+
+ @staticmethod
+ def _reconstruct_path(
+ previous: Dict[str, Optional[str]],
+ start_name: str,
+ goal_name: str,
+ ) -> List[str]:
+ """Reconstruct a path from predecessor information."""
+ path: List[str] = []
+ current_name: Optional[str] = goal_name
+
+ while current_name is not None:
+ path.append(current_name)
+
+ if current_name == start_name:
+ path.reverse()
+ return path
+
+ current_name = previous.get(current_name)
+
+ raise SystemError("Unable to reconstruct the shortest path.")
diff --git a/src/scheduler.py b/src/scheduler.py
new file mode 100644
index 0000000..9a33aec
--- /dev/null
+++ b/src/scheduler.py
@@ -0,0 +1,285 @@
+"""Scheduling of the simulation.
+ Does not run the pathfinding algorithm
+"""
+
+from drone import Drone
+from typing import List, Tuple
+from graph import Graph
+from models import Zone, ZoneType, Connection
+from pathfinder import Pathfinder, PathResult
+
+
+class Scheduler:
+ """Schedule multiple drones on a common path.
+
+ If a zone of the path is RESTRICTED and congested,
+ i.e. at max capacity, a new path is computed for
+ that drone
+ """
+
+ def __init__(
+ self,
+ graph: Graph,
+ path: List[str],
+ number_of_drones: int,
+ ) -> None:
+ """Initialize the scheduler."""
+ self.graph = graph
+ self.drones = [
+ Drone(id_=index, path=path.copy())
+ for index in range(1, number_of_drones + 1)
+ ]
+
+ @property
+ def all_delivered(self) -> bool:
+ """Check if all drones have been delivered"""
+ return all(drone.delivered for drone in self.drones)
+
+ def run(self) -> None:
+ """Run the simulation until all drones have reached the goal."""
+
+ # self.all_delivered using the property above
+ while not self.all_delivered:
+ movements = self._run_turn()
+
+ if movements:
+ print(f"{' '.join(movements)}")
+
+ def _list_moves(self) -> List[Tuple[Drone, str]]:
+ """This loop creates an object 'moves', a list
+ of Drone and the destination of their next
+ move.
+ """
+
+ moves: List[Tuple[Drone, str]] = []
+
+ for drone in self.drones:
+ if drone.delivered:
+ continue
+
+ if drone.next_zone is None:
+ raise KeyError("No next zone")
+ dest_name: str = drone.next_zone
+
+ if dest_name is not None:
+ moves.append((drone, dest_name))
+
+ return moves
+
+ def _compute_new_path(
+ self,
+ src: Zone,
+ dest: Zone,
+ ) -> PathResult | None:
+ """ Compute new path when path is congested"""
+
+ # get the end of the current path
+ end: Zone = self.graph.get_end()
+
+ pathfinder: Pathfinder = Pathfinder(self.graph)
+ if pathfinder is None:
+ return None
+ path_result: PathResult | None = pathfinder.find_path(src.name,
+ end.name
+ )
+ return path_result
+
+ def _run_turn(self) -> List[str]:
+ """Calculate and apply valid movements for one turn.
+
+ for each drone, the algorithm checks if the
+ drone can travel to its dest, and if so does so.
+
+ Else, the algorithm computes a new path.
+
+ If there no path is found; the algo moves on to
+ the next drone in the list.
+ """
+
+ moves: List[Tuple[Drone, str]] = self._list_moves()
+
+ connections_to_clear: List[Connection] = []
+ accepted: List[str] = []
+
+ for drone, dest_name in moves:
+
+ # get src and dest
+ dest: Zone = self.graph.get_zone(dest_name)
+ src_name: str = drone.current_zone
+ src: Zone = self.graph.get_zone(src_name)
+
+ if drone.in_transit is True:
+ connection = self.graph.get_connection(src, dest)
+ drone.leave_transit(src,
+ dest,
+ self.graph
+ )
+ accepted.append(f"D{drone.id_}-"
+ f"{self._color_zone(dest_name)}-"
+ f"{dest.occupancy}/{dest.max_drones}")
+ connections_to_clear.append(self.graph.get_connection(src,
+ dest
+ )
+ )
+ continue
+
+ # drone is on its way to restricted zone
+ if dest.zone_type == ZoneType.RESTRICTED:
+ connection = self.graph.get_connection(src, dest)
+ if connection.link_capacity > connection.link_occupancy \
+ and dest.reservation < dest.max_drones:
+ dest.reservation += 1
+ connection.link_occupancy += 1
+ drone.in_transit = True
+ else:
+ # if zone is not restricted
+ while not self._can_enter(dest) \
+ or not self._can_transit(src, dest):
+
+ # if the zone is congested
+ if not self._can_enter(dest) and not dest.name == 'goal':
+ dest.congested = True
+
+ # if the connection is congested
+ if not self._can_transit(src, dest):
+ self._connection_congested(src, dest, self.graph)
+
+ path_result: PathResult | None = (
+ self._compute_new_path(src, dest)
+ )
+ if path_result is None:
+ break
+
+ if self._new_dest_reachable(path_result):
+ drone.update_path(path_result)
+ dest = drone.update_dest(self.graph)
+ else:
+ break
+
+ # when path_result is None
+ # for loop moves on to the next drone
+ connection = self.graph.get_connection(src, dest)
+ if dest.congested is True or connection.congested is True:
+ continue
+
+ # regular move
+ drone.move()
+ self._increment_connection_occupancy(src, dest, self.graph)
+ if src.name != 'start':
+ src.occupancy -= 1
+ # udpate occupancy of destination zone
+ if not dest.name == 'goal':
+ dest.occupancy += 1
+ accepted.append(f"D{drone.id_}-"
+ f"{self._color_zone(dest.name)}-"
+ f"{dest.occupancy}/{dest.max_drones}")
+ connections_to_clear.append(connection)
+
+ # drone is leaving source
+ if src.congested is True:
+ src.congested = False
+
+ self._clear_connections_occupancy(connections_to_clear)
+ return accepted
+
+ def _new_dest_reachable(self, path_result: PathResult) -> bool:
+ path = path_result.path
+ src_name = path[0]
+ src: Zone = self.graph.get_zone(src_name)
+ next_zone_name = path[1]
+ next_zone: Zone = self.graph.get_zone(next_zone_name)
+ if self._can_enter(next_zone) and self._can_transit(src, next_zone):
+ return True
+ else:
+ return False
+
+ @staticmethod
+ def _increment_connection_occupancy(src: Zone,
+ dest: Zone,
+ graph: Graph
+ ) -> None:
+ """Increment the occupancy attribute of a Connection"""
+ connection = graph.get_connection(src, dest)
+ connection.link_occupancy += 1
+
+ @staticmethod
+ def _connection_congested(src: Zone,
+ dest: Zone,
+ graph: Graph
+ ) -> None:
+ """Toogle congested attribute of Connection to True"""
+ connection = graph.get_connection(src, dest)
+ connection.congested = True
+
+ @staticmethod
+ def _clear_connections_occupancy(connections: List[Connection]) -> None:
+ """Clear occupancy of connections"""
+ for connection in connections:
+ if connection.dest.zone_type == ZoneType.RESTRICTED:
+ continue
+ connection.link_occupancy -= 1
+ connection.congested = False
+
+ # spin off color methods to its own class
+ def _color_zone(
+ self,
+ dest: str,
+ ) -> str:
+ """Color zone name if zone has a color attribute"""
+ zone = self.graph.get_zone(dest)
+ if zone.color is None:
+ return zone.name
+ if zone.color:
+ return self._color_string(zone, zone.color)
+ raise KeyError(f"No zone {dest}")
+
+ def _color_string(
+ self,
+ zone: Zone,
+ zone_color: str
+ ) -> str:
+ all_colors: dict[str, str] = {'black': "\033[0;30m",
+ 'red': "\033[0;31m",
+ 'green': "\033[0;32m",
+ 'yellow': "\033[0;33m",
+ 'blue': "\033[0;34m",
+ 'magenta': "\033[0;35m",
+ 'cyan': "\033[0;36m",
+ 'white': "\033[0;37m",
+ 'gray': "\033[0;90m",
+ 'grey': "\033[0;90m",
+ # using 256-color mode
+ 'brown': "\033[38;5;137",
+ 'crimson': "\033[38;5;160m",
+ 'darkred': "\033[38;5;52m",
+ 'gold': "\033[38;5;226m",
+ 'lime': "\033[38;5;83m",
+ 'maroon': "\033[38;5;001m",
+ 'orange': "\033[38;5;208m",
+ 'purple': "\033[38;5;128m",
+ 'violet': "\033[38;5;93m",
+ 'pink': "\033[38;5;201m"
+ }
+
+ for color in all_colors:
+ if zone_color == color:
+ return f"{all_colors[color]}{zone.name}\033[0m"
+ raise KeyError(f"No color '{zone_color}', check your map.")
+
+ @staticmethod
+ def _can_enter(dest: Zone) -> bool:
+ """Return whether a destination has enough capacity."""
+ if dest.is_end:
+ return True
+
+ return dest.occupancy < dest.max_drones
+
+ def _can_transit(self,
+ src: Zone,
+ dest: Zone
+ ) -> bool:
+ """Return whether a drone can transit through a connection."""
+
+ occupancy = self.graph.get_link_occupancy(src, dest)
+ capacity = self.graph.get_link_capacity(src, dest)
+ return occupancy < capacity