hpylos (empty) → 1.0
raw patch · 10 files changed
+3151/−0 lines, 10 filesdep +EEConfigdep +GLUTdep +OpenGLsetup-changed
Dependencies added: EEConfig, GLUT, OpenGL, array, base, containers
Files
- LICENSE +621/−0
- Setup.hs +2/−0
- hpylos.cabal +22/−0
- readme.txt +12/−0
- source/PylosAI.hs +392/−0
- source/PylosBoard.hs +522/−0
- source/PylosDisplay.hs +677/−0
- source/PylosEvaluator.hs +433/−0
- source/PylosMove.hs +261/−0
- source/hpylos.hs +209/−0
+ LICENSE view
@@ -0,0 +1,621 @@+ GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. <http://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
+ Setup.hs view
@@ -0,0 +1,2 @@+import Distribution.Simple+main = defaultMain
+ hpylos.cabal view
@@ -0,0 +1,22 @@+name: hpylos+version: 1.0+copyright: (c) 2008 Bartosz Wójcik+license: GPL+license-file: LICENSE+author: Bartosz Wójcik <bartek@sudety.it>+maintainer: Bartosz Wójcik <bartek@sudety.it>+Homepage: http://sourceforge.net/projects/hpylos/+category: AI,Game+synopsis: AI of Pylos game with GLUT interface.+description: Pylos is 2 persons turn strategy board game described here: <http://www.boardgamegeek.com/game/1419>.+ hpylos is functional example of AI of pylos with 3D graphic.+ You can play vs. one of few algorithms that can be customized.+stability: stable+build-type: Simple+cabal-version: >= 1.2.1++Executable hpylos+ Build-Depends: base,containers,array,OpenGL,GLUT,EEConfig+ ghc-options: -O2+ Main-Is: hpylos.hs+ hs-source-dirs: source
+ readme.txt view
@@ -0,0 +1,12 @@+This is Pylos game with AI module.+See homepage: http://sourceforge.net/projects/hpylos/++Intallation notes.+1. GHC has to be installed (http://www.haskell.org/ghc/). +2. OpenGL, GLUT and EEConfig have to be installed (http://hackage.haskell.org/packages/archive/pkg-list.html).+3. Unpack+4. ghc --make Setup.hs+5. ./Setup configure+6. ./Setup build+7. ./Setup install (you need root rights)+
+ source/PylosAI.hs view
@@ -0,0 +1,392 @@+{-# LANGUAGE BangPatterns #-} +-- ================================== +-- Module name: PylosAI +-- Project: Pylos +-- Copyright (C) 2008 Bartosz Wojcik +-- Created on: 17.10.2008 +-- Last update: 06.11.2008 +-- Version: % + +{- 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 <http://www.gnu.org/licenses/>. +-} +-- ========================================================= +-- | +-- This module delivers AI functions that work over tree of moves. +-- It has been created using directly ideas of John Hughes presented +-- in his paper "Why Functional Programming Matters". +-- As Miranda can be translated into Haskell almost directly, +-- the code presented in the paper has big simillarity to ones in this module. + +module PylosAI (Algorithm (..), + evaluate, + maximise, + minimise, + sizeGT, + drawGT + ) +where + +-- ========================================================= +import Graphics.Rendering.OpenGL (GLint) +import qualified Data.Map as Map (fold,+ (!)) +import Data.List +import Data.Tree +import Data.Array (listArray,(!)) +import PylosBoard (Pylos (..), + Coordinate, + Player (..), + NbrOfBalls, + putable, + moveable, + moveOnCoordinate, + anyTakeable, + nextPlayer, + initPylos, + terminator + ) +import PylosMove (Move (..), + moves, + coordinatesOfLastMove, + movesResult + ) +-- ========================================================= + +-- ========================================================= +data Algorithm = SimpleDiff + | SimpleDiffMiddle + | SimpleDiffPlusVal+ | SimpleDiffAdvance + | BalancedDiffPlusVal + | MixedDiff + deriving (Eq,Read,Show,Enum,Ord) +-- ========================================================= + +-- ========================================================= +-- | +-- AI of Pylos depends on algorithm and depth of analysis. +data AIPylos = AIPylos Algorithm -- ^ Playing algorithm + Move -- ^ move + deriving (Eq,Read,Show) +-- ========================================================= + +-- ========================================================= +instance Ord (AIPylos) where +-- --------------------------------------------------------- + -- Rule of simplest difference of number of balls comparison + compare (AIPylos SimpleDiff (NextMove _ _ (w1,b1) _)) + (AIPylos _ (NextMove _ _ (w2,b2) _)) = compare (w1 - b1) (w2 - b2) + + -- Rule that compares difference of balls. In case they are equal, it compares number of + -- built 3s. + compare (AIPylos SimpleDiffPlusVal (NextMove p1 _ (w1,b1) _)) + (AIPylos _ (NextMove p2 _ (w2,b2) _)) + | d1 == d2 = compare (pylosVal (+|) p1) (pylosVal (+|) p2) + | otherwise = compare d1 d2 + where d1 = w1 - b1 + d2 = w2 - b2 + + -- Rule that compares difference of balls. In case they are equal, it perfers middle board positions + compare (AIPylos SimpleDiffMiddle (NextMove p _ (w1,b1) cs1)) + (AIPylos _ (NextMove _ _ (w2,b2) cs2)) + | d1 == d2 = compare ((fromMiddle s . head . last) cs1) ((fromMiddle s . head . last) cs2) + | otherwise = compare d1 d2 + where d1 = w1 - b1 + d2 = w2 - b2 + s = size p+ + -- Rule that compares difference of balls. In case they are equal, it perfers positions of bigger 'advance' value. + compare (AIPylos SimpleDiffAdvance (NextMove p1 _ (w1,b1) cs1)) + (AIPylos _ (NextMove p2 _ (w2,b2) cs2)) + | d1 == d2 = compare v1 v2 + | otherwise = compare d1 d2 + where d1 = w1 - b1 + d2 = w2 - b2+ v1 = (-1) * advance p1 Map.! (head . last) cs1 + v2 = (-1) * advance p2 Map.! (head . last) cs2 + + -- Rule that compares balanced difference of balls. In case they are equal, it compares number of already + -- built 3s. "Balanced" means that in case of not many balls in hand, it may be better to diminish + -- number of balls for both players equally than to increase difference of 1. Why? Because it brings faster + -- towards victory. + compare (AIPylos BalancedDiffPlusVal (NextMove p1 pl1 (w1,b1) cs1)) + (AIPylos _ (NextMove p2 pl2 (w2,b2) cs2)) + | d1 == d2 = compare ((pylosVal (+|) p1) // sum1) ((pylosVal (+|) p2) // sum2) + | otherwise = compare (d1 // sum1) (d2 // sum2) + where d1 = w1 - b1 + d2 = w2 - b2 + sum1 = w1 + b1 + sum2 = w2 + b2 + + -- The idea is following. Addtitionall to counted balls on both hands one can try + -- to recognize board situation. Player who's next on move and has at least one row, column or square + -- of 3 balls with empty 4th place can in next move have one ball more on hand. This rule is + -- not 100% correct, but at least can be used as rough estimation on next move advantages. + -- Player who's done last move and have at least 2 sets of rows, columns or squares full of 3 own + -- balls is in same situation - can get one ball more in his||her next move. So is such situation + -- is recognized, the difference of balls on hands is updated accordingly. + compare (AIPylos MixedDiff (NextMove p1 pl1 (w1,b1) cs1)) + (AIPylos _ (NextMove p2 pl2 (w2,b2) cs2)) = compare (d1 + mixedDiff p1 pl1) (d2 + mixedDiff p2 pl2) + where d1 = w1 - b1 + d2 = w2 - b2 + + -- Just in case + compare _ _ = EQ +-- ========================================================= + +-- ========================================================= +fromMiddle :: GLint -> Coordinate -> Float +-- --------------------------------------------------------- +fromMiddle size (l,(x,y)) = fromIntegral size - abs (fromIntegral x - p) - abs (fromIntegral y - p) + where p = ((size - l) + 1) // 2 - 1 +-- ========================================================= + +-- ========================================================= +-- | Recognition of future advantages. Advantage in next move is recognized if there is at least on set +-- of 3 own balls with empty 4th filed. Advantage of 2nd next move is recognized if there are at least +-- 2 such sets. +mixedDiff :: (Integral a) => Pylos -> Player -> a +-- --------------------------------------------------------- +mixedDiff pyl player | player == WhitePlayer && nbr3s <= 0 || + player == BlackPlayer && nbr3s >= 0 = (signum . round) nbr3s + | abs nbr3s < 2 = 0 + | otherwise = (signum . round) nbr3s + where nbr3s = fromIntegral (pylosVal (+|) pyl) / 3 -- tailored for pylos size 4 +-- ========================================================= + +-- ========================================================= +pylosVal :: (GLint -> GLint -> GLint) -> Pylos -> GLint +-- --------------------------------------------------------- +pylosVal f pylos = pVal f (squaresOf4 pylos) + pVal f (rows pylos) + pVal f (columns pylos) +-- ========================================================= + +-- ========================================================= +pVal :: (GLint -> GLint -> GLint) -> NbrOfBalls -> GLint +-- --------------------------------------------------------- +pVal f = Map.fold f 0 +-- ========================================================= + +-- ========================================================= +takeTerminated :: [Coordinate] -> Bool +-- --------------------------------------------------------- +takeTerminated cs = head cs == terminator +-- ========================================================= + +-- ========================================================= +-- | +-- This functions adds only agruments >= than 3 (in abs sense). +-- It's used to sum up all long enough sequences of balls. +-- "Long enough" have been chosen on experimental way for pylos size 4 and won't work properly for other sizes. +(+|) :: (Num n, Ord n) => n -> n -> n +-- --------------------------------------------------------- +a +| b | not $ abs a == 3 = b + | not $ abs b == 3 = a +-- | abs a < 3 = b +-- | abs b < 3 = a + | otherwise = a + b +-- ========================================================= + +-- ========================================================= +(//) :: (Integral a, Fractional b, Integral a1) => a -> a1 -> b +-- --------------------------------------------------------- +a // b = fromIntegral a / fromIntegral b +-- ========================================================= + +-- ========================================================= +moveOfAIPylos :: AIPylos -> Move +moveOfAIPylos (AIPylos _ move) = move +-- ========================================================= + +-- ========================================================= +repTree :: Ord a => (a -> [a]) -> a -> Tree a +-- --------------------------------------------------------- +repTree f m = Node m (map (repTree f) (f m)) +-- ========================================================= + +-- ========================================================= +gameTree :: Int -> Move -> Tree Move +-- --------------------------------------------------------- +gameTree 0 = repTree (sort . moves) +gameTree breadth = repTree (take breadth . sort . moves) +-- ========================================================= + +-- ========================================================= +-- | +-- Dynamic pruning of tree. It pruns at least to given depth, +-- deeper if foreseen size of tree is not achieved yet. +pruneD :: Int -> Int -> Int -> Tree Move -> Tree Move +-- --------------------------------------------------------- +pruneD depth 0 _ tree = prune depth tree +pruneD depth limit breadth tree = pruneD' depth limit 1 breadth tree +-- ========================================================= +pruneD' :: Int -- ^ Depth of pruning - how many leves more are to stay. + -> Int -- ^ Limit of number of nodes to be kept. In format 16^limit. + -> Integer -- ^ Current number of nodes -- estimated! + -> Int -- ^ Max breadth of each subtree - important for current number of nodes estimation. + -> Tree Move -- ^ Input tree + -> Tree Move -- ^ Output tree +-- --------------------------------------------------------- +pruneD' 0 0 _ _ (Node a sub) = Node a [] +pruneD' d n 0 b _ = error $ "pruneD': broken counter: " ++ show d ++ " " ++ show n ++ " " ++ show b +pruneD' 0 n !m 0 (Node a sub) | len == 0 = error $ " result1: " ++ show i ++ " " ++ show n ++ " " ++ show m + | 16^n + 100 <= m * len^2 = Node a [] + | otherwise = Node a (map (pruneD' 1 n (m*len) 0) sub) + where len = maxBreadth ! i + i = movesResult a +pruneD' d n !m 0 (Node a sub) | len == 0 = error $ " result2: " ++ show i ++ " " ++ show n + | otherwise = Node a (map (pruneD' (d-1) n (m*len) 0) sub) + where len = maxBreadth ! i + i = movesResult a +pruneD' 0 n !m breadth (Node a sub) | abs i > 300 = error $ " result3: " ++ show i ++ " " ++ show n + | 16^n + 100 <= m * len^2 = Node a [] + | otherwise = Node a (map (pruneD' 1 n (m*len) breadth) sub) + where len = min (fromIntegral breadth) (maxBreadth ! i) + i = movesResult a +pruneD' d n !m breadth (Node a sub) | abs i > 300 = error $ " result4: " ++ show i ++ " " ++ show n + | otherwise = Node a (map (pruneD' (d-1) n (m*len) breadth) sub) + where len = min (fromIntegral breadth) (maxBreadth ! i) + i = movesResult a +-- ========================================================= + +-- ========================================================= +prune :: Int -> Tree Move -> Tree Move +-- --------------------------------------------------------- +prune 0 (Node a sub) = Node a [] +prune n (Node a sub) = Node a (map (prune (n-1)) sub) +-- ========================================================= + +-- ========================================================= +sizeGT :: Int -> Int -> Int -> Move -> Int +-- --------------------------------------------------------- +sizeGT depth limit b = sizeT . pruneD depth limit b . gameTree b +-- ========================================================= + +-- ========================================================= +sizeT :: Tree a -> Int +-- --------------------------------------------------------- +sizeT (Node a sub) = foldl (\x y -> x + sizeT y) 1 sub +-- ========================================================= + +-- ========================================================= +-- | This table's figures have been created on experimental way. +-- maxBreadth = listArray (-30,0) [16,15,14,13,13,12,12,12,15,20,22,25,30,34,40,50,57,40,32,26,20,15,10,6,4,3,4,3,2,1,0] +-- maxBreadth = listArray (-30,30) ([16,15,14,13,13,12,12,12,15,20,20,20,20,20,20,20,20,20,20,20,15,15,10,6,4,3,4,3,2,1,100] ++ replicate 30 100) +maxBreadth = listArray (-30,300) ([16,15,14,13,13,12,12,12,15,15,16,16,16,16,16,16,16,16,16,15,10,10,10,6,4,3,4,3,2,1,100] ++ replicate 300 100) +-- ========================================================= + +drawGT depth limit b = drawTree . fmap showShort . pruneD depth limit b . gameTree b + +showShort (NextMove _ player result moves) = show player ++ " " ++ show result ++ " " ++ show moves + +-- ========================================================= +-- | +-- The function omitMin is passed a "potential maximum" - the largest minimum seen +-- so far - and omits any minima which are less than this. +omitMin :: (Ord a) => a -> [[a]] -> [a] +-- --------------------------------------------------------- +omitMin pot [] = [] +omitMin pot (nums:rest) + | minleq nums pot = omitMin pot rest + | otherwise = minNums:(omitMin minNums rest) + where minNums = minimum nums +-- ========================================================= +omitMax :: (Ord a) => a -> [[a]] -> [a] +-- --------------------------------------------------------- +omitMax pot [] = [] +omitMax pot (nums:rest) + | maxleq nums pot = omitMax pot rest + | otherwise = maxNums:(omitMax maxNums rest) + where maxNums = maximum nums +-- ========================================================= + +-- ========================================================= +-- | +-- Minleq takes a list of numbers and a potential maximum, and returns true if the +-- minimum of the list of numbers is less than or equal to the potential maximum. +-- To do this, it does not need to look at all the list! If there is any element in the +-- list less than or equal to the potential maximum, then the minimum of the list +-- is sure to be. All elements after this particular one are irrelevant. Therefore minleq can be defined by +minleq :: (Ord t) => [t] -> t -> Bool +-- --------------------------------------------------------- +minleq [] pot = False +minleq (num:rest) pot | num <= pot = True + | otherwise = minleq rest pot +-- ========================================================= +maxleq :: (Ord t) => [t] -> t -> Bool +-- --------------------------------------------------------- +maxleq [] pot = False +maxleq (num:rest) pot | num >= pot = True + | otherwise = maxleq rest pot +-- ========================================================= + +-- ========================================================= +-- | +-- mapmin omits the minima of lists whose minimum doesn't matter. +mapmin :: (Ord a) => [[a]] -> [a] +-- --------------------------------------------------------- +mapmin (nums:rest) = minNums:(omitMin minNums rest) + where minNums = minimum nums +-- ========================================================= +mapmax :: (Ord a) => [[a]] -> [a] +-- --------------------------------------------------------- +mapmax (nums:rest) = maxNums:(omitMax maxNums rest) + where maxNums = maximum nums +-- ========================================================= + + +-- ========================================================= +-- | +-- maximise' and minimise' function implement alpha-beta algortihm +maximise' :: (Ord a) => Tree a -> [a] +-- --------------------------------------------------------- +maximise' (Node n []) = n:[] +maximise' (Node n l) = mapmin (map minimise' l) +-- ========================================================= +minimise' :: (Ord a) => Tree a -> [a] +-- --------------------------------------------------------- +minimise' (Node n []) = n:[] +minimise' (Node n l) = mapmax (map maximise' l) +-- ========================================================= + +-- ========================================================= +maximise :: (Ord a) => Tree a -> a +maximise = maximum . maximise' +-- ========================================================= +minimise :: (Ord a) => Tree a -> a +minimise = minimum . minimise' +-- ========================================================= + +-- ========================================================= +compRev :: (Ord a) => a -> a -> Ordering +-- --------------------------------------------------------- +compRev x y | x == y = EQ + | x <= y = GT + | otherwise = LT +-- ========================================================= + +-- ========================================================= +-- | Evaluates next move. +evaluate :: Algorithm -- ^ Using this algorithm + -> Int -- ^ Until this depth of tree of moves + -> Int -- ^ or deeper until this limit of nodes + -> (Tree AIPylos -> AIPylos) -- ^ Using this minimax alpha beta function + -> Int -- ^ Limit of subtrees of tree of moves (if > 0) + -> Move -- ^ Last move. + -> [Coordinate] -- ^ Returns move in terms of coordinates +-- --------------------------------------------------------- +evaluate alg depth limit minmax breadth = + coordinatesOfLastMove . moveOfAIPylos . minmax . fmap (AIPylos alg) . pruneD depth limit breadth . gameTree breadth +-- ========================================================= + +
+ source/PylosBoard.hs view
@@ -0,0 +1,522 @@+-- ================================== +-- Module name: PylosBoard +-- Project: Pylos +-- Copyright (C) 2008 Bartosz Wójcik +-- Created on: 09.06.2008 +-- Last update: 06.11.2008 +-- Version: % + +{- 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 <http://www.gnu.org/licenses/>. +-} +-- ================================== +-- | This module defines board of Pylos game. +-- It contains also board manipulation and verification functions. +module PylosBoard (Stone (..), + Coordinate, + Board, + IntMapBoard, + NbrOfBalls, + Pylos (..), + Player(..), + initPylos, + putStone, + putable, + putableForMove, + takeStone, + takeable, + moveable, + updateAllBases, + updateAllSuccessors, + anyTakeable, + moveOnCoordinate, + ifTakeAfterPut, + nextPlayer, + isFree, + stone2Player, + nbrOfBalls, + terminator + ) +where + + +-- =================================== +import Graphics.Rendering.OpenGL (GLint) +import qualified Data.Map as Map +-- import Mapext (mapAny) +-- =================================== + +-- =================================== +-- | Each field of 'Board' must be one of following type. +data Stone = NoStone + | WhiteStone + | BlackStone + deriving (Eq,Ord,Enum,Read,Show) + +-- | Playes definition +data Player = WhitePlayer + | BlackPlayer + deriving (Eq,Ord,Enum,Read,Show) + +-- | Casts Players on Stones +player2Stone :: Player -> Stone +-- ---------------------------------- +player2Stone WhitePlayer = WhiteStone +player2Stone BlackPlayer = BlackStone + +-- | Casts Stones of Players +stone2Player :: Stone -> Player +-- ---------------------------------- +stone2Player WhiteStone = WhitePlayer +stone2Player BlackStone = BlackPlayer +stone2Player _ = error "stone2Player: Player of NoStone doesn't exist" + +-- | Same like not for Bool +nextPlayer :: Player -> Player +-- --------------------------------- +nextPlayer BlackPlayer = WhitePlayer +nextPlayer WhitePlayer = BlackPlayer + +-- | Coordinate within 'Board' consists of level (0 to size) and position within the level. +-- Size is a parameter that indicates number of tiles of the board, which is (size * size). +type Coordinate = (GLint,(GLint,GLint)) + +-- | Terminator terminates move. +terminator :: Coordinate +terminator = (-1,(0,0)) + +-- | Board is map of stones indexed by coordinates. +type Board = Map.Map Coordinate Stone + +-- | 'Board' has two shadow-structures of following type. +-- * 1st of them called 'bases'. +-- * 2nd of them called 'successors'. +type IntMapBoard = Map.Map Coordinate GLint + +-- | Any ball on the board increases nbr of balls of own row, colums and some number of 4 balls squares. +-- Any time ball is placed on or removed from the board, corresponding counters are increased or diminished. +-- This should accelerate taking decision whether move is good or bad. +type NbrOfBalls = Map.Map Coordinate GLint +-- =================================== + +-- =================================== +-- | Aggregated status on the board. It contains 'Board' itself and additional data that accelerate analysis. +data Pylos = + Pylos { size :: GLint -- ^ size of game + , board :: Board -- ^ board + , bases :: IntMapBoard -- ^ Number of stones that constitute base of each stone, + -- that have already been put onto board. If and only if this number = 4 + -- then field is putable. For instance all level 0 fields have this value always = 4. + , successors :: IntMapBoard -- ^ number of stones that covers each stone. + -- 'Stone' can be removed from the 'Board' only if this number = 0. + , rows :: NbrOfBalls -- ^ Indicator of content of each row. Row is full of white stones when this equals size of the game. + -- It is full of black stones when equals (-size). + -- Rows are indexed by (number of row,0) pair. + , columns :: NbrOfBalls -- ^ Indicator of content of each column. Column is full of white stones when this equals size of the game. + -- It is full of black stones when equals (-size). + -- Columns are indexed by (0,number of column) pair. + , squaresOf4 :: NbrOfBalls -- ^ Indicator of content of each 4 balls square. It is full of white stones when this equals 4. + -- It is full of black stones when equals (-4). What 4 balls square is? Each 4 tiles of + -- the board that have 1 common vertex constitute 4 balls square. + -- 4 balls squares are indexed by their upper left tile (or Nord-West if one prefers). + , advance :: IntMapBoard -- ^ Each place on board gets own advance value. It is supposed to express expectation of being a good + -- move by populating this place. + } + deriving (Eq,Read,Show) +-- =================================== +-- | Initial game situation. Input: size. +initPylos :: GLint -> Pylos +-- ----------------------------------- +initPylos s = Pylos { size = s, + board = initBoard s, + bases = basesOfFields s, + successors = succesorsOfFields s, + rows = Map.fromList [((level,(x,0)),0) | level <- [0 .. s-1], x <- [0 .. s-level-1] ] , + columns = Map.fromList [((level,(0,y)),0) | level <- [0 .. s-1], y <- [0 .. s-level-1] ] , + squaresOf4 = Map.fromList [((level,(x,y)),0) | level <- [0 .. s-1], x <- [0 .. s-level-2], y <- [0 .. s-level-2] ] , + advance = Map.fromList $ (terminator,0):[((level,(x,y)),0) | level <- [0 .. s-1], x <- [0 .. s-level-1], y <- [0 .. s-level-1] ] } +-- =================================== + +-- =================================== +-- Initial board. Input: size. +initBoard :: GLint -> Board +-- ----------------------------------- +initBoard size = Map.fromList [((level,(x,y)),NoStone) | level<-[0..(size-1)], + x<-[0..(size-level-1)], + y<-[0..(size-level-1)]] +-- =================================== + +-- =================================== +-- | Initial bases. Input: size. +basesOfFields :: GLint -> IntMapBoard +-- ----------------------------------- +basesOfFields size = Map.fromList [((level,(x,y)),nbrBaseStones level) | level<-[0..(size-1)], + x<-[0..(size-level-1)], + y<-[0..(size-level-1)]] + where nbrBaseStones 0 = 4 + nbrBaseStones _ = 0 +-- =================================== + +-- =================================== +-- | Initial successors. Input: size. +succesorsOfFields :: GLint -> IntMapBoard +-- ----------------------------------- +succesorsOfFields size = Map.fromList [((level,(x,y)),0) | level<-[0..(size-1)], + x<-[0..(size-level-1)], + y<-[0..(size-level-1)]] +-- =================================== + +-- =================================== +-- | If field is free. +isFree :: Coordinate -> Pylos -> Bool +-- ----------------------------------- +isFree c pylos = board pylos Map.! c == NoStone +-- =================================== + +-- =================================== +-- | Is stone of given coordinates of given colour? +isMyColour :: Player -> Coordinate -> Pylos -> Bool +-- ----------------------------------- +isMyColour player cor pylos = board pylos Map.! cor == player2Stone player +-- =================================== + +-- =================================== +-- | Whether given field has all bases. +hasAllBases :: Coordinate -> Pylos -> Bool +-- ----------------------------------- +hasAllBases c pylos = bases pylos Map.! c == 4 +-- =================================== +-- =================================== +-- | Whether given field has no successors. +hasNoSuccessors :: Coordinate -> Pylos -> Bool +-- ----------------------------------- +hasNoSuccessors c pylos = successors pylos Map.! c == 0 +-- =================================== + +-- =================================== +-- | Puts stone on the board on given coordinates. Uses 'Map.insert' function, so doesn't matter what was before value of given coordinates. +putStone :: Stone -> Coordinate -> Board -> Board +-- ----------------------------------- +putStone stone coordinate board = Map.insert coordinate stone board +-- =================================== + +-- =================================== +-- | Checks whether its allowed to put a ball on field given by coordinates. +putable :: Pylos -> Coordinate -> Bool +-- ----------------------------------- +putable p c | hasAllBases c p && isFree c p = True + | otherwise = False +-- =================================== + +-- =================================== +-- | Removes stone from give filed. In other words, inserts 'NoStone' value. +takeStone :: Coordinate -> Board -> Board +-- ----------------------------------- +takeStone coordinate board = Map.insert coordinate NoStone board +-- =================================== + +-- =================================== +-- | Checks whether it's allowed to take given ball from board. +takeable :: Player -> Pylos -> Coordinate -> Bool +-- ----------------------------------- +takeable pl py c | isMyColour pl c py && hasNoSuccessors c py = True + | otherwise = False +-- =================================== + +-- =================================== +-- | Checks whether it's allowed to take given ball from board and put it level above. +moveable :: Player -> Pylos -> Coordinate -> Bool +-- ----------------------------------- +moveable pl pylos c@(l,(x,y)) = takeable pl pylos c && anyPutable (l+1) pylos' + where pylos' = takeStoneAndUpdate c pylos +-- =================================== + +-- =================================== +-- | Updates successor of given coordinate. This function works as well for bases. +updateSuccessor :: Stone -> Coordinate -> IntMapBoard -> IntMapBoard +-- ----------------------------------- +updateSuccessor NoStone coordinate succesorsOfFields = Map.adjust (\x -> x-1) coordinate succesorsOfFields +updateSuccessor _ coordinate succesorsOfFields = Map.adjust (+ 1) coordinate succesorsOfFields +-- =================================== + + +-- =================================== +-- | Each time a stone is put or taken 4 (or 3 or 2 or 1) bases have to be updated. +-- Takes stone, coordinate, size, bases and returns new bases. +updateAllBases :: Stone -> Coordinate -> GLint -> IntMapBoard -> IntMapBoard +-- ----------------------------------- +updateAllBases stone (level,(0,0)) size bases = updateSuccessor stone (level+1,(0,0)) bases +updateAllBases stone (level,(x,0)) size bases | x == size - 1 = updateSuccessor stone (level+1,(x-1,0)) bases + | otherwise = updateSuccessor stone (level+1,(x-1,0)) $ + updateSuccessor stone (level+1,(x,0)) bases +updateAllBases stone (level,(0,y)) size bases | y == size - 1 = updateSuccessor stone (level+1,(0,y-1)) bases + | otherwise = updateSuccessor stone (level+1,(0,y-1)) $ + updateSuccessor stone (level+1,(0,y)) bases +updateAllBases stone (level,(x,y)) size bases | x == size - 1 && + y == size - 1 = updateSuccessor stone (level+1,(x-1,y-1)) bases + | x == size - 1 = updateSuccessor stone (level+1,(x-1,y)) $ + updateSuccessor stone (level+1,(x-1,y-1)) bases + | y == size - 1 = updateSuccessor stone (level+1,(x,y-1)) $ + updateSuccessor stone (level+1,(x-1,y-1)) bases + | otherwise = updateSuccessor stone (level+1,(x-1,y-1)) $ + updateSuccessor stone (level+1,(x-1,y)) $ + updateSuccessor stone (level+1,(x,y-1)) $ + updateSuccessor stone (level+1,(x,y)) bases +-- =================================== + + +-- =================================== +-- | Each time a stone is put or taken 4 successors have to be updated. +-- Takes stone, coordinate, size, bases and returns new successors. +updateAllSuccessors :: Stone -> Coordinate -> GLint -> IntMapBoard -> IntMapBoard +-- ----------------------------------- +updateAllSuccessors stone (0,(x,y)) size successors = successors +updateAllSuccessors stone (level,(x,y)) size successors = updateSuccessor stone (level-1,(x+1,y+1)) $ + updateSuccessor stone (level-1,(x+1,y)) $ + updateSuccessor stone (level-1,(x,y+1)) $ + updateSuccessor stone (level-1,(x,y)) successors +-- =================================== + +-- =================================== +-- | Updates number of balls of given row. +updateRow :: Stone + -> Bool -- ^ True - stone is put, False - stone is being removed from the board. + -> Coordinate + -> GLint -- ^ size + -> NbrOfBalls + -> NbrOfBalls +-- ----------------------------------- +updateRow WhiteStone True (level,(x,y)) size rows = Map.adjust (+ 1) (level,(x,0)) rows +updateRow BlackStone True (level,(x,y)) size rows = Map.adjust (\x -> x - 1) (level,(x,0)) rows +updateRow WhiteStone False (level,(x,y)) size rows = Map.adjust (\x -> x - 1) (level,(x,0)) rows +updateRow BlackStone False (level,(x,y)) size rows = Map.adjust (+ 1) (level,(x,0)) rows +-- =================================== + +-- =================================== +-- | 2nd argument points on the action: True - stone is put, False - stone is being removed from the board. +-- 4th - size. +updateColumn :: Stone -> Bool -> Coordinate -> GLint -> NbrOfBalls -> NbrOfBalls +-- ----------------------------------- +updateColumn WhiteStone True (level,(x,y)) size columns = Map.adjust (+ 1) (level,(0,y)) columns +updateColumn BlackStone True (level,(x,y)) size columns = Map.adjust (\x -> x - 1) (level,(0,y)) columns +updateColumn WhiteStone False (level,(x,y)) size columns = Map.adjust (\x -> x - 1) (level,(0,y)) columns +updateColumn BlackStone False (level,(x,y)) size columns = Map.adjust (+ 1) (level,(0,y)) columns +-- =================================== + +-- =================================== +-- Coordinate of squareOf4 is its NE ball. +-- | 2nd argument points on the action: True - stone is put, False - stone is being removed from the board. +-- 4th - size. +updateSquaresOf4 :: Stone -> Bool -> Coordinate -> GLint -> NbrOfBalls -> NbrOfBalls +-- ----------------------------------- +updateSquaresOf4 WhiteStone True coordinate size squaresOf4 = (updateSquareNE 1 coordinate size . + updateSquareNW 1 coordinate size . + updateSquareSE 1 coordinate size . + updateSquareSW 1 coordinate size) squaresOf4 +updateSquaresOf4 BlackStone True coordinate size squaresOf4 = (updateSquareNE (-1) coordinate size . + updateSquareNW (-1) coordinate size . + updateSquareSE (-1) coordinate size . + updateSquareSW (-1) coordinate size) squaresOf4 +updateSquaresOf4 BlackStone False coordinate size squaresOf4 = (updateSquareNE 1 coordinate size . + updateSquareNW 1 coordinate size . + updateSquareSE 1 coordinate size . + updateSquareSW 1 coordinate size) squaresOf4 +updateSquaresOf4 WhiteStone False coordinate size squaresOf4 = (updateSquareNE (-1) coordinate size . + updateSquareNW (-1) coordinate size . + updateSquareSE (-1) coordinate size . + updateSquareSW (-1) coordinate size) squaresOf4 +-- =================================== +updateSquareNE :: GLint -> Coordinate -> GLint -> NbrOfBalls -> NbrOfBalls +-- ----------------------------------- +updateSquareNE one (level,(x,y)) size squaresOf4 | x > 0 && y > 0 = Map.adjust (+ one) (level,(x-1,y-1)) squaresOf4 + | otherwise = squaresOf4 +-- =================================== +updateSquareNW :: GLint -> Coordinate -> GLint -> NbrOfBalls -> NbrOfBalls +-- ----------------------------------- +updateSquareNW one (level,(x,y)) size squaresOf4 | x > 0 && y < size - level -1 = Map.adjust (+ one) (level,(x-1,y)) squaresOf4 + | otherwise = squaresOf4 +-- =================================== +updateSquareSE :: GLint -> Coordinate -> GLint -> NbrOfBalls -> NbrOfBalls +-- ----------------------------------- +updateSquareSE one (level,(x,y)) size squaresOf4 | x < size - level -1 && y > 0 = Map.adjust (+ one) (level,(x,y-1)) squaresOf4 + | otherwise = squaresOf4 +-- =================================== +updateSquareSW :: GLint -> Coordinate -> GLint -> NbrOfBalls -> NbrOfBalls +-- ----------------------------------- +updateSquareSW one (level,(x,y)) size squaresOf4 | x < size - level -1 && y < size - level -1 = Map.adjust (+ one) (level,(x,y)) squaresOf4 + | otherwise = squaresOf4 +-- =================================== + +-- =================================== +updateAllAdvances :: Stone -> Coordinate -> GLint -> GLint -> IntMapBoard -> IntMapBoard +-- ----------------------------------- +updateAllAdvances stone (l,(x,y)) one size = updateAdvances (valueOfStone stone) keysS . + updateAdvances (valueOfStone stone) keysR . + updateAdvances (valueOfStone stone) keysC + where keysR = [(l,(x,y')) | y' <- [0 .. size-l-1], y' /= y ] -- update all of given row + keysC = [(l,(x',y)) | x' <- [0 .. size-l-1], x' /= x ] -- update all of given column + keysS = [(l,(x',y')) | x' <- [(max 0 (x-1)) .. (min (size-l-1) (x+1))], -- update all of all squaresOf4 + y' <- [(max 0 (y-1)) .. (min (size-l-1) (y+1))], x' /= x || y' /= y] + valueOfStone WhiteStone = 1 * one + valueOfStone BlackStone = -1 * one + valueOfStone _ = 0 +-- =================================== +updateAdvances :: GLint -> [Coordinate] -> IntMapBoard -> IntMapBoard +-- ----------------------------------- +updateAdvances one keys advance = foldl (\adv key -> Map.adjust (+ one) key adv) advance keys +-- =================================== + +-- =================================== +-- | If there is any puttable filed on the board. +-- Takes level and current game situation. +anyPutable :: GLint -> Pylos -> Bool +-- ----------------------------------- +anyPutable level pylos = any (putable pylos) keys + where keys = [(l,(x,y)) | l<-[level..s-1], x <- [0..s-l-1], y<-[0..s-l-1]] + s = size pylos +-- =================================== + +-- =================================== +-- | +-- Whether ball can be put to given position within the move turn. +putableForMove :: GLint -> Coordinate -> Pylos -> Bool +-- ----------------------------------- +putableForMove level c@(l,(x,y)) pylos = l > level && putable pylos c +-- =================================== + +-- =================================== +-- | If there is any takeable field on the board. +-- Takes stone to be taken and current game situation. +anyTakeable :: Player -> Pylos -> Bool +-- ----------------------------------- +anyTakeable player pylos = any (takeable player pylos) keys + where keys = [(l,(x,y)) | l<-[0..s-1], x <- [0..s-l-1], y<-[0..s-l-1]] + s = size pylos +-- =================================== + +-- =================================== +-- | +-- Does only possible action on given field. +-- Gets stone colour which depends on what playes is on move, coordinates and game status. +-- Updates the whole status of Pylos structure. +moveOnCoordinate :: Player -> Coordinate -> Pylos -> Pylos +-- ----------------------------------- +moveOnCoordinate player coordinate pylos | coordinate == terminator = pylos + | putable pylos coordinate = putStoneAndUpdate stone coordinate pylos + | takeable player pylos coordinate = takeStoneAndUpdate coordinate pylos + | otherwise = pylos + where stone = player2Stone player +-- =================================== + +-- =================================== +-- | +-- Updates whole 'Pylos' structure after stone has been put. +putStoneAndUpdate :: Stone -> Coordinate -> Pylos -> Pylos +-- ----------------------------------- +putStoneAndUpdate stone c@(l,(x,y)) pylos = Pylos { size = s, + board = putStone stone c (board pylos), + bases = updateAllBases stone c s (bases pylos), + successors = updateAllSuccessors stone c s (successors pylos), + rows = updateRow stone True c s (rows pylos), + columns = updateColumn stone True c s (columns pylos), + squaresOf4 = updateSquaresOf4 stone True c s (squaresOf4 pylos), + advance = updateAllAdvances stone c 1 s (advance pylos) + } + where s = size pylos +-- =================================== + +-- =================================== +-- | +-- Updates whole 'Pylos' structure after stone has been taken. +takeStoneAndUpdate :: Coordinate -> Pylos -> Pylos +-- ----------------------------------- +takeStoneAndUpdate c@(l,(x,y)) pylos = Pylos { size = s, + board = takeStone c (board pylos), + bases = updateAllBases NoStone c s (bases pylos), + successors = updateAllSuccessors NoStone c s (successors pylos), + rows = updateRow stone False c s (rows pylos), + columns = updateColumn stone False c s (columns pylos), + squaresOf4 = updateSquaresOf4 stone False c s (squaresOf4 pylos), + advance = updateAllAdvances stone c (-1) s (advance pylos) + } + where s = size pylos + stone = board pylos Map.! c +-- =================================== + +-- =================================== +-- | +-- Checks whether player can take balls after he||she puts one. +ifTakeAfterPut :: Pylos -> Player -> Coordinate -> Bool +-- ----------------------------------- +ifTakeAfterPut pylos player c = isInFullCol player c (columns pylos) s || -- anyRowOrColFull s player (columns pylos) || + isInFullRow player c (rows pylos) s || -- anyRowOrColFull s player (rows pylos) || + isInFullSquareOf4 player c (squaresOf4 pylos) s -- anySquareOf4Full player (squaresOf4 pylos) + where s = size pylos +-- =================================== + +-- =================================== +isInFullRow :: Player -> Coordinate -> NbrOfBalls -> GLint -> Bool +-- ----------------------------------- +isInFullRow player c@(l,(x,y)) row size = row Map.! (l,(x,0)) == value player + where value WhitePlayer = size + value _ = -size +-- =================================== + +-- =================================== +isInFullCol :: Player -> Coordinate -> NbrOfBalls -> GLint -> Bool +-- ----------------------------------- +isInFullCol player c@(l,(x,y)) col size = col Map.! (l,(0,y)) == value player + where value WhitePlayer = size + value _ = -size +-- =================================== + +-- =================================== +ifFullSquareNE :: GLint -> Coordinate -> NbrOfBalls -> GLint -> Bool +-- ----------------------------------- +ifFullSquareNE value (level,(x,y)) squaresOf4 size | x > 0 && y > 0 = squaresOf4 Map.! (level,(x-1,y-1)) == value + | otherwise = False +-- =================================== +ifFullSquareNW :: GLint -> Coordinate -> NbrOfBalls -> GLint -> Bool +-- ----------------------------------- +ifFullSquareNW value (level,(x,y)) squaresOf4 size | x > 0 && y < size - level -1 = squaresOf4 Map.! (level,(x-1,y)) == value + | otherwise = False +-- =================================== +ifFullSquareSE :: GLint -> Coordinate -> NbrOfBalls -> GLint -> Bool +-- ----------------------------------- +ifFullSquareSE value (level,(x,y)) squaresOf4 size | x < size - level -1 && y > 0 = squaresOf4 Map.! (level,(x,y-1)) == value + | otherwise = False +-- =================================== +ifFullSquareSW :: GLint -> Coordinate -> NbrOfBalls -> GLint -> Bool +-- ----------------------------------- +ifFullSquareSW value (level,(x,y)) squaresOf4 size | x < size - level -1 && y < size - level -1 = squaresOf4 Map.! (level,(x,y)) == value + | otherwise = False +-- =================================== + +-- =================================== +isInFullSquareOf4 :: Player -> Coordinate -> NbrOfBalls -> GLint -> Bool +-- ----------------------------------- +isInFullSquareOf4 player c squaresOf4 size = ifFullSquareNE (value player) c squaresOf4 size || + ifFullSquareNW (value player) c squaresOf4 size || + ifFullSquareSE (value player) c squaresOf4 size || + ifFullSquareSW (value player) c squaresOf4 size + where value WhitePlayer = 4 + value _ = -4 +-- =================================== + +-- ========================================================= +-- | +-- Returns total number of balls for given size of the game. +nbrOfBalls :: (Enum a, Num a) => a -> a +-- --------------------------------------------------------- +nbrOfBalls size = sum $ map (\x->x*x) [1..size] +-- =========================================================
+ source/PylosDisplay.hs view
@@ -0,0 +1,677 @@+-- ================================== +-- Module name: PylosDisplay +-- Project: Pylos +-- Copyright (C) 2008 Bartosz Wójcik +-- Created on: 09.06.2008 +-- Last update: 06.11.2008 +-- Version: % + +{- 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 <http://www.gnu.org/licenses/>. +-} +-- ================================== +-- | This module is a simple interface to Pylos game <http://www.boardgamegeek.com/game/1419> +-- It uses AI module in order to follow game status or provide game between human and computer. +module PylosDisplay (displayPylos) +where + +-- ========================================================= +import Graphics.Rendering.OpenGL +import Graphics.UI.GLUT as GLUT +import Data.Array ( Array, listArray, array, elems, (!) ) +import qualified Data.Map as Map ((!)) +import Data.Either +import Data.IORef +import Data.List +import System.Exit +import PylosBoard (Pylos (..), + Coordinate, + Player (..), + putable, + takeable, + moveable, + initPylos, + putableForMove, + ifTakeAfterPut, + isFree, + stone2Player, + nextPlayer + ) +import PylosMove (Move (NextMove)) +import PylosAI (Algorithm (..), + evaluate, + maximise, + minimise, + sizeGT, + drawGT + ) +import PylosEvaluator (Action (..), + TileStatus (..), + Actions, + BoardState, + BallsState, + PlayerType, + State (..), + algPlayerType, + depPlayerType, + brePlayerType, + nbrPlayerType, + makeState, + stateProcessMain, + actionTerminate, + alreadyFinishedCase, + stateProcessSecondary, + stateProcess, + updateNbrBalls, + aiOnMove + ) +-- ========================================================= +-- | Ball's display properity, apart of colour +data BallEmphasize = NoEmphasize + | Lighter + | Wire + | Transparent + | Marked + deriving (Eq,Ord,Enum,Read,Show) + +-- | Ball's display full properities. +type BallColour = (Player,BallEmphasize) + +-- ========================================================= +-- | +-- Prepares colour and flavour of given ball depending on status details. +ballColour :: Pylos -- ^ Pylos game status + -> Coordinate -- ^ Coordinates of given ball + -> Coordinate -- ^ Recently put ball + -> Maybe Coordinate -- ^ Ball pointed by cursor + -> (Coordinate, Coordinate) -- ^ Balls recently taken from board + -> Actions -- ^ current action's state + -> Bool -- ^ whether shadow mode (shadow mode is for balls that are supposed to react on mouse pointer) + -> BallColour -- ^ real colour * flavour to be rendered. +-- --------------------------------------------------------- +ballColour pylos c@(l,(x,y)) aB pB (rB1@(lr,(xr,yr)),rB2) (player,action) shadowMode + | action == Puts && isPutableForMove && ((Just c == pB) || shadowMode) = (player,Lighter) + | action == PutsOrTakes && (isPutable || isMoveable) && ((Just c == pB) || shadowMode) = (player,Lighter) + | doesTake && isTakeable && ((Just c == pB) || shadowMode) = (player,Lighter) + | (c == rB1 || c == rB2) && not shadowMode = (player,Wire) + | ifTakeAfterPut pylos player c && not shadowMode = (player,Marked) + | isFree c pylos || shadowMode = (player,Transparent) + | c == aB = (stone,Lighter) + | otherwise = (stone,NoEmphasize) + where isPutable = putable pylos c + isTakeable = takeable player pylos c + isMoveable = moveable player pylos c + isPutableForMove = putableForMove lr c pylos + doesTake = action == Takes1 || action == Takes2 + stone = stone2Player $ board pylos Map.! c +-- ========================================================= + +-- ========================================================= +darkGrey = Color4 0.3 0.3 0.3 1 +white = Color4 1 1 1 1 +blue = Color4 0 0 1 1 +-- ========================================================= + +-- ========================================================= +-- | +-- Set of colour definitions. +blackBoard = do + materialAmbient FrontAndBack $= Color4 0.2 0.2 0.2 1.0 + materialDiffuse FrontAndBack $= Color4 0.15 0.15 0.15 1.0 + materialSpecular FrontAndBack $= Color4 0.11 0.11 0.11 1 + materialShininess FrontAndBack $= 5 + +whiteBoard = do + materialAmbient FrontAndBack $= Color4 0.4 0.4 0.4 1.0 + materialDiffuse FrontAndBack $= Color4 0.15 0.15 0.15 1.0 + materialSpecular FrontAndBack $= Color4 0.11 0.11 0.11 1 + materialShininess FrontAndBack $= 5 + +blackBall = do + materialAmbient FrontAndBack $= Color4 0.01 0.01 0.01 1.0 + materialDiffuse FrontAndBack $= Color4 0.1 0.1 0.1 1.0 + materialSpecular FrontAndBack $= Color4 0.11 0.11 0.11 1 + materialShininess FrontAndBack $= 5 + +lightBlackBall = do + materialAmbient FrontAndBack $= Color4 0.04 0.04 0.04 1.0 + materialDiffuse FrontAndBack $= Color4 0.15 0.15 0.15 1.0 + materialSpecular FrontAndBack $= Color4 0.65 0.65 0.65 1 + materialShininess FrontAndBack $= 5 + +whiteBall = do + materialAmbient FrontAndBack $= Color4 0.45 0.45 0.45 1.0 + materialDiffuse FrontAndBack $= Color4 0.25 0.25 0.25 1.0 + materialSpecular FrontAndBack $= Color4 0 0 0 5 + materialShininess FrontAndBack $= 20 + +lightWhiteBall = do + materialAmbient FrontAndBack $= Color4 0.58 0.58 0.58 1.0 + materialDiffuse FrontAndBack $= Color4 0.32 0.32 0.32 1.0 + materialSpecular FrontAndBack $= Color4 0 0 0 1 + materialShininess FrontAndBack $= 20 + +redBall = do + materialAmbient FrontAndBack $= Color4 0.25 0 0 1.0 + materialDiffuse FrontAndBack $= Color4 0.5 0.05 0.05 1.0 + materialSpecular FrontAndBack $= Color4 0.65 0.65 0.65 1 + materialShininess FrontAndBack $= 5 + +blackGrid = do + materialAmbient FrontAndBack $= Color4 0 0 0 1 + materialDiffuse FrontAndBack $= Color4 0 0 0 1 + materialSpecular FrontAndBack $= Color4 0 0 0 1 + materialShininess FrontAndBack $= 1 + +whiteGrid = do + materialAmbient FrontAndBack $= Color4 1 1 1 1 + materialDiffuse FrontAndBack $= Color4 1 1 1 1 + materialSpecular FrontAndBack $= Color4 1 1 1 1 + materialShininess FrontAndBack $= 1 + +goldenBoard = do + materialAmbient FrontAndBack $= Color4 0.12 0.1 0 1 + materialDiffuse FrontAndBack $= Color4 0.11 0.08 0 1 + materialSpecular FrontAndBack $= Color4 0.37 0.37 0.37 1 + materialShininess FrontAndBack $= 3 + +violetBall = do + materialAmbient FrontAndBack $= Color4 0.05 0 0.05 1.0 + materialDiffuse FrontAndBack $= Color4 0.22 0.00 0.22 1.0 + materialSpecular FrontAndBack $= Color4 0.06 0.06 0.06 1 + materialShininess FrontAndBack $= 10 + +-- ========================================================= + +-- ========================================================= +-- | +-- This "function" initiates game, opens window, and passes stearing to 'Graphics.Rendering.OpenGL.mainLoop'. +displayPylos :: GLint -> PlayerType -> PlayerType -> Int -> IO () +-- --------------------------------------------------------- +displayPylos size pl1 pl2 verbose = do +-- ========================================================= + initialDisplayMode $= [DoubleBuffered,WithDepthBuffer] + win <- createWindow ("Pylos: " ++ header pl1 ++ " vs. " ++ header pl2) + windowSize $= Size 900 800 + + depthFunc $= Just Less + lighting $= Enabled + normalize $= Enabled + position (Light 0) $= Vertex4 0 0 1 0-- 0.2 0.4 (-15) 1 + ambient (Light 0) $= Color4 1 1 1 1 + diffuse (Light 0) $= Color4 1 1 1 1 + specular (Light 0) $= Color4 1 1 1 1 + light (Light 0) $= Enabled + clearColor $= darkGrey + + ambientCol <- newIORef (Color4 0 0 (0::GLfloat) 1) + diffuseCol <- newIORef (Color4 0 0 (0::GLfloat) 1) + specularCol <- newIORef (Color4 0 0 (0::GLfloat) 1) + shineCol <- newIORef (0::GLfloat) + + aX <- newIORef 0 -- rotation in X axe + aY <- newIORef 0 -- rotation in Y axe + + state <- makeState size pl1 pl2 verbose + + reshapeCallback $= Just reshape + + passiveMotionCallback $= Just (mousePosition win aX aY state) + motionCallback $= Just (mouseDrags win aX aY state) + keyboardMouseCallback $= Just (keyboardMouse win aX aY size state) + + displayCallback $= display aX aY size state + + idleCallback $= Just (idle win state) + + mainLoop + + where header Nothing = "Human" + header (Just (alg,depth,breadth,nbr)) = show alg ++ " " ++ show depth ++ " " ++ show breadth ++ " " ++ show nbr +-- ========================================================= + +-- ========================================================= +reshape :: Size -> IO () +-- --------------------------------------------------------- +reshape screenSize@(Size w h) = do +-- ========================================================= + viewport $= ((Position 0 0),screenSize) + matrixMode $= Projection + loadIdentity + myFrustrum w h + matrixMode $= Modelview 0 +-- ========================================================= + +-- ========================================================= +myFrustrum :: (Integral a1, Integral a) => a -> a1 -> IO () +-- --------------------------------------------------------- +myFrustrum w h = frustum (-right) right (-top) top near far + where far = 120 + aspect = fromIntegral(w)/fromIntegral(h) + right = top * aspect +-- ========================================================= +near = 10 +fov = 0.1 +top = near * tan fov +-- ========================================================= + +-- ========================================================= +myModelView :: GLdouble -> GLdouble -> IO () +-- --------------------------------------------------------- +myModelView x y = do +-- ========================================================= + loadIdentity + lookAt (Vertex3 0 0.5 15) (Vertex3 0 0 (-100)) (Vector3 0 1 0) + rotate x (Vector3 1 0 (0::GLdouble)) + rotate y (Vector3 0 0 (1::GLdouble)) +-- ========================================================= + +-- ========================================================= +display :: IORef GLdouble -> IORef GLdouble -> GLint -> State -> IO () +-- --------------------------------------------------------- +display aX aY size state = do +-- ========================================================= + clear [ColorBuffer,DepthBuffer] + (_, (Size width height)) <- get viewport + matrixMode $= Projection + loadIdentity + myFrustrum width height + matrixMode $= Modelview 0 + + x <- readIORef aX + y <- readIORef aY + myModelView x y + + goldenBoard + displayBoard size state + displayBalls state False + + dispStat state $= True + + swapBuffers +-- ========================================================= + + +-- ========================================================= +-- | +-- Displays all balls. It does it in very imperative way. +-- 3 dimensional loop over all levels, rows and columns with ball display for each coordinate separatelly. +-- Balls can be displayed as follows. Already put in place are black or white. One that have been put recently +-- is a bit lighter. Ball where cursor points and which can be used for next move (either put as new one or +-- removed from board) is in Wireframe flavour and black or white colour, corresponding to colour of player who is on move. +-- Recently removed balls are displayed also in Wireframe flavour. +displayBalls :: State -- ^ Game status + -> Bool -- ^ If preserving matrix mode (for mouse pointer selection) + -> IO () -- ^ Displays all balls +-- --------------------------------------------------------- +displayBalls state shadowMode = do + loadName (Name 1) -- this allows to recognize tile selection + pyl <- get $ balls state + aB <- get (aBall state) + rB <- get (rBall state) + sB <- get (sBall state) + pB <- get (pBall state) + act <- get (action state) + let s = size pyl + flip mapM_ [0 .. s-1] $ \l -> do + withName (Name (fromIntegral l)) $ do + flip mapM_ [0 .. s-l-1] $ \i -> do + withName (Name (fromIntegral i)) $ do + flip mapM_ [0 .. s-l-1] $ \j -> + withName (Name (fromIntegral j)) $ do + let c = (l,(i,j)) + let val = ballColour pyl c aB pB rB act shadowMode + preservingMatrix $ displayBall s c val +-- ========================================================= + + +-- ========================================================= +-- | +-- Selects color of given ball and lets it be rendered with given flavour +displayBall :: GLint -> Coordinate -> BallColour -> IO () +-- --------------------------------------------------------- +displayBall size c (_,Wire) = do + violetBall + renderSphere size c Wireframe +displayBall size c (_,Marked) = do + redBall + renderSphere size c Solid +displayBall size c (WhitePlayer,NoEmphasize) = do + whiteBall + renderSphere size c Solid +displayBall size c (WhitePlayer,Lighter) = do + lightWhiteBall + renderSphere size c Solid +displayBall size c (BlackPlayer,NoEmphasize) = do + blackBall + renderSphere size c Solid +displayBall size c (BlackPlayer,Lighter) = do + lightBlackBall + renderSphere size c Solid +displayBall _ _ _ = return () +-- ========================================================= + +-- ========================================================= +-- | +-- Renders a ball of given coordinates. +renderSphere :: GLint -> Coordinate -> Flavour -> IO () +-- --------------------------------------------------------- +renderSphere size (level,(i,j)) material = do +-- ========================================================= + translate (Vector3 x y z) + renderObject material (Sphere' (rr size) 24 24) + where x = dXY size level i + y = dXY size level j + z = dZ size level +-- ========================================================= +-- | Radius of ball depends on size of game. +rr size = 1 / fromIntegral size +-- ========================================================= +-- | +-- Each level of balls has to be rendered at different Z-axe position. +-- In order that balls looked like thay were located laying each next level on previous one, +-- each Z-axe position differs of (sqrt 2) from next one. +-- ========================================================= +dZ :: GLint -> GLint -> GLdouble +-- --------------------------------------------------------- +dZ size level = (rr size) * (1 + 1.42 * fromIntegral level) +-- ========================================================= +dXY :: GLint -> GLint -> GLint -> GLdouble +-- --------------------------------------------------------- +dXY size level i = (rr size) * (2 * (fromIntegral i - fromIntegral (size-1) / 2) + fromIntegral level) +-- ========================================================= + +-- ========================================================= +cuboidCoordinates :: GLint -> (GLint,GLint) -> [(GLfloat, GLfloat, GLfloat)] +-- --------------------------------------------------------- +cuboidCoordinates size (x,y) = [(cX,cY+d,0),(cX+d,cY+d,0),(cX,cY,0),(cX+d,cY,0), + (cX,cY+d,-0.05),(cX+d,cY+d,-0.05),(cX,cY,-0.05),(cX+d,cY,-0.05)] + where d = 1.8 / fromIntegral size + d1 = 2 / fromIntegral size + cX = (-1.0) + d1 * fromIntegral x + cY = (-1.0) + d1 * fromIntegral y +-- ========================================================= + +-- ========================================================= +displayBoard :: GLint -> State -> IO () +-- --------------------------------------------------------- +displayBoard size state = do + loadName (Name 0) -- this allows to recognize tile selection + withName (Name 0) $ do + flip mapM_ [0 .. size-1] $ \i -> do + withName (Name (fromIntegral i)) $ do + flip mapM_ [0 .. size-1] $ \j -> + withName (Name (fromIntegral j)) $ do + val <- get (sboard state ! (0,i,j)) + act <- get $ action state + if val == PointedTile -- colour selection + then redBall + else if fst act == WhitePlayer + then whiteBoard + else blackBoard + (sboard state ! (0,i,j)) $= Tile -- next display of board will unmark all tiles, unless some of them get marked by mouse move + (cuboid.cuboidCoordinates size) (i,j) +-- ========================================================= + +-- ========================================================= +displayText vector text = do + loadIdentity +-- translate vector + scale 0.001 0.001 (1::GLfloat) + currentColor $= white + blackGrid + renderString Roman text +-- ========================================================= + + +-- ========================================================= +-- | +-- Draws a cuboid where vertices are given in the following order +-- frontLeftTop frontRightTop frontLeftBottom frontRightBottom +-- backLeftTop backRightTop backLeftBottom backRightBottom +cuboid :: [(GLfloat, GLfloat, GLfloat)] -> IO () +-- --------------------------------------------------------- +cuboid [fLT,fRT,fLB,fRB,bLT,bRT,bLB,bRB] = renderPrimitive Quads $ makeVertices [fLT,fRT,fRB,fLB, + fLB,fRB,bRB,bLB, + bRB,bLB,bLT,bRT, + bLT,bRT,fRT,fLT, + fLT,fLB,bLB,bLT, + fRT,fRB,bLB,bLT] +-- ========================================================= + + +-- ========================================================= +-- | +-- Renders list of given points as vectors. +makeVertices :: [(GLfloat,GLfloat,GLfloat)] -> IO () +-- --------------------------------------------------------- +makeVertices = mapM_ (\(x,y,z)->vertex$Vertex3 x y z) +-- ========================================================= + +-- ========================================================= +-- | +-- KeyUp rotates board arround X axe. +keyboardMouse :: Window + -> IORef GLdouble + -> IORef GLdouble + -> GLint + -> State + -> Key + -> KeyState + -> t1 + -> Position + -> IO () +-- --------------------------------------------------------- +keyboardMouse win aX aY size state (SpecialKey KeyUp) Down _ (Position x y) = do + readIORef aX >>= \x -> aX $= min 0 (x + 1) + mousePosition win aX aY state (Position x y) + postRedisplay (Just win) +-- ========================================================= +-- ========================================================= +-- | +-- KeyLeft rotates board arround Y axe. +keyboardMouse win aX aY size state (SpecialKey KeyLeft) Down _ (Position x y) = do + readIORef aY >>= \y -> aY $= y - 1 + mousePosition win aX aY state (Position x y) +-- postRedisplay (Just win) +-- ========================================================= +-- ========================================================= +-- | +-- KeyRight rotates board arround Y axe. +keyboardMouse win aX aY size state (SpecialKey KeyRight) Down _ (Position x y) = do + readIORef aY >>= \y -> aY $= y + 1 + mousePosition win aX aY state (Position x y) +-- postRedisplay (Just win) +-- ========================================================= +-- ========================================================= +-- | +-- KeyDown rotates board arround X axe. +keyboardMouse win aX aY size state (SpecialKey KeyDown) Down _ (Position x y) = do + readIORef aX >>= \x -> aX $= max (-90) (x - 1) + mousePosition win aX aY state (Position x y) + postRedisplay (Just win) +-- ========================================================= +-- ========================================================= +-- | +-- ESC causes exit. +keyboardMouse win _ _ _ _ (Char '\27') Down _ _ = do + exitWith ExitSuccess + destroyWindow win +-- ========================================================= +-- ========================================================= +-- | Left Mouse Button released. +keyboardMouse _ _ _ _ state (MouseButton LeftButton) Up _ (Position x y) = leftButton state $= Nothing +-- ========================================================= +-- | Left Mouse Button couses selection of pointed ball. +keyboardMouse win aX aY size state (MouseButton LeftButton) Down _ (Position x y) = do + vp@(_, (Size width height)) <- get viewport + ax <- readIORef aX + ay <- readIORef aY + (_, maybeHitRecords) <- getHitRecords bufSize $ do + preservingMatrix $ do + matrixMode $= Projection + loadIdentity + pickMatrix (fromIntegral x, fromIntegral height - fromIntegral y) (1, 1) vp + myFrustrum width height + matrixMode $= Modelview 0 + myModelView ax ay + withName (Name 0) $ displayBoard size state + withName (Name 1) $ displayBalls state True + swapBuffers + + processMouseButton maybeHitRecords state + leftButton state $= Just (Position x y) + + postRedisplay (Just win) +-- ========================================================= + +-- ========================================================= +keyboardMouse _ _ _ _ _ _ _ _ _ = return () +-- ========================================================= + + +-- ========================================================= +processMouseButton :: Maybe[HitRecord] -> State -> IO () +-- --------------------------------------------------------- +processMouseButton Nothing _ = putStrLn "selection buffer overflow" +-- --------------------------------------------------------- +processMouseButton (Just hitRecords) state = do + if hitRecords == [] + then return () + else do + let (t:l:i:j:xs) = [ fromIntegral n | Name n <- namesOfHitRecord $ minimumBy closerObject hitRecords ] + case t of + 1 -> stateProcessMain state (l,(i,j)) + 0 -> stateProcessSecondary state (l,(i,j)) +-- ========================================================= + +-- ========================================================= +bufSize :: GLsizei +bufSize = 512 +-- ========================================================= + +-- ========================================================= +mouseDrags win aX aY state (Position x y) = do + prevPosition <- readIORef $ leftButton state + if prevPosition == Nothing + then return () + else do + readIORef aX >>= \ax -> aX $= (min 0 $ max (-90) (ax + (fromIntegral y - fromIntegral (pY prevPosition y)) / 2)) + readIORef aY >>= \ay -> aY $= ay + ((fromIntegral x - fromIntegral (pX prevPosition x)) / 2) + leftButton state $= Just (Position x y) + mousePosition win aX aY state (Position x y) + where pX (Just (Position x y)) _ = x + pX Nothing def = def + pY (Just (Position x y)) _ = y + pY Nothing def = def +-- ========================================================= + +-- ========================================================= +mousePosition win aX aY state (Position x y) = do + vp@(_, (Size width height)) <- get viewport + ax <- readIORef aX + ay <- readIORef aY + pBall state $= Nothing + pylos <- readIORef $ balls state + (_, maybeHitRecords) <- getHitRecords bufSize $ do + preservingMatrix $ do + matrixMode $= Projection + loadIdentity + pickMatrix (fromIntegral x, fromIntegral height - fromIntegral y) (1, 1) vp + myFrustrum width height + matrixMode $= Modelview 0 + myModelView ax ay + withName (Name 0) $ displayBoard (size pylos) state + withName (Name 1) $ displayBalls state True + swapBuffers + + aiOnM <- aiOnMove state + if aiOnM + then pBall state $= Nothing + else processCursorPosition maybeHitRecords state + postRedisplay (Just win) +-- ========================================================= + +-- ========================================================= +processCursorPosition :: Maybe[HitRecord] -> State -> IO () +-- --------------------------------------------------------- +processCursorPosition Nothing _ = putStrLn "selection buffer overflow" +-- --------------------------------------------------------- +processCursorPosition (Just hitRecords) state = do + if hitRecords == [] + then return () -- putChar '$' + else if length names < 3 + then putChar '#' + else do + let [t, l, i, j] = [ fromIntegral n | Name n <- namesOfHitRecord $ minimumBy closerObject hitRecords ] + val <- readIORef $ balls state + case t of + 0 -> do + (sboard state ! (0,i,j)) $= PointedTile -- mark tile mouse points on + pBall state $= Just (l,(i,j)) -- mark ball mouse points on + + 1 -> do + pBall state $= Just (l,(i,j)) -- mark ball mouse points on + _ -> putStrLn $ "? " ++ show (t,i) + where names = namesOfHitRecord $ minimumBy closerObject hitRecords + nbrNames = length names +-- ========================================================= + +-- ========================================================= +namesOfHitRecord :: HitRecord -> [Name] +-- --------------------------------------------------------- +namesOfHitRecord (HitRecord _ _ names) = names +-- ========================================================= + +-- ========================================================= +closerObject (HitRecord z1 _ _) (HitRecord z2 _ _) | z1 < z2 = LT + | otherwise = GT +-- ========================================================= + +-- ========================================================= +idle win state = do + (player,act) <- readIORef $ action state + pyl <- readIORef $ balls state + pl1 <- readIORef $ player1 state + pl2 <- readIORef $ player2 state + nbrB <- readIORef $ nbrBalls state + displayed <- readIORef $ dispStat state + verb <- readIORef $ verbose state + mvNbr <- readIORef $ moveNbr state + if displayed && player == WhitePlayer && not (pl1 == Nothing) && (not $ nbrB == (0,0)) + then do + let evWhite = evaluate (algPlayerType pl1) (depPlayerType pl1) (nbrPlayerType pl1) maximise (brePlayerType pl1) (NextMove pyl ( player) nbrB []) + if verb > 0 + then putStrLn $ show mvNbr ++ ". WhitePlayer: " ++ show evWhite + else return () + mapM_ (stateProcessMain state) (reverse evWhite) + if verb > 1 + then putStrLn $ show (sizeGT (depPlayerType pl1) (nbrPlayerType pl1) (brePlayerType pl1) (NextMove pyl ( player) nbrB [])) + else return () + postRedisplay (Just win) + else if displayed && player == BlackPlayer && not (pl2 == Nothing) && (not $ nbrB == (0,0)) + then do + let evBlack = evaluate (algPlayerType pl2) (depPlayerType pl2) (nbrPlayerType pl2) minimise (brePlayerType pl2) (NextMove pyl ( player) nbrB []) + if verb > 0 + then putStrLn $ show mvNbr ++ ". BlackPlayer: " ++ show evBlack + else return () + mapM_ (stateProcessMain state) (reverse evBlack) + if verb > 1 + then do + putStrLn $ show (sizeGT (depPlayerType pl2) (nbrPlayerType pl2) (brePlayerType pl2) (NextMove pyl ( player) nbrB [])) +-- putStr $ drawGT (depPlayerType pl2) (nbrPlayerType pl2) (brePlayerType pl2) (NextMove pyl ( player) nbrB []) + else return () + postRedisplay (Just win) + else return () +-- ========================================================= +
+ source/PylosEvaluator.hs view
@@ -0,0 +1,433 @@+-- ================================== +-- Module name: PylosEvaluator +-- Project: Pylos +-- Copyright (C) 2008 Bartosz Wójcik +-- Created on: 07.11.2008 +-- Last update: 07.11.2008 +-- Version: % + +{- 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 <http://www.gnu.org/licenses/>. +-} +-- ================================== +-- | This module is a simple interface to Pylos game <http://www.boardgamegeek.com/game/1419> +-- It uses AI module in order to follow game status or provide game between human and computer. +module PylosEvaluator (Action (..), + TileStatus (..), + Actions, + BoardState, + BallsState, + PlayerType, + State (..), + algPlayerType, + depPlayerType, + brePlayerType, + nbrPlayerType, + makeState, + stateProcessMain, + actionTerminate, + alreadyFinishedCase, + stateProcessSecondary, + stateProcess, + updateNbrBalls, + aiOnMove, + evaluatePylos + ) + +where + +-- ========================================================= +import Graphics.Rendering.OpenGL (GLint, + Position, + ($=)) +import Data.Array ( Array, listArray, array, elems, (!) ) +import Data.IORef +import Data.List +import PylosBoard (Pylos (..), + Coordinate, + Stone (..), + NbrOfBalls, + Player (..), + putable, + takeable, + moveable, + initPylos, + moveOnCoordinate, + anyTakeable, + ifTakeAfterPut, + nextPlayer, + nbrOfBalls, + terminator + ) +import PylosMove (Move (NextMove)) +import PylosAI (Algorithm (..), + evaluate, + maximise, + minimise, + sizeGT + ) +-- ========================================================= +data Action = Puts -- ^ player has to put ball on the higher level he/she's it just taken from. + | PutsOrTakes -- ^ player either takes a takeable ball or puts one. + | PutsAfterTake2 -- ^ same like Puts, but keeps info, that there is one more ball to be taken + | Takes2 -- ^ player can take 2 balls from board + | Takes1 -- ^ player can take 1 ball from board + deriving (Eq,Ord,Enum,Read,Show) + +-- | +-- Board is displayed as square matrix of tiles. Each tile can be in either of following statuses. +data TileStatus = Tile + | PointedTile + | PickedTile + deriving (Eq,Ord,Enum,Show) + +-- | +-- Actions are status of game's move. Users are on move one after another and they have different types of moves that can be done. +type Actions = (Player,Action) + +-- | +-- The 3 dimentions of board array states for: +-- 1st dimention is level of object: from -1 (tile) till size - 1 (0 - size-1 - ball) +-- 2nd and 3rd dimentions are coordinates within current level +type BoardState = Array (GLint,GLint,GLint) (IORef TileStatus) + +type BallsState = IORef Pylos + +type PlayerType = Maybe (Algorithm, -- Playing algorithm + Int, -- Depth of search tree + Int, -- Max number of subtrees, or unlimited if 0 + Int -- Extend tree of search until this value if possible. + ) + +algPlayerType :: PlayerType -> Algorithm +algPlayerType (Just (algorithm,_,_,_)) = algorithm +algPlayerType _ = error "alg (Nothing)" +depPlayerType (Just (_,depth,_,_)) = depth +depPlayerType _ = error "dep (Nothing)" +brePlayerType (Just (_,_,breadth,_)) = breadth +brePlayerType _ = error "bre (Nothing)" +nbrPlayerType (Just (_,_,_,nbr)) = nbr +nbrPlayerType _ = error "nbr (Nothing)" + +-- | +-- State states for current state of the game. +-- It is used for display, reaction analysis and game stearing purposes. +data State = State {sboard :: BoardState, + balls :: BallsState, + aBall :: IORef Coordinate, -- ^ recently activated ball + rBall :: IORef (Coordinate, Coordinate), -- ^ recently removed balls + sBall :: IORef (Maybe Coordinate), -- ^ selected ball + pBall :: IORef (Maybe Coordinate), -- ^ mouse cursor pointed ball + action :: IORef Actions, -- ^ action on the board + leftButton :: IORef (Maybe Position), -- ^ to turn a board around of axes + player1 :: IORef PlayerType, -- ^ Nothing => human plays + player2 :: IORef PlayerType, -- ^ Nothing => human plays + nbrBalls :: IORef (Int,Int), -- ^ Number of balls of both players being not yet on board. Fst for white player. + dispStat :: IORef Bool, -- ^ Status to first display balls after human move then evaluate next AI move. + verbose :: IORef Int, -- ^ Verbosity level + moveNbr :: IORef Int, -- ^ Number of next move + history :: IORef [[Coordinate]] -- ^ List of done moves + } +-- ========================================================= + +-- ========================================================= +-- | Creates initial status with empty board. White is on move. +makeState :: GLint -> PlayerType -> PlayerType -> Int -> IO State +-- --------------------------------------------------------- +makeState size pl1 pl2 verb = do + boardRefs <- sequence $ (replicate (fromIntegral $ size^2) . newIORef $ Tile) + ballRefs <- newIORef $ initPylos size + aB <- newIORef (0,(0,0)) + rB <- newIORef ((-1,(0,0)),(-1,(0,0))) + pB <- newIORef Nothing + sB <- newIORef Nothing + act <- newIORef (WhitePlayer,Puts) + lButton <- newIORef Nothing + p1 <- newIORef pl1 + p2 <- newIORef pl2 + nbrB <- newIORef $ (ceiling halfOfBalls, truncate halfOfBalls) + dStat <- newIORef False + v <- newIORef verb + mvN <- newIORef 1 + hist <- newIORef [] + return $ State { sboard = listArray ((0,0,0),(0,size-1,size-1)) boardRefs, + balls = ballRefs, + aBall = aB, + sBall = sB, + pBall = pB, + rBall = rB, + action = act, + leftButton = lButton, + player1 = p1, + player2 = p2, + nbrBalls = nbrB, + dispStat = dStat, + verbose = v, + moveNbr = mvN, + history = hist + } + where halfOfBalls = (fromIntegral.nbrOfBalls) size / 2 +-- ========================================================= + +-- ========================================================= +-- | +-- This "function" initiates game, opens window, and passes stearing to 'Graphics.Rendering.OpenGL.mainLoop'. +evaluatePylos :: GLint -> PlayerType -> PlayerType -> Int -> IO State +-- --------------------------------------------------------- +evaluatePylos size pl1 pl2 verbose = do +-- ========================================================= + state <- makeState size pl1 pl2 verbose + untilM_ gameFinished evaluateNextMove state + return state +-- ========================================================= + +-- ========================================================= +-- | monadic version of until function +untilM_ :: (a -> IO Bool) -> (a -> IO ()) -> a -> IO () +-- --------------------------------------------------------- +untilM_ conditionIO f value = do + condition <- conditionIO value + if condition + then return () + else f value >> untilM_ conditionIO f value +-- ========================================================= + +-- ========================================================= +-- | Next move evaluation with assumption both players are computer. +evaluateNextMove :: State -> IO () +-- --------------------------------------------------------- +evaluateNextMove state = dispStat state $= True >> evaluateMove state +-- ========================================================= + +-- ========================================================= +-- | Recognition of end of game (also tie is recognized). +gameFinished :: State -> IO Bool +-- --------------------------------------------------------- +gameFinished state = do + (w,b) <- readIORef $ nbrBalls state + hist <- readIORef $ history state + mvN <- readIORef $ moveNbr state + if w == 0 || b == 0 || checkLoop hist || mvN > 300 + then return True + else return False +-- ========================================================= + +-- ========================================================= +checkLoop :: [[Coordinate]] -> Bool +-- --------------------------------------------------------- +checkLoop (a:b:c:d:e:f:g:h:i:j:k:l:a':b':c':d':e':f':g':h':i':j':k':l':ls) = l == l' && k == k' && j == j' && i == i' && h == h' +checkLoop (a:b:c:d:e:f:g:h:i:j:a':b':c':d':e':f':g':h':i':j':ls) = h == h' && g == g' && j == j' && i == i' +checkLoop (a:b:c:d:e:f:g:h:a':b':c':d':e':f':g':h':ls) = h == h' && g == g' && f == f' && d == d' && e == e' +checkLoop (a:b:c:d:e:f:a':b':c':d':e':f':ls) = b == b' && c == c' && f == f' && d == d' && e == e' +checkLoop (a:b:c:d:e:f:g:h:ls) = a == e && b == f && c == g && d == h +checkLoop (a:b:c:d:ls) = a == c && b == d +checkLoop _ = False +-- ========================================================= + +-- ========================================================= +stateProcessMain :: State -> Coordinate -> IO () +-- --------------------------------------------------------- +stateProcessMain state c = do + act <- readIORef $ action state + verb <- readIORef $ verbose state + dispStat state $= False + if c == terminator + then do + (player,act) <- readIORef $ action state + if act == PutsOrTakes + then if verb > 1 + then putStrLn "terminator: PutsOrTakes" + else return () + else actionTerminate state (player,act) + else stateProcess act state c + aiOnM <- aiOnMove state + if aiOnM + then pBall state $= Nothing + else return () + if verb > 0 + then (readIORef $ nbrBalls state) >>= \n -> (putStrLn $ show n) + else return () + alreadyFinishedCase state +-- ========================================================= + +-- ========================================================= +actionTerminate :: State -> Actions -> IO () +-- --------------------------------------------------------- +actionTerminate state (player,act) = do + action state $= (nextPlayer player,PutsOrTakes) + verb <- readIORef $ verbose state + if verb > 1 + then putStrLn ("terminator: " ++ show (nextPlayer player) ++ "'s turn") + else return () +-- ========================================================= + +-- ========================================================= +-- | +-- Below action controlls if one of players hasn't lost already. +-- If yes, the opposite one can continue. +-- Situation when user put last ball but can take one is not already lost situation. +alreadyFinishedCase :: State -> IO () +-- --------------------------------------------------------- +alreadyFinishedCase state = do + (w,b) <- readIORef $ nbrBalls state + (player,act) <- readIORef $ action state + if w == 0 && b > 0 && player == WhitePlayer && act == PutsOrTakes || + w > 0 && b == 0 && player == BlackPlayer && act == PutsOrTakes + then action state $= (nextPlayer player,act) + else return () +-- ========================================================= + +-- ========================================================= +-- | This function process termination and ball on 1st level selection. +stateProcessSecondary :: State -> Coordinate -> IO () +-- --------------------------------------------------------- +stateProcessSecondary state c = do + (player,act) <- readIORef $ action state + pyl <- readIORef $ balls state + if putable pyl c + then stateProcess (player,act) state c + else if act == Takes2 || act == Takes1 + then actionTerminate state (player,act) + else return () + alreadyFinishedCase state +-- ========================================================= + +-- ========================================================= +stateProcess :: Actions -> State -> Coordinate -> IO () +-- --------------------------------------------------------- +stateProcess (player,Puts) state c = do + pyl <- readIORef $ balls state + if putable pyl c + then do + let pyl' = moveOnCoordinate player c pyl + balls state $= pyl' + aBall state $= c + rB <- readIORef $ rBall state + (readIORef $ nbrBalls state) >>= \x -> nbrBalls state $= updateNbrBalls x (player,Puts) + if c == fst rB || c == snd rB + then rBall state $= ((-1,(0,0)),(-1,(0,0))) + else return () + if ifTakeAfterPut pyl' player c && anyTakeable player pyl' + then action state $= (player,Takes2) -- putable + else do + action state $= (nextPlayer player,PutsOrTakes) + (readIORef $ moveNbr state) >>= \n -> (moveNbr state $= n + 1) + else do + putStrLn $ "@@ " ++ show c + error "stateProcess: Puts on not putable field" +stateProcess (player,PutsOrTakes) state c@(l,(x,y)) = do + pyl <- readIORef $ balls state + if moveable player pyl c + then do + let pyl' = moveOnCoordinate player c pyl + balls state $= pyl' + aBall state $= (-1,(0,0)) + rBall state $= (c,(-1,(0,0))) + action state $= (player,Puts) + (readIORef $ nbrBalls state) >>= \x -> nbrBalls state $= updateNbrBalls x (player,Takes1) + else stateProcess (player,Puts) state c +stateProcess (player,Takes2) state c@(l,(x,y)) = do + pyl <- readIORef $ balls state + if takeable player pyl c + then do + let pyl' = moveOnCoordinate player c pyl + balls state $= pyl' + rBall state $= (c,(-1,(0,0))) + (readIORef $ nbrBalls state) >>= \x -> nbrBalls state $= updateNbrBalls x (player,Takes2) + if anyTakeable player pyl' + then action state $= (player,Takes1) + else action state $= (nextPlayer player,PutsOrTakes) >> + (readIORef $ moveNbr state) >>= \n -> (moveNbr state $= n + 1) + + -- Click on empty tile - nothing happens + else return () -- actionTerminate state (player,Takes2) +stateProcess (player,Takes1) state c@(l,(x,y)) = do + pyl <- readIORef $ balls state + if takeable player pyl c + then do + let pyl' = moveOnCoordinate player c pyl + (rB1,rB2) <- readIORef $ rBall state + balls state $= pyl' + rBall state $= (rB1,c) + aBall state $= (-1,(0,0)) + (readIORef $ nbrBalls state) >>= \x -> nbrBalls state $= updateNbrBalls x (player,Takes1) + action state $= (nextPlayer player,PutsOrTakes) + (readIORef $ moveNbr state) >>= \n -> (moveNbr state $= n + 1) + -- Click on empty tile - player resigns and doesn't take 2nd ball + else actionTerminate state (player,Takes1) + +stateProcess _ _ _ = return () +-- ========================================================= + +-- ========================================================= +updateNbrBalls :: (Int,Int) -> Actions -> (Int,Int) +-- --------------------------------------------------------- +updateNbrBalls (w,b) (WhitePlayer,Puts) = (w - 1,b) +updateNbrBalls (w,b) (BlackPlayer,Puts) = (w,b - 1) +updateNbrBalls (w,b) (WhitePlayer,_) = (w + 1,b) +updateNbrBalls (w,b) (BlackPlayer,_) = (w,b + 1) +-- ========================================================= + + +-- ========================================================= +evaluateMove :: State -> IO () +-- --------------------------------------------------------- +evaluateMove state = do + (player,act) <- readIORef $ action state + pyl <-readIORef $ balls state + pl1 <- readIORef $ player1 state + pl2 <- readIORef $ player2 state + nbrB <- readIORef $ nbrBalls state + displayed <- readIORef $ dispStat state + verb <- readIORef $ verbose state + mvNbr <- readIORef $ moveNbr state + if displayed && player == WhitePlayer && not (pl1 == Nothing) && (not $ nbrB == (0,0)) + then do + let evWhite = evaluate (algPlayerType pl1) (depPlayerType pl1) (nbrPlayerType pl1) maximise (brePlayerType pl1) (NextMove pyl player nbrB []) + if verb > 0 + then putStrLn $ show mvNbr ++ ". WhitePlayer: " ++ show evWhite + else return () + mapM_ (stateProcessMain state) (reverse evWhite) + (readIORef $ history state) >>= \moves -> history state $= evWhite:moves + if verb > 1 + then putStrLn $ show (sizeGT (depPlayerType pl1) (nbrPlayerType pl1) (brePlayerType pl1) (NextMove pyl player nbrB [])) + else return () + else if displayed && player == BlackPlayer && not (pl2 == Nothing) && (not $ nbrB == (0,0)) + then do + let evBlack = evaluate (algPlayerType pl2) (depPlayerType pl2) (nbrPlayerType pl2) minimise (brePlayerType pl2) (NextMove pyl player nbrB []) + if verb > 0 + then putStrLn $ show mvNbr ++ ". BlackPlayer: " ++ show evBlack + else return () + mapM_ (stateProcessMain state) (reverse evBlack) + (readIORef $ history state) >>= \moves -> history state $= evBlack:moves + if verb > 1 + then putStrLn $ show (sizeGT (depPlayerType pl2) (nbrPlayerType pl2) (brePlayerType pl2) (NextMove pyl player nbrB [])) + else return () + else return () +-- ========================================================= + +-- ========================================================= +aiOnMove :: State -> IO Bool +-- --------------------------------------------------------- +aiOnMove state = do + (player,act) <- readIORef $ action state + pl1 <- readIORef $ player1 state + pl2 <- readIORef $ player2 state + nbrB <- readIORef $ nbrBalls state + if (not $ nbrB == (0,0)) && + (player == WhitePlayer && not (pl1 == Nothing) || + player == BlackPlayer && not (pl2 == Nothing)) + then return True + else return False +-- ========================================================= +
+ source/PylosMove.hs view
@@ -0,0 +1,261 @@+-- ================================== +-- Module name: PylosMove +-- Project: Pylos +-- Copyright (C) 2008 Bartosz Wójcik +-- Created on: 10.10.2008 +-- Last update: 06.11.2008 +-- Version: % + +{- 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 <http://www.gnu.org/licenses/>. +-} +-- ========================================================= +-- | This module delivers tree of moves over goven status of Pylos game. +module PylosMove (Move (..), + moves, + coordinatesOfLastMove, + movesResult + ) +where + +-- ========================================================= +import Graphics.Rendering.OpenGL (GLint) +import Data.List (partition, + sort) +import qualified Data.Map as Map ((!)) +import PylosBoard (Pylos (..), + Coordinate, + Player (..), + putable, + moveable, + takeable, + moveOnCoordinate, + anyTakeable, + ifTakeAfterPut, + nextPlayer, + terminator + ) +-- ========================================================= + +-- ========================================================= +-- | Move constitutes tree of moves over Pylos structure. +data Move = NextMove Pylos -- ^ Game state before the move. + Player -- ^ Player on current move. + (Int,Int) -- ^ Number of balls of both players not yet on board after the move. Fst for white player. + [[Coordinate]] -- ^ List of moves where move is list of actions + | Take1Ball Pylos + Player + (Int,Int) -- ^ Number of balls of both players not yet on board. Fst for white player. + [[Coordinate]] -- ^ List of moves where move is list of actions + | PutBall Pylos + Player + (Int,Int) -- ^ Number of balls of both players not yet on board. Fst for white player. + GLint -- ^ Minimum level the ball has to be put on. + [[Coordinate]] -- ^ List of moves where move is list of actions + deriving (Eq,Read,Show) +-- ========================================================= + +-- ========================================================= +-- | +-- List of next moves can be sorted unsing expected value of move which is precalaculated. +instance Ord (Move) where + compare (NextMove pyl1 WhitePlayer (w1,b1) _) + (NextMove pyl2 _ (w2,b2) _) = compare (w1 - b1) (w2 - b2)-- compare (w2 - b2) (w1 - b1) + compare (NextMove pyl1 BlackPlayer (w1,b1) _) + (NextMove pyl2 _ (w2,b2) _) = compare (w2 - b2) (w1 - b1) --compare (w1 - b1) (w2 - b2) -- + compare m1 m2 = error $ "Move compare: not allowed values " ++ show m1 ++ show m2 +-- ========================================================= + +-- ========================================================= +pylosOfMove :: Move -> Pylos +-- --------------------------------------------------------- +pylosOfMove (NextMove pylos _ _ _) = pylos +-- pylosOfMove (Take2Balls pylos _ _ _ _) = pylos +pylosOfMove (Take1Ball pylos _ _ _) = pylos +pylosOfMove (PutBall pylos _ _ _ _) = pylos +-- ========================================================= + +-- ========================================================= +playerOnMove :: Move -> Player +-- --------------------------------------------------------- +playerOnMove (NextMove _ player _ _) = player +-- playerOnMove (Take2Balls _ player _ _ _) = player +playerOnMove (Take1Ball _ player _ _) = player +playerOnMove (PutBall _ player _ _ _) = player +-- ========================================================= + +-- ========================================================= +movesResult :: Move -> Int +-- --------------------------------------------------------- +movesResult (NextMove _ _ (w,b) _) = (-w) - b +movesResult m = error $ "movesRsult: " ++ show m +-- ========================================================= + +-- ========================================================= +coordinatesOfLastMove :: Move -> [Coordinate] +-- --------------------------------------------------------- +coordinatesOfLastMove (NextMove _ _ _ cs) = last cs +coordinatesOfLastMove _ = [] -- this should never happen +-- ========================================================= + +-- ========================================================= +unfinishedMove :: Move -> Bool +-- --------------------------------------------------------- +unfinishedMove (NextMove _ _ _ _) = False +unfinishedMove _ = True +-- ========================================================= +-- finishedMove :: Move -> Bool +-- --------------------------------------------------------- +-- finishedMove (NextMove _ _ _ _) = True +-- finishedMove _ = False +-- ========================================================= + +-- ========================================================= +-- | +-- This function takes current game status and returns list of possible moves out of given status. +-- netxPass creates a pair of lists. First list contains moves not finished yet, i.e. where part of the +-- move has been performed. E.g. ball has been taken but not yet put. This list has to be injected +-- to moves function again in order to be finished. +-- Second list contains all properly finished moves. +-- Finished move is recognized by player on move. Same player before and after move means +-- that move is to be continued. Different player - opposite. +-- It can be recognized by Move contructor. Only NextMove constructor points finished move. +moves :: Move -> [Move] +-- --------------------------------------------------------- +moves move@(NextMove pylos player _ _) = (concat.map moves) (fst nextPass) ++ snd nextPass + where nextPass = partition unfinishedMove (map (nextTaken move) (allMoveables player pylos) ++ + map (nextPut move) (allPutables 0 pylos)) +-- moves move@(Take2Balls pylos player _ _ _) = (concat.map moves) (fst nextPass) ++ snd nextPass +-- where nextPass = partition unfinishedMove (map (nextTaken move) (allTakeables player pylos coordinateForAny)) +moves move@(Take1Ball pylos player _ _) = (concat.map moves) (fst nextPass ) ++ snd nextPass ++ [terminate move] -- + where nextPass = partition unfinishedMove (map (nextTaken move) (allTakeables player pylos)) -- coordinate)) +moves move@(PutBall pylos player _ l _) = (concat.map moves) (fst nextPass) ++ snd nextPass + where nextPass = partition unfinishedMove (map (nextPut move) (allPutables l pylos)) +-- ========================================================= + +-- ========================================================= +-- coordinateForAny :: Coordinate +-- coordinateForAny = (1000,(0,0)) +-- ========================================================= + +-- ========================================================= +-- | This function returns new move after ball has been taken. +nextTaken :: Move -> Coordinate -> Move +-- --------------------------------------------------------- +nextTaken (NextMove pylos player (whites,blacks) cs) coordinate@(l,(x,y)) = + PutBall newPylos player (newQuantity player) (l+1) ([coordinate]:cs) + where newPylos = moveOnCoordinate player coordinate pylos + newQuantity WhitePlayer = (whites + 1,blacks) + newQuantity BlackPlayer = (whites,blacks + 1) +{- nextTaken (Take2Balls pylos player plA (whites,blacks) (c:cs)) coordinate + | anyTakeable player newPylos = Take1Ball newPylos player plA (newQuantity player) coordinate ((coordinate:c):cs) + | otherwise = NextMove newPylos (nextPlayer player) plA (newQuantity player) ((coordinate:c):cs) + where newPylos = moveOnCoordinate player coordinate pylos + newQuantity WhitePlayer = (whites + 1,blacks) + newQuantity BlackPlayer = (whites,blacks + 1) -} +nextTaken (Take1Ball pylos player (whites,blacks) (c:cs)) coordinate + = NextMove newPylos (nextPlayer player) (newQuantity player) ((coordinate:c):cs) + where newPylos = moveOnCoordinate player coordinate pylos + newQuantity WhitePlayer = (whites + 1,blacks) + newQuantity BlackPlayer = (whites,blacks + 1) +nextTaken move coordinate = error "nextTaken of PutBall" +-- ========================================================= + +-- ========================================================= +-- | This function returns new move after ball has been put. +nextPut :: Move -> Coordinate -> Move +-- --------------------------------------------------------- +nextPut m@(NextMove pylos player (whites,blacks) cs) coordinate + | ifTakeAfterPut newPylos player coordinate && notYetWon player (whites,blacks) + -- First ball is taken always from same place the last one has been put. This makes number of + -- possible moves smaller. + = Take1Ball pylos player (whites,blacks) ([coordinate,coordinate]:cs) -- must be not existing coordinate of not existing great level!! +-- = Take2Balls newPylos player plA (newQuantity player) ([coordinate]:cs) -- must be not existing coordinate of not existing great level!! + | ifTakeAfterPut newPylos player coordinate = NextMove newPylos (nextPlayer player) (newQuantity player) ([terminator,coordinate]:cs) -- to finish won game + | otherwise = NextMove newPylos (nextPlayer player) (newQuantity player) ([coordinate]:cs) + where newPylos = moveOnCoordinate player coordinate pylos + newQuantity WhitePlayer = (whites - 1,blacks) + newQuantity BlackPlayer = (whites,blacks - 1) + notYetWon WhitePlayer (_,0) = False + notYetWon WhitePlayer _ = True + notYetWon BlackPlayer (0,_) = False + notYetWon BlackPlayer _ = True +nextPut (PutBall pylos player (whites,blacks) level (c:cs)) coordinate + | ifTakeAfterPut newPylos player coordinate = Take1Ball pylos player (whites,blacks) ((coordinate:coordinate:c):cs) +-- Take2Balls newPylos player plA (newQuantity player) ((coordinate:c):cs) + | otherwise = NextMove newPylos (nextPlayer player) (newQuantity player) ((coordinate:c):cs) + where newPylos = moveOnCoordinate player coordinate pylos + newQuantity WhitePlayer = (whites - 1,blacks) + newQuantity BlackPlayer = (whites,blacks - 1) +nextPut move _ = error "nextPut of Take2Balls" +-- ========================================================= + +-- ========================================================= +-- | Instead of taking 2nd ball player can decide to finish own turn in status quo. +terminate :: Move -> Move +-- --------------------------------------------------------- +terminate (Take1Ball pylos player (w,b) (c:cs)) = NextMove pylos (nextPlayer player) (newQuantity player) ((terminator:c):cs) --(w,b) ((terminator:c):cs) -- + -- Following 2 lines are supposed to cause not choosing terminator. + where newQuantity WhitePlayer = (w,b + 1) + newQuantity BlackPlayer = (w + 1,b) +terminate _ = error "terminate: input not matched" +-- ========================================================= + +-- ========================================================= +-- | +-- Checks if player is allowed to take any ball after he||she's just put one (eg. any square of 4 is full) +-- and if he||she can take any ball - which is obvious, because recently put ball always can be taken. +-- anyBallTakeable :: Pylos -> Player -> Bool +-- anyBallTakeable pylos player = ifTakeAfterPut pylos player && anyTakeable player pylos +-- ========================================================= + +-- ========================================================= +-- | Gives list of all coordinates where one can put a ball. +-- Takes level and current game situation. +allPutables :: GLint -> Pylos -> [Coordinate] +-- --------------------------------------------------------- +allPutables level pylos = filter (putable pylos) keys + where keys = [(l,(x,y)) | l<-[level..s-1], x<-[0..s-l-1], y<-[0..s-l-1]] + s = size pylos +-- ========================================================= + +-- ========================================================= +-- | Gives list of all moveable fields on the board. +allMoveables :: Player -> Pylos -> [Coordinate] +-- --------------------------------------------------------- +allMoveables player pylos = filter (moveable player pylos) keys + where keys = [(l,(x,y)) | l<-[0..s-1], x<-[0..s-l-1], y<-[0..s-l-1]] + s = size pylos +-- ========================================================= + +-- ========================================================= +-- | Gives list of all takeable fields on the board, that fulfil additional condition. +-- This condition is order condition which prevents taking two same balls in different order. +--allTakeables :: Player -> Pylos -> Coordinate -> [Coordinate] +allTakeables :: Player -> Pylos -> [Coordinate] +-- --------------------------------------------------------- +--allTakeables player pylos c = filter (takeable player pylos) keys +allTakeables player pylos = filter (takeable player pylos) keys + where keys = [(l,(x,y)) | l<-[0..s-1], x<-[0..s-l-1], y<-[0..s-l-1]] -- , inProperOrder c (l,(x,y))] + s = size pylos +-- ========================================================= + +{-- ========================================================= +inProperOrder :: Coordinate -> Coordinate -> Bool +-- --------------------------------------------------------- +inProperOrder oldC@(l1,(x1,y1)) newC@(l2,(x2,y2)) = l1 > l2 || + l1 == l2 && (x1 > x2 || + x1 == x2 && y1 > y2) +-- ========================================================= +-} +
+ source/hpylos.hs view
@@ -0,0 +1,209 @@+-- ================================== +-- Module name: hpylos +-- Project: Foo +-- Copyright (C) 2008 Bartosz Wójcik +-- Created on: 24.10.2008 +-- Last update: 19.11.2008 +-- Version: % + +{- 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 <http://www.gnu.org/licenses/>. +-} +-- ================================== +module Main where + +-- Simply user interface reading parameters from file or +-- aksing for initial game parameters if parameter file doesn't exist. + +import PylosDisplay (displayPylos) +import PylosAI (Algorithm (..)) +import EEConfig (ParameterInput, + ParameterOutput, + ParameterTree, + matchParamsL, + matchParamsT, + (!), + member) +import PylosEvaluator (PlayerType, + State (..), + evaluatePylos) +import PylosBoard (Pylos (..)) +import System.IO.Error +import Data.IORef + + +main = do + inputText <- catch (readFile "pylos.conf") (\e -> if isEOFError e || isDoesNotExistError e then return [] else ioError e) + let paramsList = matchParamsL params inputText + let paramsTree = matchParamsT paramsList + if evaluatorAll paramsTree + then evaluateAll (setVerbosity paramsTree) + else do + alg1 <- findAlgorithm 1 paramsTree paramsList + alg2 <- findAlgorithm 2 paramsTree paramsList + if evaluatorOnly paramsTree + then evaluatePylos 4 alg1 alg2 (setVerbosity paramsTree) >>= \x -> return () + else displayPylos 4 alg1 alg2 (setVerbosity paramsTree) + + +-- ========================================================= +evaluatorOnly :: ParameterTree -> Bool +evaluatorOnly paramsTree | "-evaluator" `member` paramsTree && paramsTree ! "-evaluator" == "only" = True + | otherwise = False +-- ========================================================= + +-- ========================================================= +evaluatorAll :: ParameterTree -> Bool +evaluatorAll paramsTree | "-evaluator" `member` paramsTree && paramsTree ! "-evaluator" == "all" = True + | otherwise = False +-- ========================================================= + +-- ========================================================= +allPlayers :: [PlayerType] +-- allPlayers = [Just (alg,depth,breadth,nbr) | alg <- [SimpleDiff ..], depth <- [1 .. 6], breadth <- [0,11,13,16], nbr <- 0:[depth + 2 .. 6]] +--pylos4 allPlayers = [Just (alg,depth,breadth,nbr) | alg <- [SimpleDiff .. SimpleDiffPlusVal], depth <- [4 .. 6], breadth <- [0,11], nbr <- 0:[depth .. 6]] +allPlayers = [Just (alg,depth,breadth,nbr) | alg <- [SimpleDiff .. MixedDiff], depth <- [6], breadth <- [0], nbr <- [0,7]] +-- ========================================================= + +-- ========================================================= +evaluateAll :: Int -> IO () +evaluateAll verb = mapM_ (\pl1 -> mapM_ (\pl2 -> evaluatePylos 4 pl1 pl2 verb >>= \x -> printResult x) allPlayers) allPlayers +-- ========================================================= + +-- ========================================================= +printResult :: State -> IO () +printResult state = do + (w,b) <- readIORef $ nbrBalls state + pl1 <- readIORef $ player1 state + pl2 <- readIORef $ player2 state + putStrLn $ show pl1 ++ ";" ++ resultW (w,b) ++ ";" ++ show w ++ " ; " ++ + show pl2 ++ ";" ++ resultB (w,b) ++ ";" ++ show b +-- ========================================================= + +-- ========================================================= +resultW :: (Int,Int) -> String +resultW (0,b) = "0" +resultW (w,0) = "2" +resultW _ = "1" +-- ========================================================= +resultB :: (Int,Int) -> String +resultB (0,b) = "2" +resultB (w,0) = "0" +resultB _ = "1" +-- ========================================================= + +-- ========================================================= +paramToAlg :: String -> (Maybe (Algorithm,Int)) +paramToAlg "h" = Nothing +paramToAlg alg = Just ((toEnum . (\n -> n - fromEnum 'a') . fromEnum . head) alg,(read . tail) alg) +-- ========================================================= + +-- ========================================================= +params :: [ParameterInput] +params = [("-pl1",algNum),("-pl2",algNum), + ("-br1","0":(map show [5..30])),("-br2","0":(map show [5..30])), + ("-dp1","0":(map show [2..8])),("-dp2","0":(map show [2..8])), + ("-verbose",["0","1","2","3"]), + ("-evaluator",["only","all"])] +-- ========================================================= + +-- ========================================================= +algDisp :: String -> [String] +algDisp text = [text] ++ ["Human - h"] ++ map (\(a,n) -> (show a ++ " - " ++ [n] ++ "1 .. " ++ [n] ++ "8")) (zip [SimpleDiff ..] ['a'..]) + ++ ["Or select just level 0-9"] +-- ========================================================= + +-- ========================================================= +-- | There are 6 levels of search depth hardcoded. +algNum :: [String] +algNum = "h" : (concat $ map (\(a,x) -> map (\n -> x:n:[]) ['1'..'8']) (zip [SimpleDiff ..] ['a'..])) ++ map show [0..9] +-- ========================================================= + +-- ========================================================= +enterValue :: [String] -> [String] -> IO String +enterValue possibleValues messages = do + mapM putStrLn messages + word <- getLine + if any (word ==) possibleValues + then return word + else enterValue possibleValues messages +-- ========================================================= + +-- ========================================================= +-- | +-- Always selects presorted search tree +selectAlgorithm :: String -> IO PlayerType +selectAlgorithm text = do + alg <- enterValue algNum (algDisp text) -- >>= (\x -> return (read x)) + if head alg == 'h' + then return Nothing + else return $ selAlg alg (Just (SimpleDiff,0,0,0)) --(Just ((toEnum . (\n -> n - fromEnum 'a') . fromEnum . head) alg, (read . tail) alg, 0, 0)) +-- ========================================================= + +-- ========================================================= +-- | selects algorithm from pylos.conf file, if not exists from stdin +findAlgorithm :: Int -> ParameterTree -> [ParameterOutput] -> IO PlayerType +findAlgorithm 1 paramsTree paramList | "-pl1" `member` paramsTree = return $ findParam1 paramList -- paramToAlg (paramsTree Map.! param) + | otherwise = selectAlgorithm "Select player 1" +findAlgorithm 2 paramsTree paramList | "-pl2" `member` paramsTree = return $ findParam2 paramList + | otherwise = selectAlgorithm "Select player 2" +-- ========================================================= + +-- ========================================================= +findParam1 :: [ParameterOutput] -> PlayerType +findParam1 input = foldl fParam1 defaultParam input +-- ========================================================= +findParam2 input = foldl fParam2 defaultParam input +-- ========================================================= + +-- ========================================================= +defaultParam :: PlayerType +defaultParam = Just (toEnum 0, 2, 0, 0) +-- ========================================================= + +-- ========================================================= +fParam1 :: PlayerType -> ParameterOutput -> PlayerType +fParam1 _ ("-pl1","h") = Nothing +fParam1 (Just (a,b,c,d)) ("-pl1",val) = selAlg val (Just (a,b,c,d)) +fParam1 (Just (a,b,c,d)) ("-br1",val) = Just (a,b,read val,d) +fParam1 (Just (a,b,c,d)) ("-dp1",val) = Just (a,b,c,read val) +fParam1 pl _ = pl +-- ========================================================= +fParam2 :: PlayerType -> ParameterOutput -> PlayerType +fParam2 _ ("-pl2","h") = Nothing +fParam2 (Just (a,b,c,d)) ("-pl2",val) = selAlg val (Just (a,b,c,d)) +fParam2 (Just (a,b,c,d)) ("-br2",val) = Just (a,b,read val,d) +fParam2 (Just (a,b,c,d)) ("-dp2",val) = Just (a,b,c,read val) +fParam2 pl _ = pl +-- ========================================================= + +-- ========================================================= +selAlg :: String -> PlayerType -> PlayerType +selAlg "0" _ = Just (SimpleDiff,1,0,0) +selAlg "1" _ = Just (SimpleDiffAdvance,1,0,0) +selAlg "2" _ = Just (SimpleDiffAdvance,2,0,0) +selAlg "3" _ = Just (SimpleDiffAdvance,3,0,0) +selAlg "4" _ = Just (SimpleDiffAdvance,4,0,0) +selAlg "5" _ = Just (SimpleDiffAdvance,5,0,0) +selAlg "6" _ = Just (SimpleDiffAdvance,6,0,0) +selAlg "7" _ = Just (SimpleDiffAdvance,6,0,7) +selAlg "8" _ = Just (SimpleDiffAdvance,7,0,0) +selAlg "9" _ = Just (SimpleDiffAdvance,8,0,0) +selAlg val (Just (_,_,c,d)) = Just ((toEnum . (\n -> n - fromEnum 'a') . fromEnum . head) val, (read . tail) val, c, d) +-- ========================================================= + +-- ========================================================= +setVerbosity :: ParameterTree -> Int +setVerbosity paramsTree | "-verbose" `member` paramsTree = read $ paramsTree ! "-verbose" + | otherwise = 1 +-- =========================================================