├── .gitignore ├── CODE_OF_CONDUCT.md ├── LICENSE ├── README.md ├── build.sbt ├── project ├── build.properties └── plugins.sbt ├── src ├── main │ ├── resources │ │ └── logback.xml │ └── scala │ │ └── caart │ │ ├── Arguments.scala │ │ ├── Launcher.scala │ │ ├── Main.scala │ │ ├── engine │ │ ├── Automaton.scala │ │ ├── Board.scala │ │ ├── Cell.scala │ │ ├── EventHub.scala │ │ ├── GlobalCell.scala │ │ ├── GlobalUpdateStrategy.scala │ │ ├── UpdateStrategy.scala │ │ └── fields │ │ │ ├── CMYK.scala │ │ │ ├── Dir2D.scala │ │ │ ├── Pos2D.scala │ │ │ ├── RGB.scala │ │ │ └── package.scala │ │ ├── examples │ │ ├── Chase.scala │ │ ├── GameOfLife.scala │ │ ├── LangtonsAnt.scala │ │ ├── LangtonsColors.scala │ │ └── Snake.scala │ │ └── visualisation │ │ ├── Game.scala │ │ ├── World.scala │ │ ├── examples │ │ ├── ChaseWorld.scala │ │ ├── GameOfLifeWorld.scala │ │ ├── LangtonsAntWorld.scala │ │ ├── LangtonsColorsWorld.scala │ │ └── SnakeWorld.scala │ │ └── package.scala └── test │ └── scala │ └── caart │ └── engine │ └── fields │ ├── CMYKSpec.scala │ └── Dir2DSpec.scala └── system └── Readme.txt /.gitignore: -------------------------------------------------------------------------------- 1 | *.cache 2 | .cache 3 | */logs 4 | */project/project 5 | */project/target 6 | */project/metals.sbt 7 | *target/ 8 | */tmp/ 9 | *.history 10 | */dist/ 11 | *.idea/ 12 | */*.iml 13 | */out 14 | */.idea_modules 15 | */.classpath 16 | */.project 17 | */RUNNING_PID 18 | */.settings 19 | *.class 20 | */bin 21 | *.target/* 22 | *.diff 23 | *.log 24 | *.sc 25 | *.worksheet* 26 | *projectFilesBackup/* 27 | *src/main/resources/evolution/* 28 | *contextMatrixTest* 29 | .cache-main 30 | .cache-tests 31 | *.odp 32 | *.odt 33 | *.gif 34 | *.png 35 | *.jpg 36 | *.svg 37 | *.bloop* 38 | *.metals* 39 | *.bsp -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | In the interest of fostering an open and welcoming environment, we as 6 | contributors and maintainers pledge to making participation in our project and 7 | our community a harassment-free experience for everyone, regardless of age, body 8 | size, disability, ethnicity, sex characteristics, gender identity and expression, 9 | level of experience, education, socio-economic status, nationality, personal 10 | appearance, race, religion, or sexual identity and orientation. 11 | 12 | ## Our Standards 13 | 14 | Examples of behavior that contributes to creating a positive environment 15 | include: 16 | 17 | * Using welcoming and inclusive language 18 | * Being respectful of differing viewpoints and experiences 19 | * Gracefully accepting constructive criticism 20 | * Focusing on what is best for the community 21 | * Showing empathy towards other community members 22 | 23 | Examples of unacceptable behavior by participants include: 24 | 25 | * The use of sexualized language or imagery and unwelcome sexual attention or 26 | advances 27 | * Trolling, insulting/derogatory comments, and personal or political attacks 28 | * Public or private harassment 29 | * Publishing others' private information, such as a physical or electronic 30 | address, without explicit permission 31 | * Other conduct which could reasonably be considered inappropriate in a 32 | professional setting 33 | 34 | ## Our Responsibilities 35 | 36 | Project maintainers are responsible for clarifying the standards of acceptable 37 | behavior and are expected to take appropriate and fair corrective action in 38 | response to any instances of unacceptable behavior. 39 | 40 | Project maintainers have the right and responsibility to remove, edit, or 41 | reject comments, commits, code, wiki edits, issues, and other contributions 42 | that are not aligned to this Code of Conduct, or to ban temporarily or 43 | permanently any contributor for other behaviors that they deem inappropriate, 44 | threatening, offensive, or harmful. 45 | 46 | ## Scope 47 | 48 | This Code of Conduct applies both within project spaces and in public spaces 49 | when an individual is representing the project or its community. Examples of 50 | representing a project or community include using an official project e-mail 51 | address, posting via an official social media account, or acting as an appointed 52 | representative at an online or offline event. Representation of a project may be 53 | further defined and clarified by project maintainers. 54 | 55 | ## Enforcement 56 | 57 | Instances of abusive, harassing, or otherwise unacceptable behavior may be 58 | reported by contacting the project team at maciej.gorywoda@wire.com. All 59 | complaints will be reviewed and investigated and will result in a response that 60 | is deemed necessary and appropriate to the circumstances. The project team is 61 | obligated to maintain confidentiality with regard to the reporter of an incident. 62 | Further details of specific enforcement policies may be posted separately. 63 | 64 | Project maintainers who do not follow or enforce the Code of Conduct in good 65 | faith may face temporary or permanent repercussions as determined by other 66 | members of the project's leadership. 67 | 68 | ## Attribution 69 | 70 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, 71 | available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html 72 | 73 | [homepage]: https://www.contributor-covenant.org 74 | 75 | For answers to common questions about this code of conduct, see 76 | https://www.contributor-covenant.org/faq 77 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # CA Art 2 | 3 | Hi there. 4 | This repository consists of a few examples of Cellular Automata, the common part of the code ("the engine") and the graphical user interface made in JavaFX and FXGL. 5 | 6 | After compilation, you can run an example from the `sbt` shield. There are five of them: 7 | 1. Game of Life ("life") 8 | 2. Langton's Ant ("ant") 9 | 3. Langton's Ants in color ("antc") 10 | 4. Chase ("chase") 11 | 5. Snake ("snake") 12 | 13 | You can run each one by writing `run ` in the sbt console or if you want more fine control over the example's configuration you can use: 14 | ``` 15 | >run example=[...] dim=[...] scale=[...] delay=[...] enforcegc=[...] 16 | ``` 17 | where the arguments are: 18 | - `example` - the name of the example (no default, choose something) 19 | - `dim` - the length of one side of the board (default = 100) 20 | - `scale` - the length of one side of a cell (default = 8) 21 | - `delay` - the forced delay between turns in milliseconds (default = 0) 22 | There is also `enforcegc`. The cellular automaton generates a new board every turn and discards the old one. This creates a lot of garbage to collect and if your JDK use a slow, unoptimized GC then after a few hundreds turns you will start to experience more and more hiccups. `enforcegc`, if set to `true`, enforces GC every turn. It results in slower simulations but it fixes the problem. Type `run example 1 enforcegc true` and see for yourself. 23 | 24 | If you run the Game of Life example (with `run life`) you will see an empty, white window. This is the initial board. You can populate it with the left mouse clicks. When you're done, start the animation by hitting the space bar. You can always stop the simulation again (with the space bar) and edit the board. 25 | 26 | ### If you want to write your own cellular automata ... 27 | 28 | ... watch [the talk](https://www.youtube.com/watch?v=0ABjVP0st08), read the comments in the code, figure out how the Game of Life example works, and start from writing its copy. Apart from the cell's case class you will also need to tell the graphic library how to turn a cell into a colored square on the screen (the `toColor` method), and how to interpret clicks. You can also contact me on Twitter ([@makingthematrix](https://twitter.com/makingthematrix)). 29 | 30 | A link to the "slides" - the animation in VideoScribe that was a big part of the talk: [here](https://drive.google.com/file/d/1wsKXR3r-_lGhPVG-KyxA7aJ_OOL5EVy2/view?usp=sharing) 31 | -------------------------------------------------------------------------------- /build.sbt: -------------------------------------------------------------------------------- 1 | name := "ca_art" 2 | 3 | version := "0.3" 4 | scalaVersion := "2.13.7" 5 | 6 | scalacOptions ++= Seq( 7 | "-deprecation", 8 | "-feature", 9 | "-unchecked", 10 | "-encoding", 11 | "utf8", 12 | "-opt:unreachable-code", 13 | "-opt:simplify-jumps", 14 | "-opt:compact-locals", 15 | "-opt:copy-propagation", 16 | "-opt:redundant-casts", 17 | "-opt:box-unbox", 18 | "-opt:nullness-tracking", 19 | "-opt:closure-invocations", 20 | "-opt:allow-skip-core-module-init", 21 | "-opt:assume-modules-non-null", 22 | "-opt:allow-skip-class-loading", 23 | "-opt:inline" 24 | ) 25 | 26 | libraryDependencies ++= Seq( 27 | "org.scala-lang.modules" %% "scala-parallel-collections" % "1.0.3", 28 | "com.wire" %% "wire-signals" % "1.0.0", 29 | "ch.qos.logback" % "logback-classic" % "1.2.6", 30 | "com.typesafe.scala-logging" %% "scala-logging" % "3.9.4", 31 | "com.github.almasb" % "fxgl"% "11.17", 32 | //Test dependencies 33 | "org.scalameta" %% "munit" % "0.7.26" % "test" 34 | ) 35 | 36 | lazy val nativeImage = 37 | project 38 | .in(file(".")) 39 | .enablePlugins(NativeImagePlugin) 40 | .settings( 41 | Compile / mainClass := Some("caart.Main"), 42 | nativeImageInstalled := true 43 | ) 44 | 45 | testFrameworks += new TestFramework("munit.Framework") 46 | 47 | Test / parallelExecution := true 48 | fork := true 49 | Test / fork := true 50 | 51 | developers := List( 52 | Developer("makingthematrix", "Maciej Gorywoda", "maciej.gorywoda@wire.com", url("https://github.com/makingthematrix")) 53 | ) 54 | 55 | licenses := Seq("GPL 3.0" -> url("https://www.gnu.org/licenses/gpl-3.0.en.html")) 56 | -------------------------------------------------------------------------------- /project/build.properties: -------------------------------------------------------------------------------- 1 | sbt.version = 1.5.5 -------------------------------------------------------------------------------- /project/plugins.sbt: -------------------------------------------------------------------------------- 1 | addSbtPlugin("org.scalameta" % "sbt-native-image" % "0.3.1") -------------------------------------------------------------------------------- /src/main/resources/logback.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n 5 | 6 | 7 | 8 | 9 | 10 | logs/lastlogs.log 11 | false 12 | 13 | %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | -------------------------------------------------------------------------------- /src/main/scala/caart/Arguments.scala: -------------------------------------------------------------------------------- 1 | package caart 2 | 3 | import caart.Arguments.{GameOfLifeExample, Example} 4 | 5 | final case class Arguments(dim: Int = 100, // the number of cells in one dimension of the automaton 6 | it: Int = 100, // the number of iterations the automaton will run 7 | step: Int = 1, // how often the visualisation should be refresh 8 | scale: Int = 8, // how many pixels per cell in the visualisation 9 | delay: Long = 0L, // interval between two updates in milliseconds 10 | enforceGC: Boolean = false, // enforce garbage collection every turn 11 | example: Example = GameOfLifeExample 12 | ) { 13 | lazy val windowSize: Int = dim * scale 14 | } 15 | 16 | object Arguments { 17 | sealed trait Example { val str: String } 18 | case object GameOfLifeExample extends Example { override val str: String = "life" } 19 | case object LangtonsAntExample extends Example { override val str: String = "ant" } 20 | case object LangtonsColorsExample extends Example { override val str: String = "antc" } 21 | case object ChaseExample extends Example { override val str: String = "chase" } 22 | case object SnakeExample extends Example { override val str: String = "snake" } 23 | 24 | val examples = Seq(GameOfLifeExample, LangtonsAntExample, LangtonsColorsExample, ChaseExample, SnakeExample) 25 | 26 | def parseArguments(args: Seq[String]): Arguments = 27 | if (args.size == 1) 28 | args.head.toLowerCase.trim match { 29 | case "life" => Arguments(example = Arguments.GameOfLifeExample) 30 | case "ant" => Arguments(example = Arguments.LangtonsAntExample) 31 | case "antc" => Arguments(example = Arguments.LangtonsColorsExample) 32 | case "chase" => Arguments(example = Arguments.ChaseExample) 33 | case "snake" => Arguments(example = Arguments.SnakeExample, dim = 40, delay = 60, scale = 16) 34 | } 35 | else 36 | args.flatMap(_.split('=')).sliding(2, 2).foldLeft(Arguments()){ 37 | case (acc, Seq("dim", value)) => acc.copy(dim = Integer.parseInt(value)) 38 | case (acc, Seq("it", value)) => acc.copy(it = Integer.parseInt(value)) 39 | case (acc, Seq("step", value)) => acc.copy(step = Integer.parseInt(value)) 40 | case (acc, Seq("scale", value)) => acc.copy(scale = Integer.parseInt(value)) 41 | case (acc, Seq("delay", value)) => acc.copy(delay = Integer.parseInt(value).toLong) 42 | case (acc, Seq("enforcegc", "true")) => acc.copy(enforceGC = true) 43 | case (acc, Seq("enforcegc", "false")) => acc.copy(enforceGC = false) 44 | case (acc, Seq("example", value)) => 45 | examples.find(_.str == value) match { 46 | case Some(ex) => acc.copy(example = ex) 47 | case _ => println(s"unrecognized example: $value"); acc 48 | } 49 | case (acc, Seq(name, value)) => 50 | println(s"unrecognized parameter: $name with value $value"); acc 51 | case (acc, _) => 52 | println(s"something went wrong"); acc 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /src/main/scala/caart/Launcher.scala: -------------------------------------------------------------------------------- 1 | package caart 2 | 3 | import caart.visualisation.Game 4 | import com.almasb.fxgl.app.GameApplication 5 | import javafx.application.Application 6 | import javafx.scene.Scene 7 | import javafx.stage.Stage 8 | 9 | import scala.jdk.CollectionConverters._ 10 | 11 | final class Launcher extends Application { 12 | override def start(stage: Stage): Unit = { 13 | val args = Arguments.parseArguments(getParameters.getRaw.asScala.toSeq) 14 | stage.setScene(new Scene(GameApplication.embeddedLaunch(new Game(args)), args.windowSize, args.windowSize)) 15 | stage.show() 16 | } 17 | } 18 | 19 | -------------------------------------------------------------------------------- /src/main/scala/caart/Main.scala: -------------------------------------------------------------------------------- 1 | package caart 2 | 3 | import javafx.application.Application 4 | 5 | object Main extends App { 6 | Application.launch(classOf[Launcher], args: _*) 7 | } 8 | -------------------------------------------------------------------------------- /src/main/scala/caart/engine/Automaton.scala: -------------------------------------------------------------------------------- 1 | package caart.engine 2 | 3 | import caart.engine.GlobalCell.Empty 4 | import caart.engine.fields.{Dir2D, Pos2D} 5 | import com.typesafe.scalalogging.LazyLogging 6 | 7 | import scala.collection.mutable 8 | 9 | /** The main class of a cellular automaton. 10 | * 11 | * To create a cellular automaton, the user has to specify the size of the board, `dim`, (for simpilicity reasons 12 | * before the ScalaIO talk I assumed the board has the same length in all dimensions), and provide 13 | * a function which will be used to create automaton's cells. Optionally, the user can provide a specialized 14 | * function for creating the board, eg. in case of cell.a. which can be optimized by skipping computations 15 | * on a part of the board. 16 | * 17 | * TODO: Move away from the default board being a torus with a square surface. `dim` should be specified inside 18 | * `applyBoard`, and `applyBoard` should not be optional. Instead, allow for choosing from a list of utility methods, 19 | * similar to how neighborhoods work. 20 | * 21 | * @constructor Takes the board edge size, a function for creating cells, and a function to create the board. 22 | */ 23 | class Automaton[C <: Cell[C], GC <: GlobalCell[C, GC]]( 24 | override val dim: Int, 25 | private val createCell: (Pos2D, Cell.AutoContract[C, GC]) => C, 26 | private val createBoard: (Int, Pos2D => C) => Board[C], 27 | private val createGlobalCell: GlobalCell.AutoContract[C, GC] => GC, 28 | override val updateStrategy: UpdateStrategy.Type[C], 29 | override val globalUpdateStrategy: GlobalUpdateStrategy.Type[C, GC] 30 | ) extends Iterator[Board[C]] 31 | with Cell.AutoContract[C, GC] 32 | with GlobalCell.AutoContract[C, GC] 33 | with LazyLogging { self: Automaton[C, GC] => 34 | override val eventHub: EventHub[C, GC] = new EventHub 35 | 36 | private var _board: Board[C] = createBoard(dim, createCell(_, this)) 37 | private var _globalCell: GC = createGlobalCell(this) 38 | 39 | override final def globalCell: GC = _globalCell 40 | 41 | final def updatedByEvents(cell: C): Option[C] = { 42 | val events: List[C#CE] = eventHub.oneCellEvents(cell.pos) 43 | if (events.nonEmpty) cell.updateFromEvents(events) else None 44 | } 45 | 46 | final def globalUpdatedByEvents: Option[GC] = globalCell.updateFromEvents(eventHub.globalEvents) 47 | 48 | override def next(): Board[C] = { 49 | _globalCell = _globalCell.next(eventHub.drainGlobalEvents()) 50 | _board = _board.next(eventHub.drainCellEvents()) 51 | _board 52 | } 53 | 54 | override def hasNext: Boolean = true 55 | 56 | override def board: Board[C] = _board 57 | 58 | /** Updates the current state of the iterator. 59 | * 60 | * Used to provide the initial state of the automaton or to perform a change in the middle of the main loop. 61 | * `updater` is a function which for a given cell returns its updated version (or the cell itself, without 62 | * changes). It's called for every cell on the board in order to create an updated copy of the board, which 63 | * in turn replaces the old one. 64 | * 65 | * @param updater Called for every cell; creates an updated copy or returns the old one. 66 | * @return the updated board 67 | */ 68 | def update(updater: C => C): Board[C] = { 69 | _board = _board.copy(updater) 70 | _board 71 | } 72 | 73 | def updateCell(pos: Pos2D)(updater: C => C): Board[C] = { 74 | _board = _board.copy(pos)(updater) 75 | _board 76 | } 77 | 78 | def updateGlobal(updater: GC => GC): GC = { 79 | _globalCell = updater(_globalCell) 80 | _globalCell 81 | } 82 | 83 | def cells: Vector[C] = _board.cells 84 | val positions: Set[Pos2D] = Pos2D(dim).toSet 85 | override def findCell(pos: Pos2D): C = _board.findCell(pos) 86 | 87 | /** 88 | * The von Neumann's neighborhood is a collection of four cells which are 89 | * up, right, down, and left from the given one. The method returns them 90 | * as a map where keys are the corresponding Dir2D constants. 91 | */ 92 | override final def neumann(pos: Pos2D): Map[Dir2D, C] = 93 | neumannFind(pos).map { case (dir, neighbor) => dir -> _board.findCell(neighbor) } 94 | 95 | private final val neumannMap = new mutable.HashMap[Pos2D, Map[Dir2D, Pos2D]]() 96 | private final def neumannFind(pos: Pos2D): Map[Dir2D, Pos2D] = 97 | neumannMap.getOrElseUpdate(pos, Dir2D.dirs4.map(dir => dir -> pos.move(dir)).toMap) 98 | 99 | /** 100 | * The Moore's neighborhood is a collection of eight cells which are 101 | * up, up-right, right, right-down, down, down-left, left, and left-up from 102 | * the given one. The method returns them as a map where keys are 103 | * the corresponding Dir2D constants. 104 | */ 105 | override final def moore(pos: Pos2D): Map[Dir2D, C] = 106 | mooreFind(pos).map { case (dir, neighbor) => dir -> _board.findCell(neighbor) } 107 | 108 | private final val mooreMap = new mutable.HashMap[Pos2D, Map[Dir2D, Pos2D]]() 109 | private final def mooreFind(pos: Pos2D): Map[Dir2D, Pos2D] = 110 | mooreMap.getOrElseUpdate(pos, Dir2D.dirs8.map(dir => dir -> pos.move(dir)).toMap) 111 | } 112 | 113 | class AutomatonNoGlobal[C <: Cell[C]](override val dim: Int, 114 | private val createCell: (Pos2D, Cell.AutoContractNoGlobal[C]) => C, 115 | private val createBoard: (Int, Pos2D => C) => Board[C], 116 | override val updateStrategy: UpdateStrategy.Type[C]) 117 | extends Automaton[C, Empty[C]]( 118 | dim, 119 | createCell, 120 | createBoard, 121 | (_: GlobalCell.AutoContract[C, Empty[C]]) => GlobalCell.empty[C], 122 | updateStrategy, 123 | GlobalUpdateStrategy.noUpdate[C, Empty[C]] 124 | ) 125 | 126 | object Automaton { 127 | trait Creator[C <: Cell[C], GC <: GlobalCell[C, GC]] { 128 | def cell(pos: Pos2D, auto: Cell.AutoContract[C, GC]): C 129 | def globalCell(auto: GlobalCell.AutoContract[C, GC]): GC 130 | 131 | def automaton(dim: Int, 132 | updateStrategy: UpdateStrategy.Type[C] = UpdateStrategy.eventsOverrideSelf[C], 133 | globalUpdateStrategy: GlobalUpdateStrategy.Type[C, GC] = GlobalUpdateStrategy.eventsOverrideSelf[C, GC]): Automaton[C, GC] = 134 | new Automaton[C, GC](dim, cell, Board.apply, globalCell, updateStrategy, globalUpdateStrategy) 135 | } 136 | 137 | trait CreatorNoGlobal[C <: Cell[C]] extends Creator[C, Empty[C]] { 138 | override def globalCell(auto: GlobalCell.AutoContract[C, Empty[C]]): Empty[C] = GlobalCell.empty[C] 139 | 140 | def automatonNoGlobal(dim: Int, updateStrategy: UpdateStrategy.Type[C] = UpdateStrategy.eventsOverrideSelf[C]): AutomatonNoGlobal[C] = 141 | new AutomatonNoGlobal[C](dim, cell, Board.apply, updateStrategy) 142 | } 143 | } 144 | -------------------------------------------------------------------------------- /src/main/scala/caart/engine/Board.scala: -------------------------------------------------------------------------------- 1 | package caart.engine 2 | 3 | import caart.engine.fields.Pos2D 4 | import com.typesafe.scalalogging.LazyLogging 5 | 6 | import scala.collection.parallel.CollectionConverters.ImmutableMapIsParallelizable 7 | import scala.collection.parallel.immutable.ParMap 8 | 9 | /** A 2D board; both the container for cells and the graph of their spatial relations. 10 | * 11 | * @param dim length of the edge 12 | * @param map a map of identifiers to cells 13 | * @tparam C the exact case class implementing the cell 14 | */ 15 | class Board[C <: Cell[C]](dim: Int, protected val map: ParMap[Pos2D, C]) extends LazyLogging { 16 | def findCell(pos: Pos2D): C = map(Board.wrap(pos, dim)) 17 | 18 | final def next(events: Map[Pos2D, Iterable[C#CE]]): Board[C] = 19 | copy { c => c.next(events.getOrElse(c.pos, Nil)) } 20 | 21 | def copy(pos: Pos2D)(updater: C => C): Board[C] = { 22 | val wrappedPos = Board.wrap(pos, dim) 23 | new Board(dim, map.updated(wrappedPos, updater(map(wrappedPos)))) 24 | } 25 | 26 | def copy(updater: C => C): Board[C] = new Board(dim, map.map { case (pos, cell) => pos -> updater(cell) }) 27 | 28 | final def cells: Vector[C] = map.values.toVector 29 | 30 | final def -(board: Board[C]): Vector[C] = 31 | map.collect { case (id, cell) if board.map(id) != cell => cell }.toVector 32 | } 33 | 34 | object Board { 35 | private val Empty: Board[_] = new Board(0, ParMap.empty[Pos2D, Nothing]) 36 | def empty[C <: Cell[C]]: Board[C] = Empty.asInstanceOf[Board[C]] 37 | 38 | def wrap(pos: Pos2D, dim: Int): Pos2D = 39 | if (pos.x >= 0 && pos.x < dim) { 40 | if (pos.y >= 0 && pos.y < dim) pos 41 | else pos.copy(y = (pos.y + dim) % dim) 42 | } else { 43 | if (pos.y >= 0 && pos.y < dim) pos.copy(x = (pos.x + dim) % dim) 44 | else pos.copy(x = (pos.x + dim) % dim, y = (pos.y + dim) % dim) 45 | } 46 | 47 | /** Builds a map of identifiers to the automaton's cells. 48 | * 49 | * @param dim length of the board's edge 50 | * @param findCell a function building the cell 51 | * @tparam C type of the cell 52 | * @return a parallel map of identifiers (based on the given cell's position) to the cells 53 | */ 54 | def buildMap[C <: Cell[C]](dim: Int, findCell: Pos2D => C): ParMap[Pos2D, C] = 55 | Pos2D(dim).map(pos => pos -> findCell(pos)).toMap.par 56 | 57 | /** Builds the board of the given automaton's cells. 58 | * 59 | * @param dim length of the board's edge 60 | * @param findCell a function building the cell 61 | * @tparam C type of the cell 62 | * @return the board 63 | */ 64 | def apply[C <: Cell[C]](dim: Int, findCell: Pos2D => C): Board[C] = new Board(dim, buildMap(dim, findCell)) 65 | } 66 | -------------------------------------------------------------------------------- /src/main/scala/caart/engine/Cell.scala: -------------------------------------------------------------------------------- 1 | package caart.engine 2 | 3 | import caart.engine.GlobalCell.Empty 4 | import caart.engine.fields.{Dir2D, Pos2D} 5 | 6 | /** The trait which must be implemented by every Cellular Automaton's cell class. 7 | * Every cell must know its position on the board (`pos`), it must have access 8 | * to other cells of its type (`findCell`), and it must implement the rules which 9 | * control the creation of its successor (`selfUpdate`). 10 | * 11 | * @tparam C the lower bound for the cell is this trait itself 12 | */ 13 | trait Cell[C <: Cell[C]] { self: C => 14 | type GC <: GlobalCell[C, GC] 15 | type CE <: Cell.Event 16 | 17 | val pos: Pos2D 18 | val auto: Cell.AutoContract[C, GC] 19 | 20 | def selfUpdate: Option[C] 21 | def updateFromEvents(events: Iterable[C#CE]): Option[C] 22 | 23 | def needsSelfUpdate: Boolean = true 24 | 25 | @inline final def next(events: Iterable[C#CE]): C = auto.updateStrategy(self, events) 26 | } 27 | 28 | object Cell { 29 | trait Event 30 | final case class NoEvent() extends Event 31 | 32 | trait AutoContract[C <: Cell[C], GC <: GlobalCell[C, GC]] { 33 | val updateStrategy: UpdateStrategy.Type[C] 34 | val eventHub: EventHub.AddEvents[C, GC] 35 | val dim: Int 36 | 37 | def globalCell: GC 38 | 39 | def findCell(pos: Pos2D): C 40 | def neumann(pos: Pos2D): Map[Dir2D, C] 41 | def moore(pos: Pos2D): Map[Dir2D, C] 42 | } 43 | 44 | type AutoContractNoGlobal[C <: Cell[C]] = AutoContract[C, Empty[C]] 45 | 46 | trait NoGlobal[C <: Cell[C]] extends Cell[C] { self: C => 47 | override type GC = Empty[C] 48 | override val auto: Cell.AutoContractNoGlobal[C] // no change really, but maybe it will be better readable in IDE hints?... 49 | } 50 | 51 | trait NoEvents[C <: Cell[C]] extends Cell[C] { self: C => 52 | override type CE = Cell.NoEvent 53 | override final def updateFromEvents(events: Iterable[C#CE]): Option[C] = None 54 | } 55 | 56 | trait CellOnlySelfUpdate[C <: Cell[C]] extends NoGlobal[C] with NoEvents[C] { self: C => } 57 | } -------------------------------------------------------------------------------- /src/main/scala/caart/engine/EventHub.scala: -------------------------------------------------------------------------------- 1 | package caart.engine 2 | 3 | import caart.engine.fields.Pos2D 4 | import scala.util.chaining.scalaUtilChainingOps 5 | 6 | final class EventHub[C <: Cell[C], GC <: GlobalCell[C, GC]] extends EventHub.AddEvents[C, GC] { 7 | private var _cellEvents = List.empty[(Pos2D, C#CE)] 8 | private var _globalEvents = List.empty[GC#GCE] 9 | 10 | def !(event: (Pos2D, C#CE)): Unit = 11 | _cellEvents ::= event 12 | 13 | def !(event: GC#GCE): Unit = 14 | _globalEvents ::= event 15 | 16 | @inline def cellEvents: Map[Pos2D, Iterable[C#CE]] = 17 | if (_cellEvents.isEmpty) 18 | Map.empty 19 | else 20 | _cellEvents.groupBy(_._1).map { case (pos, events) => (pos, events.map(_._2)) } 21 | 22 | @inline def globalEvents: List[GC#GCE] = _globalEvents 23 | 24 | @inline def oneCellEvents(pos: Pos2D): List[C#CE] = _cellEvents.collect { case (p, event) if pos == p => event } 25 | 26 | @inline def drainCellEvents(): Map[Pos2D, Iterable[C#CE]] = cellEvents.tap { _ => _cellEvents = Nil } 27 | 28 | @inline def drainGlobalEvents(): List[GC#GCE] = _globalEvents.tap { _ => _globalEvents = Nil } 29 | } 30 | 31 | object EventHub { 32 | trait AddEvents[C <: Cell[C], GC <: GlobalCell[C, GC]] { 33 | def !(event: (Pos2D, C#CE)): Unit 34 | def !(event: GC#GCE): Unit 35 | } 36 | } -------------------------------------------------------------------------------- /src/main/scala/caart/engine/GlobalCell.scala: -------------------------------------------------------------------------------- 1 | package caart.engine 2 | 3 | import caart.engine.GlobalUpdateStrategy.Type 4 | import caart.engine.fields.Pos2D 5 | 6 | trait GlobalCell[C <: Cell[C], GC <: GlobalCell[C, GC]] { self: GC => 7 | type GCE <: GlobalCell.Event 8 | protected val auto: GlobalCell.AutoContract[C, GC] 9 | def selfUpdate: Option[GC] 10 | def updateFromEvents(events: Iterable[GC#GCE]): Option[GC] 11 | 12 | def needsSelfUpdate: Boolean = true 13 | 14 | @inline final def next(events: Iterable[GC#GCE]): GC = auto.globalUpdateStrategy(self, events) 15 | } 16 | 17 | object GlobalCell { 18 | trait Event 19 | 20 | trait AutoContract[C <: Cell[C], GC <: GlobalCell[C, GC]] { 21 | val dim: Int 22 | val globalUpdateStrategy: GlobalUpdateStrategy.Type[C, GC] 23 | val eventHub: EventHub.AddEvents[C, GC] 24 | 25 | def board: Board[C] 26 | } 27 | 28 | def noAutoContract[C <: Cell[C], GC <: GlobalCell[C, GC]]: AutoContract[C, GC] = new AutoContract[C, GC] { 29 | override val dim: Int = 0 30 | override def board: Board[C] = Board.empty[C] 31 | 32 | override val globalUpdateStrategy: Type[C, GC] = GlobalUpdateStrategy.onlyEvents[C, GC] 33 | override val eventHub: EventHub.AddEvents[C, GC] = new EventHub.AddEvents[C, GC] { 34 | override def !(event: (Pos2D, C#CE)): Unit = () 35 | override def !(event: GC#GCE): Unit = () 36 | } 37 | } 38 | 39 | final case class Empty[C <: Cell[C]] private() extends GlobalCell[C, Empty[C]] { 40 | override type GCE = GlobalCell.Event 41 | override def selfUpdate: Option[Empty[C]] = None 42 | override def needsSelfUpdate: Boolean = false 43 | override val auto: AutoContract[C, Empty[C]] = noAutoContract[C, Empty[C]] 44 | override def updateFromEvents(events: Iterable[Empty[C]#GCE]): Option[Empty[C]] = None 45 | } 46 | 47 | def empty[C <: Cell[C]]: Empty[C] = Empty[C]() 48 | 49 | trait NoSelfUpdate[C <: Cell[C], GC <: GlobalCell[C, GC]] extends GlobalCell[C, GC] { self: GC => 50 | override def needsSelfUpdate: Boolean = false 51 | def selfUpdate: Option[GC] = None 52 | override val auto: AutoContract[C, GC] = noAutoContract[C, GC] 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /src/main/scala/caart/engine/GlobalUpdateStrategy.scala: -------------------------------------------------------------------------------- 1 | package caart.engine 2 | 3 | object GlobalUpdateStrategy { 4 | type Type[C <: Cell[C], GC <: GlobalCell[C, GC]] = (GC, Iterable[GC#GCE]) => GC 5 | 6 | @inline private def otherwise[C <: Cell[C], GC <: GlobalCell[C, GC]](self: GC, events: Iterable[GC#GCE]): GC = 7 | if (self.needsSelfUpdate) self.selfUpdate.getOrElse(self) 8 | else if (events.nonEmpty) self.updateFromEvents(events).getOrElse(self) 9 | else self 10 | 11 | def eventsOverrideSelf[C <: Cell[C], GC <: GlobalCell[C, GC]](self: GC, events: Iterable[GC#GCE]): GC = 12 | if (self.needsSelfUpdate && events.nonEmpty) 13 | self.updateFromEvents(events).orElse(self.selfUpdate).getOrElse(self) 14 | else 15 | otherwise[C, GC](self, events) 16 | 17 | def firstEventsThenSelf[C <: Cell[C], GC <: GlobalCell[C, GC]](self: GC, events: Iterable[GC#GCE]): GC = 18 | if (self.needsSelfUpdate && events.nonEmpty) 19 | self.updateFromEvents(events).map(c => c.selfUpdate.getOrElse(c)).getOrElse(self.selfUpdate.getOrElse(self)) 20 | else 21 | otherwise[C, GC](self, events) 22 | 23 | def firstSelfThenEvents[C <: Cell[C], GC <: GlobalCell[C, GC]](self: GC, events: Iterable[GC#GCE]): GC = 24 | if (self.needsSelfUpdate && events.nonEmpty) 25 | self.selfUpdate.map(c => c.updateFromEvents(events).getOrElse(c)).getOrElse(self.updateFromEvents(events).getOrElse(self)) 26 | else 27 | otherwise[C, GC](self, events) 28 | 29 | def onlyEvents[C <: Cell[C], GC <: GlobalCell[C, GC]](self: GC, events: Iterable[GC#GCE]): GC = 30 | if (events.nonEmpty) 31 | self.updateFromEvents(events).getOrElse(self) 32 | else 33 | self 34 | 35 | def onlySelf[C <: Cell[C], GC <: GlobalCell[C, GC]](self: GC, events: Iterable[GC#GCE]): GC = 36 | if (self.needsSelfUpdate) 37 | self.selfUpdate.getOrElse(self) 38 | else 39 | self 40 | 41 | def noUpdate[C <: Cell[C], GC <: GlobalCell[C, GC]](self: GC, events: Iterable[GC#GCE]): GC = self 42 | } 43 | -------------------------------------------------------------------------------- /src/main/scala/caart/engine/UpdateStrategy.scala: -------------------------------------------------------------------------------- 1 | package caart.engine 2 | 3 | object UpdateStrategy { 4 | type Type[C <: Cell[C]] = (C, Iterable[C#CE]) => C 5 | 6 | @inline private def otherwise[C <: Cell[C]](self: C, events: Iterable[C#CE]): C = 7 | if (self.needsSelfUpdate) self.selfUpdate.getOrElse(self) 8 | else if (events.nonEmpty) self.updateFromEvents(events).getOrElse(self) 9 | else self 10 | 11 | def eventsOverrideSelf[C <: Cell[C]](self: C, events: Iterable[C#CE]): C = 12 | if (self.needsSelfUpdate && events.nonEmpty) 13 | self.updateFromEvents(events).orElse(self.selfUpdate).getOrElse(self) 14 | else 15 | otherwise[C](self, events) 16 | 17 | def firstEventsThenSelf[C <: Cell[C]](self: C, events: Iterable[C#CE]): C = 18 | if (self.needsSelfUpdate && events.nonEmpty) 19 | self.updateFromEvents(events).map(c => c.selfUpdate.getOrElse(c)).getOrElse(self.selfUpdate.getOrElse(self)) 20 | else 21 | otherwise[C](self, events) 22 | 23 | def firstSelfThenEvents[C <: Cell[C]](self: C, events: Iterable[C#CE]): C = 24 | if (self.needsSelfUpdate && events.nonEmpty) 25 | self.selfUpdate.map(c => c.updateFromEvents(events).getOrElse(c)).getOrElse(self.updateFromEvents(events).getOrElse(self)) 26 | else 27 | otherwise[C](self, events) 28 | 29 | def onlyEvents[C <: Cell[C]](self: C, events: Iterable[C#CE]): C = 30 | if (events.nonEmpty) 31 | self.updateFromEvents(events).getOrElse(self) 32 | else 33 | self 34 | 35 | def onlySelf[C <: Cell[C]](self: C, events: Iterable[C#CE]): C = 36 | if (self.needsSelfUpdate) 37 | self.selfUpdate.getOrElse(self) 38 | else 39 | self 40 | 41 | def noUpdate[C <: Cell[C]](self: C, events: Iterable[C#CE]): C = self 42 | } 43 | -------------------------------------------------------------------------------- /src/main/scala/caart/engine/fields/CMYK.scala: -------------------------------------------------------------------------------- 1 | package caart.engine.fields 2 | 3 | import math.round 4 | 5 | /** 6 | * While RGB is what we use to describe colors made from mixing light of different wavelength, 7 | * we can think of CMYK as a description of colors made from mixing paint. The main difference 8 | * is that in RGB the "zero" color (the identity) is black, and adding colors to it we move 9 | * towards white, while in CMYK the identity is the white color of the canvas on which we paint. 10 | * Mixing colors on the canvas moves us towards black. However, CMYK is not a simple inversion 11 | * of RGB. The methods used to convert between the two can be very complex - what I use here is 12 | * probably the simplest one. 13 | * 14 | * In CA Art, CMYK is used to visualize the state of a cell. This way we can treat the white color 15 | * in CMYK (0.0, 0.0, 0.0) as the default state, and then use basic colors (cyan, magenta, yellow) 16 | * for data in the cell. Mixing the colors gives us the visualization of the whole state. At the 17 | * end, just before it's displayed on the screen, the result color is converted to RGB. 18 | * 19 | * https://en.wikipedia.org/wiki/CMYK_color_model 20 | */ 21 | final case class CMYK(c: Double, m: Double, y: Double, k: Double) { 22 | def +(other: CMYK): CMYK = CMYK.sum(Seq(this, other)) 23 | 24 | // this makes sense only for dimming the color, ie. coeff in <0.0, 1.0> 25 | def *(coeff: Double): CMYK = { 26 | require(coeff >= 0.0 && coeff <= 1.0) 27 | val nc = CMYK(c * coeff, m * coeff, y * coeff, k * coeff) 28 | if (nc.c > 1.0 || nc.m > 1.0 || nc.y >1.0 || nc.k > 1.0) CMYK.sum(Seq(nc)) else nc 29 | } 30 | 31 | def toRGB: RGB = this match { 32 | case CMYK.White => RGB.White 33 | case CMYK.Black => RGB.Black 34 | case _ => 35 | RGB( 36 | round(255.0 * (1.0 - c) * (1.0 -k)).toInt, 37 | round(255.0 * (1.0 - m) * (1.0 -k)).toInt, 38 | round(255.0 * (1.0 - y) * (1.0 -k)).toInt 39 | ) 40 | } 41 | 42 | lazy val abs: Double = math.sqrt(c *c + m * m + y * y + k * k) 43 | 44 | override def toString: String = s"CMYK(${c.round(3)}, ${m.round(3)}, ${y.round(3)}, ${k.round(3)})" 45 | } 46 | 47 | object CMYK { 48 | def apply(c: Double, m: Double, y: Double): CMYK = CMYK(c, m, y, 0.0) 49 | 50 | def unapply(color: CMYK): Option[(Double, Double, Double, Double)] = Some((color.c, color.m, color.y, color.k)) 51 | 52 | val Cyan: CMYK = CMYK(1.0, 0.0, 0.0) 53 | val Magenta: CMYK = CMYK(0.0, 1.0, 0.0) 54 | val Yellow: CMYK = CMYK(0.0, 0.0, 1.0) 55 | 56 | val colors: Array[CMYK] = Array(Cyan, Magenta, Yellow) 57 | 58 | val Black: CMYK = CMYK(0.0, 0.0, 0.0, 1.0) 59 | val White: CMYK = CMYK(0.0, 0.0, 0.0) 60 | 61 | def sum(colors: Iterable[CMYK]): CMYK = 62 | sum(Vector(colors.map(c => c.c + c.k).sum, colors.map(c => c.m + c.k).sum, colors.map(c => c.y + c.k).sum)) 63 | 64 | private[CMYK] def sum(vec: Vector[Double]): CMYK = { 65 | val max = vec.max 66 | val narr = vec.map(_ / max) 67 | val nk = narr.min 68 | if (nk >= 1.0) CMYK.Black else { 69 | val nnarr = narr.map(n => (n - nk) / (1.0 - nk)) 70 | CMYK(nnarr(0), nnarr(1), nnarr(2), nk) 71 | } 72 | } 73 | } 74 | -------------------------------------------------------------------------------- /src/main/scala/caart/engine/fields/Dir2D.scala: -------------------------------------------------------------------------------- 1 | package caart.engine.fields 2 | 3 | /** 4 | Similarly to `Pos2D` this is a simple representation of a 2D vector. 5 | It can be used in two ways: as a normalized vector between two positions, 6 | and as such it can be held as a field in a cell and used to compute 7 | its new state, or it can denote a spatial relation between two cells. 8 | In the second case we deal usually only with constants: Up, Right, Down, etc. 9 | */ 10 | class Dir2D(val x: Double, val y: Double) { 11 | def turnRight: Dir2D = new Dir2D(-y, x) 12 | def turnLeft: Dir2D = new Dir2D(y, -x) 13 | def turnAround: Dir2D = new Dir2D(-x, -y) 14 | 15 | // returns the cross product of this vector and another 16 | def crossZ(other: Dir2D): Double = x * (other.y - y) - y * (other.x - x) 17 | 18 | // calculating the cross product is an easy way to tell if the other vector 19 | // is clockwise or counterclockwise from this one 20 | // `crossZ` is 0.0 if the vectors are parallel 21 | def rightOf(other: Dir2D): Boolean = crossZ(other) < 0 22 | def leftOf(other: Dir2D): Boolean = crossZ(other) > 0 23 | 24 | def approx4: Dir2D = Dir2D.approx4(x, y) 25 | def approx8: Dir2D = Dir2D.approx8(x, y) 26 | 27 | override def equals(obj: scala.Any): Boolean = obj match { 28 | case dir: Dir2D => dir.x == x && dir.y == y 29 | case _ => false 30 | } 31 | 32 | override def hashCode: Int = x.hashCode + y.hashCode 33 | 34 | override def toString: String = s"Dir2D(${x.round(3)}, ${y.round(3)})" 35 | } 36 | 37 | object Dir2D { 38 | 39 | case object Up extends Dir2D(0.0, -1.0) { 40 | override lazy val turnRight: Dir2D = Right 41 | override lazy val turnLeft : Dir2D = Left 42 | override lazy val turnAround : Dir2D = Down 43 | 44 | override def toString: String = "Up" 45 | } 46 | 47 | case object Right extends Dir2D(1.0, 0.0) { 48 | override lazy val turnRight: Dir2D = Down 49 | override lazy val turnLeft : Dir2D = Up 50 | override lazy val turnAround : Dir2D = Left 51 | 52 | override def toString: String = "Right" 53 | } 54 | 55 | case object Down extends Dir2D(0.0, 1.0) { 56 | override lazy val turnRight: Dir2D = Left 57 | override lazy val turnLeft : Dir2D = Right 58 | override lazy val turnAround : Dir2D = Up 59 | 60 | override def toString: String = "Down" 61 | } 62 | 63 | case object Left extends Dir2D(-1.0, 0.0) { 64 | override lazy val turnRight: Dir2D = Up 65 | override lazy val turnLeft : Dir2D = Down 66 | override lazy val turnAround : Dir2D = Right 67 | 68 | override def toString: String = "Left" 69 | } 70 | 71 | case object UpLeft extends Dir2D(-1.0, -1.0) { 72 | override lazy val turnRight: Dir2D = UpRight 73 | override lazy val turnLeft : Dir2D = DownLeft 74 | override lazy val turnAround : Dir2D = DownRight 75 | 76 | override def toString: String = "UpLeft" 77 | } 78 | 79 | case object UpRight extends Dir2D(1.0, -1.0) { 80 | override lazy val turnRight: Dir2D = DownRight 81 | override lazy val turnLeft : Dir2D = UpLeft 82 | override lazy val turnAround : Dir2D = DownLeft 83 | 84 | override def toString: String = "UpRight" 85 | } 86 | 87 | case object DownRight extends Dir2D(1.0, 1.0) { 88 | override lazy val turnRight: Dir2D = DownLeft 89 | override lazy val turnLeft : Dir2D = UpRight 90 | override lazy val turnAround : Dir2D = UpLeft 91 | 92 | override def toString: String = "DownRight" 93 | } 94 | 95 | case object DownLeft extends Dir2D(-1.0, 1.0) { 96 | override lazy val turnRight: Dir2D = UpLeft 97 | override lazy val turnLeft : Dir2D = DownRight 98 | override lazy val turnAround : Dir2D = UpRight 99 | 100 | override def toString: String = "DownLeft" 101 | } 102 | 103 | val dirs4: Array[Dir2D] = Array(Up, Right, Down, Left) 104 | val dirs8: Array[Dir2D] = Array(Up, UpRight, Right, DownRight, Down, DownLeft, Left, UpLeft) 105 | 106 | def apply(x: Double, y: Double): Dir2D = { 107 | require(x != 0.0 || y != 0.0, "Unable to create a Dir2D from (x = 0.0, y = 0.0)") 108 | (x, y) match { 109 | case (0.0, _) if y < 0.0 => Up 110 | case (_, 0.0) if x > 0.0 => Right 111 | case (0.0, _) if y > 0.0 => Down 112 | case (_, 0.0) if x < 0.0 => Left 113 | case _ if x == y && x < 0.0 => UpLeft 114 | case _ if x == -y && x > 0.0 => UpRight 115 | case _ if x == y && x > 0.0 => DownRight 116 | case _ if x == -y && x < 0.0 => DownLeft 117 | case _ => 118 | val den = math.sqrt(x * x + y * y) 119 | new Dir2D(x / den, y / den) 120 | } 121 | } 122 | 123 | def approx4(x: Double, y: Double): Dir2D = 124 | if (x > 0.0) { 125 | if (y > x) Down 126 | else if (y < -x) Up 127 | else Right 128 | } else { 129 | if (y < x) Up 130 | else if (y > -x) Down 131 | else Left 132 | } 133 | 134 | def approx8(x: Double, y: Double): Dir2D = { 135 | val absX = math.abs(x) 136 | if (y < 0.0) { 137 | if (2.0 * absX < -y) Up 138 | else if (absX < -2.0 * y) { 139 | if (x < 0.0) UpLeft else UpRight 140 | } else { 141 | if (x < 0.0) Left else Right 142 | } 143 | } else { 144 | if (2.0 * absX < y) Down 145 | else if (absX < 2.0 * y) { 146 | if (x < 0.0) DownLeft else DownRight 147 | } else { 148 | if (x < 0.0) Left else Right 149 | } 150 | } 151 | } 152 | 153 | def unapply(dir: Dir2D): Option[(Double, Double)] = Some((dir.x, dir.y)) 154 | } -------------------------------------------------------------------------------- /src/main/scala/caart/engine/fields/Pos2D.scala: -------------------------------------------------------------------------------- 1 | package caart.engine.fields 2 | 3 | import scala.util.Random 4 | 5 | /** 6 | * Yet another representation of a position in 2D :) 7 | * I decided to implement it myself, because it allowed me to introduce 8 | * a few important utility methods. I think that as long as conversion 9 | * to other representations is trivial, implementing such simple case 10 | * classes is totally ok. They may be reduntant, but they simplify a lot. 11 | */ 12 | final case class Pos2D(x: Int, y: Int) { 13 | // If Dir2D is one of the Dir2D constants, the method returns 14 | // the adjacent position in the given direction. 15 | // Used to collect the neighborhood of the cell with the given `pos`. 16 | def move(dir: Dir2D): Pos2D = copy(x + dir.x.toInt, y + dir.y.toInt) 17 | 18 | // Returns the direction (normalized) vector between the two positions. 19 | def dir(other: Pos2D): Dir2D = Dir2D(other.x - x, other.y - y) 20 | def -(other: Pos2D): Dir2D = other.dir(this) 21 | } 22 | 23 | object Pos2D { 24 | // Returns all positions for a square board with the given edge length `dim` (exclusive). 25 | def apply(dim: Int): Vector[Pos2D] = (0 until dim).flatMap(x => (0 until dim).map(Pos2D(x, _))).toVector 26 | 27 | // Returns all positions for a square board between two positions (inclusive) 28 | def range(p1: Pos2D, p2: Pos2D): Vector[Pos2D] = { 29 | val xfrom = math.min(p1.x, p2.x) 30 | val yfrom = math.min(p1.y, p2.y) 31 | val xto = math.max(p1.x, p2.x) 32 | val yto = math.max(p1.y, p2.y) 33 | 34 | (xfrom to xto).flatMap(x => (yfrom to yto).map(Pos2D(x, _))).toVector 35 | } 36 | 37 | // Returns a random position on a board of the given size 38 | def random(dim: Int): Pos2D = Pos2D(Random.nextInt(dim), Random.nextInt(dim)) 39 | } 40 | -------------------------------------------------------------------------------- /src/main/scala/caart/engine/fields/RGB.scala: -------------------------------------------------------------------------------- 1 | package caart.engine.fields 2 | 3 | import math.min 4 | 5 | /** 6 | * Please see the CMYK.scala file for a short discussion of RGB and CMYK. 7 | */ 8 | final case class RGB(r: Int, g: Int, b: Int) { 9 | def +(c: RGB) : RGB = RGB(min(r + c.r, 255),min(b + c.b, 255), min(b + c.b, 255)) 10 | 11 | def toCMYK: CMYK = this match { 12 | case RGB.White => CMYK.White 13 | case RGB.Black => CMYK.Black 14 | case _ => 15 | val c = 1.0 - (r / 255.0) 16 | val m = 1.0 - (g / 255.0) 17 | val y = 1.0 - (b / 255.0) 18 | val k = Array(c, m, y).min 19 | if (k >= 1.0) CMYK.Black 20 | else CMYK((c - k)/(1.0 - k), (m- k)/(1.0 - k), (y - k)/(1.0 - k), k) 21 | } 22 | } 23 | 24 | object RGB { 25 | val White: RGB = RGB(255, 255, 255) 26 | val Black: RGB = RGB(0, 0, 0) 27 | 28 | val Red: RGB = RGB(255, 0, 0) 29 | val Orange: RGB = RGB(255, 165, 0) 30 | val Yellow: RGB = RGB(255, 255, 0) 31 | val Green: RGB = RGB(0, 255, 0) 32 | val Blue: RGB = RGB(0, 0, 255) 33 | val Indigo: RGB = RGB(0, 28, 200) 34 | val Violet: RGB = RGB(128, 0, 255) 35 | 36 | val monotone: List[RGB] = List(White, Black) 37 | val rainbow: List[RGB] = List(Red, Orange, Yellow, Green, Blue, Indigo, Violet) 38 | 39 | val all: List[RGB] = monotone ::: rainbow 40 | } 41 | -------------------------------------------------------------------------------- /src/main/scala/caart/engine/fields/package.scala: -------------------------------------------------------------------------------- 1 | package caart.engine 2 | 3 | package object fields { 4 | 5 | implicit final class RichDouble(val d: Double) extends AnyVal { 6 | def round(digits: Int = 0): Double = 7 | if (digits == 0) math.round(d).toDouble else { 8 | val t = math.pow(10.0, digits) 9 | math.round(d * t).toDouble / t 10 | } 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /src/main/scala/caart/examples/Chase.scala: -------------------------------------------------------------------------------- 1 | package caart.examples 2 | 3 | import caart.engine.{Automaton, Cell, GlobalCell} 4 | import caart.engine.fields.{CMYK, Pos2D} 5 | import com.typesafe.scalalogging.LazyLogging 6 | 7 | final case class Chase(override val pos: Pos2D, 8 | override val auto: Cell.AutoContract[Chase, ChaseGlobal], 9 | color: CMYK = CMYK.White, 10 | brushes: List[CMYK] = Nil) extends Cell[Chase] { 11 | import Chase._ 12 | override type GC = ChaseGlobal 13 | override type CE = ChaseEvent 14 | 15 | override def selfUpdate: Option[Chase] = (color, dirToPlayerPosition) match { 16 | case (CMYK.White, None) => None 17 | case (_, None) => Some(copy(color = newColor)) 18 | case (_, Some(_)) => Some(copy(color = newColor, brushes = newBrushes)) 19 | } 20 | 21 | override def updateFromEvents(events: Iterable[ChaseEvent]): Option[Chase] = 22 | events.collectFirst { 23 | case SetPlayerHere => copy(color = CMYK.Black) 24 | }.orElse { 25 | val colors = events.collect { case CreateChaser(color) => color }.toList 26 | Some(copy(color = CMYK.sum(color :: colors), brushes = colors)) 27 | } 28 | 29 | override def needsSelfUpdate: Boolean = 30 | (color != CMYK.White) || auto.moore(pos).values.exists(_.brushes.nonEmpty) 31 | 32 | private def newColor = 33 | if (auto.globalCell.playerPosition.contains(pos)) CMYK.Black 34 | else if (brushes.nonEmpty) CMYK.sum(color :: brushes) 35 | else if (color.abs < 0.02) CMYK.White 36 | else color * 0.98 37 | 38 | private def newBrushes = auto.moore(pos).collect { 39 | case (thisDir, cell) if cell.brushes.nonEmpty && cell.dirToPlayerPosition.contains(thisDir.turnAround) => cell.brushes 40 | }.flatten.toList 41 | 42 | private def dirToPlayerPosition = auto.globalCell.playerPosition match { 43 | case None => None 44 | case Some(cPos) if cPos == pos => None 45 | case Some(cPos) => Some((cPos - pos).approx8) 46 | } 47 | } 48 | 49 | final case class ChaseGlobal(playerPosition: Option[Pos2D] = None) extends GlobalCell.NoSelfUpdate[Chase, ChaseGlobal] { 50 | override type GCE = Chase.SetPlayer 51 | override def updateFromEvents(events: Iterable[Chase.SetPlayer]): Option[ChaseGlobal] = 52 | events.headOption.map { case Chase.SetPlayer(pos) => copy(playerPosition = Some(pos)) } 53 | } 54 | 55 | object Chase extends Automaton.Creator[Chase, ChaseGlobal] with LazyLogging { 56 | override def cell(pos: Pos2D, auto: Cell.AutoContract[Chase, ChaseGlobal]): Chase = Chase(pos, auto) 57 | override def globalCell(auto: GlobalCell.AutoContract[Chase, ChaseGlobal]): ChaseGlobal = ChaseGlobal() 58 | 59 | trait ChaseEvent extends Cell.Event 60 | final case class CreateChaser(color: CMYK) extends ChaseEvent 61 | case object SetPlayerHere extends ChaseEvent 62 | 63 | final case class SetPlayer(pos: Pos2D) extends GlobalCell.Event 64 | } 65 | -------------------------------------------------------------------------------- /src/main/scala/caart/examples/GameOfLife.scala: -------------------------------------------------------------------------------- 1 | package caart.examples 2 | 3 | import caart.engine.fields.Pos2D 4 | import caart.engine.{Automaton, Cell} 5 | 6 | final case class GameOfLife(override val pos: Pos2D, 7 | override val auto: Cell.AutoContractNoGlobal[GameOfLife], 8 | life: Boolean = false) extends Cell.NoGlobal[GameOfLife] { 9 | override type CE = GameOfLife.FlipCell.type 10 | 11 | override def updateFromEvents(events: Iterable[GameOfLife.FlipCell.type]): Option[GameOfLife] = 12 | if (events.size % 2 == 1) Some(copy(life = !life)) else None 13 | 14 | override def selfUpdate: Option[GameOfLife] = auto.moore(pos).values.count(_.life) match { 15 | case 3 if !life => Some(copy(life = true)) 16 | case n if life && (n < 2 || n > 3) => Some(copy(life = false)) 17 | case _ => None 18 | } 19 | } 20 | 21 | object GameOfLife extends Automaton.CreatorNoGlobal[GameOfLife] { 22 | override def cell(pos: Pos2D, auto: Cell.AutoContractNoGlobal[GameOfLife]): GameOfLife = GameOfLife(pos, auto) 23 | case object FlipCell extends Cell.Event 24 | } 25 | -------------------------------------------------------------------------------- /src/main/scala/caart/examples/LangtonsAnt.scala: -------------------------------------------------------------------------------- 1 | package caart.examples 2 | 3 | import caart.engine.fields.{Dir2D, Pos2D} 4 | import caart.engine.{Automaton, Cell} 5 | 6 | final case class LangtonsAnt(override val pos: Pos2D, 7 | override val auto: Cell.AutoContractNoGlobal[LangtonsAnt], 8 | color: Boolean = false, 9 | dir: Option[Dir2D] = None) extends Cell.NoGlobal[LangtonsAnt] { 10 | override type CE = LangtonsAnt.CreateAnt.type 11 | 12 | override def needsSelfUpdate: Boolean = dir.isDefined || auto.neumann(pos).exists(_._2.dir.isDefined) 13 | 14 | override def selfUpdate: Option[LangtonsAnt] = (newColor, newDir) match { 15 | case (`color`, `dir`) => None 16 | case (c, d) => Some(copy(color = c, dir = d)) 17 | } 18 | 19 | override def updateFromEvents(events: Iterable[LangtonsAnt.CreateAnt.type]): Option[LangtonsAnt] = 20 | if (events.nonEmpty) Some(copy(dir = Some(Dir2D.Up))) else None 21 | 22 | private def newColor = if (dir.isEmpty) color else !color 23 | 24 | private def newDir = auto.neumann(pos).find { 25 | case (thisDir, cell) => cell.dir.contains(thisDir.turnAround) 26 | }.map { 27 | case (thisDir, _) if color => thisDir.turnLeft 28 | case (thisDir, _) => thisDir.turnRight 29 | } 30 | } 31 | 32 | object LangtonsAnt extends Automaton.CreatorNoGlobal[LangtonsAnt] { 33 | override def cell(pos: Pos2D, auto: Cell.AutoContractNoGlobal[LangtonsAnt]): LangtonsAnt = LangtonsAnt(pos, auto) 34 | case object CreateAnt extends Cell.Event 35 | } 36 | -------------------------------------------------------------------------------- /src/main/scala/caart/examples/LangtonsColors.scala: -------------------------------------------------------------------------------- 1 | package caart.examples 2 | 3 | import caart.engine.fields.{CMYK, Dir2D, Pos2D} 4 | import caart.engine.{Automaton, Cell} 5 | 6 | final case class LangtonsColors(override val pos: Pos2D, 7 | override val auto: Cell.AutoContractNoGlobal[LangtonsColors], 8 | colors: Set[CMYK] = Set.empty, 9 | dirs: Map[Dir2D, CMYK] = Map.empty) extends Cell.NoGlobal[LangtonsColors] { 10 | override type CE = LangtonsColors.CreateAnt 11 | 12 | override def needsSelfUpdate: Boolean = 13 | dirs.nonEmpty || auto.neumann(pos).exists(_._2.dirs.nonEmpty) 14 | 15 | override def selfUpdate: Option[LangtonsColors] = (newColors, newDirs) match { 16 | case (`colors`, `dirs`) => None 17 | case (cs, ds) => Some(copy(colors = cs, dirs = ds)) 18 | } 19 | 20 | override def updateFromEvents(events: Iterable[LangtonsColors.CreateAnt]): Option[LangtonsColors] = 21 | events.headOption.map { 22 | case LangtonsColors.CreateAnt(color, dir) => copy(colors = Set(color), dirs = Map(dir -> color)) 23 | } 24 | 25 | private def newColors = { 26 | val newColors = dirs.values.toSet 27 | (colors | newColors) &~ (colors & newColors) // no generic xor? 28 | } 29 | 30 | private def newDirs = auto.neumann(pos).flatMap { 31 | case (thisDir, cell) => cell.dirs.filter(_._1 == thisDir.turnAround) 32 | }.map { 33 | case (thatDir, color) if colors.contains(color) => (thatDir.turnRight, color) 34 | case (thatDir, color) => (thatDir.turnLeft, color) 35 | } 36 | } 37 | 38 | object LangtonsColors extends Automaton.CreatorNoGlobal[LangtonsColors] { 39 | override def cell(pos: Pos2D, auto: Cell.AutoContractNoGlobal[LangtonsColors]): LangtonsColors = LangtonsColors(pos, auto) 40 | final case class CreateAnt(color: CMYK, dir: Dir2D) extends Cell.Event 41 | } 42 | -------------------------------------------------------------------------------- /src/main/scala/caart/examples/Snake.scala: -------------------------------------------------------------------------------- 1 | package caart.examples 2 | 3 | import caart.engine.{Automaton, Cell, GlobalCell} 4 | import caart.engine.fields.{Dir2D, Pos2D} 5 | 6 | import scala.util.Random 7 | 8 | final case class Snake(override val pos: Pos2D, 9 | override val auto: Cell.AutoContract[Snake, SnakeGlobal], 10 | cellType: Snake.CellType = Snake.Empty) extends Cell.NoEvents[Snake] { 11 | import Snake._ 12 | override type GC = SnakeGlobal 13 | 14 | override def selfUpdate: Option[Snake] = cellType match { 15 | case Empty => ifEmpty 16 | case Treat => ifTreat 17 | case Head(dir) => ifHead(dir) 18 | case Body(headDir, tailDir) => ifBody(headDir, tailDir) 19 | case Tail(_) => ifTail 20 | } 21 | 22 | @inline private def headDir = auto.globalCell.headDir 23 | @inline private def treatFound = auto.globalCell.treatFound 24 | @inline private def showTreat = Random.nextDouble() < auto.globalCell.treatProbability 25 | 26 | private def ifEmpty = 27 | auto.findCell(pos.move(headDir.turnAround)) match { 28 | case Snake(_, _, Head(_)) => 29 | Some(copy(cellType = Head(headDir))) 30 | case _ if showTreat => 31 | auto.eventHub ! NewTreat 32 | Some(copy(cellType = Treat)) 33 | case _ => 34 | None 35 | } 36 | 37 | private def ifTreat = 38 | auto.findCell(pos.move(headDir.turnAround)) match { 39 | case Snake(_, _, Head(_)) => 40 | auto.eventHub ! TreatFound 41 | Some(copy(cellType = Head(headDir))) 42 | case _ => 43 | None 44 | } 45 | 46 | private def ifHead(dir: Dir2D) = { 47 | auto.findCell(pos.move(headDir)) match { 48 | case Snake(_, _, Body(_, _)) => auto.eventHub ! GameOver 49 | case Snake(_, _, Tail(_)) if treatFound => auto.eventHub ! GameOver 50 | case _ => 51 | } 52 | Some(copy(cellType = Body(headDir, dir.turnAround))) 53 | } 54 | 55 | private def ifBody(dir: Dir2D, tailDir: Dir2D) = 56 | auto.findCell(pos.move(tailDir)) match { 57 | case Snake(_, _, Tail(_)) if !treatFound => Some(copy(cellType = Tail(dir))) 58 | case _ => None 59 | } 60 | 61 | private def ifTail = 62 | if (treatFound) { 63 | auto.eventHub ! TreatEaten 64 | None 65 | } else 66 | Some(copy(cellType = Empty)) 67 | } 68 | 69 | final case class SnakeGlobal(headDir: Dir2D = Dir2D.Right, 70 | score: Int = 0, 71 | treatFound: Boolean = false, 72 | gameOver: Boolean = false, 73 | treatProbability: Double = 0.0002) extends GlobalCell.NoSelfUpdate[Snake, SnakeGlobal] { 74 | import Snake._ 75 | override type GCE = GlobalEvent 76 | override def updateFromEvents(events: Iterable[GlobalEvent]): Option[SnakeGlobal] = Some { 77 | events.foldLeft(this) { 78 | case (cell, GameOver) => cell.copy(gameOver = true) 79 | case (cell, NewTreat) => cell.copy(treatProbability = treatProbability / 2.0) 80 | case (cell, TreatFound) => cell.copy(treatFound = true, treatProbability = treatProbability * 2.0) 81 | case (cell, TreatEaten) => cell.copy(score = score + 1, treatFound = false) 82 | case (cell, TurnLeft) => cell.copy(headDir = headDir.turnLeft) 83 | case (cell, TurnRight) => cell.copy(headDir = headDir.turnRight) 84 | } 85 | } 86 | } 87 | 88 | object Snake extends Automaton.Creator[Snake, SnakeGlobal] { 89 | override def cell(pos: Pos2D, auto: Cell.AutoContract[Snake, SnakeGlobal]): Snake = Snake(pos, auto) 90 | override def globalCell(auto: GlobalCell.AutoContract[Snake, SnakeGlobal]): SnakeGlobal = SnakeGlobal() 91 | 92 | sealed trait CellType 93 | case object Empty extends CellType 94 | case object Treat extends CellType 95 | final case class Head(dir2D: Dir2D) extends CellType 96 | final case class Body(headDir: Dir2D, tailDir: Dir2D) extends CellType 97 | final case class Tail(dir2D: Dir2D) extends CellType 98 | 99 | sealed trait GlobalEvent extends GlobalCell.Event 100 | case object TurnLeft extends GlobalEvent 101 | case object TurnRight extends GlobalEvent 102 | case object NewTreat extends GlobalEvent 103 | case object TreatEaten extends GlobalEvent 104 | case object TreatFound extends GlobalEvent 105 | case object GameOver extends GlobalEvent 106 | } 107 | -------------------------------------------------------------------------------- /src/main/scala/caart/visualisation/Game.scala: -------------------------------------------------------------------------------- 1 | package caart.visualisation 2 | 3 | import caart.Arguments 4 | import caart.visualisation.Game.buildWorld 5 | import caart.visualisation.examples.{ChaseWorld, GameOfLifeWorld, LangtonsAntWorld, LangtonsColorsWorld, SnakeWorld} 6 | import com.almasb.fxgl.app.{ApplicationMode, GameApplication, GameSettings} 7 | import com.almasb.fxgl.dsl.FXGL 8 | import com.typesafe.scalalogging.LazyLogging 9 | import com.wire.signals.Signal 10 | import com.wire.signals.ui.UiDispatchQueue 11 | import javafx.application.Platform 12 | import javafx.scene.input.KeyCode 13 | 14 | final class Game(args: Arguments) extends GameApplication with LazyLogging { 15 | import com.wire.signals.Threading.defaultContext 16 | 17 | private lazy val world = buildWorld(args) 18 | 19 | private val gameState = Signal[GameState](GameState.Pause) 20 | gameState.foreach { 21 | case GameState.Play => run() 22 | case GameState.End => endGame() 23 | case _ => 24 | } 25 | 26 | private def run(): Unit = 27 | while(gameState.currentValue.contains(GameState.Play)) { 28 | //val t = System.currentTimeMillis 29 | if (!world.next()) gameState ! GameState.End 30 | //logger.debug(s"the turn took ${System.currentTimeMillis - t}ms") 31 | if (args.delay > 0L) Thread.sleep(args.delay) 32 | } 33 | 34 | private def endGame(): Unit = { 35 | Platform.runLater(() => Platform.exit()) 36 | } 37 | 38 | override def initSettings(gameSettings: GameSettings): Unit = { 39 | gameSettings.setWidth(args.windowSize) 40 | gameSettings.setHeight(args.windowSize) 41 | gameSettings.set3D(false) 42 | gameSettings.setApplicationMode(ApplicationMode.RELEASE) 43 | gameSettings.setGameMenuEnabled(true) 44 | gameSettings.setPixelsPerMeter(args.scale) 45 | gameSettings.setScaleAffectedOnResize(true) 46 | } 47 | 48 | override protected def initUI(): Unit = { 49 | logger.debug(s"args: $args") 50 | UiDispatchQueue.setUi(Platform.runLater) 51 | world.init() 52 | } 53 | 54 | override def initInput(): Unit = { 55 | FXGL.onKeyUp(KeyCode.SPACE, () => gameState.mutate { 56 | case GameState.Pause => GameState.Play 57 | case GameState.Play => GameState.Pause 58 | case other => other 59 | }) 60 | } 61 | } 62 | 63 | object Game { 64 | def buildWorld(args: Arguments): GameContract = args.example match { 65 | case Arguments.GameOfLifeExample => new GameOfLifeWorld(args) 66 | case Arguments.LangtonsAntExample => new LangtonsAntWorld(args) 67 | case Arguments.LangtonsColorsExample => new LangtonsColorsWorld(args) 68 | case Arguments.ChaseExample => new ChaseWorld(args) 69 | case Arguments.SnakeExample => new SnakeWorld(args) 70 | } 71 | } -------------------------------------------------------------------------------- /src/main/scala/caart/visualisation/World.scala: -------------------------------------------------------------------------------- 1 | package caart.visualisation 2 | 3 | import caart.Arguments 4 | import caart.engine.GlobalCell.Empty 5 | import caart.engine.fields.Pos2D 6 | import caart.engine.{Automaton, AutomatonNoGlobal, Board, Cell, GlobalCell} 7 | import com.almasb.fxgl.dsl.FXGL 8 | import com.typesafe.scalalogging.LazyLogging 9 | import com.wire.signals.ui.UiDispatchQueue.Ui 10 | import com.wire.signals.{EventStream, Signal, SourceStream} 11 | import javafx.scene.canvas.Canvas 12 | import javafx.scene.input.{MouseButton, MouseEvent} 13 | import javafx.scene.paint.Color 14 | 15 | import scala.concurrent.Future 16 | import scala.util.chaining.scalaUtilChainingOps 17 | 18 | abstract class World[C <: Cell[C], GC <: GlobalCell[C, GC]] extends GameContract with LazyLogging { 19 | protected val args: Arguments 20 | protected val auto: Automaton[C, GC] 21 | protected def toColor(c: C): Color 22 | protected def processUserEvent(event: UserEvent): Unit 23 | 24 | protected val onUserEvent: SourceStream[UserEvent] = EventStream[UserEvent]() 25 | onUserEvent.foreach { event => 26 | processUserEvent(event) 27 | event.pos.map(auto.findCell).foreach { cell => 28 | val color = toColor(cell) 29 | Future { 30 | val graphics = canvas.getGraphicsContext2D 31 | graphics.setFill(color) 32 | graphics.fillRect(cell.pos.x * args.scale, cell.pos.y * args.scale, args.scale, args.scale) 33 | }(Ui) 34 | } 35 | } 36 | 37 | private val drag = Signal(Option.empty[Pos2D]) 38 | drag.onUpdated.collect { case (Some(prev), _) => UserEvent(prev, UserEventType.LeftClick) }.pipeTo(onUserEvent) 39 | 40 | protected val canvas: Canvas = new Canvas().tap { canvas => 41 | canvas.setWidth(args.windowSize.toDouble) 42 | canvas.setHeight(args.windowSize.toDouble) 43 | } 44 | 45 | private var currentBoard = Option.empty[Board[C]] 46 | private var currentTurn = 0L 47 | 48 | private def updateBoard(newBoard: Board[C]): Unit = { 49 | val toUpdate = currentBoard.fold(newBoard.cells)(newBoard - _).groupBy(toColor) 50 | if (toUpdate.nonEmpty) { 51 | currentBoard = Some(newBoard) 52 | Future { 53 | val graphics = canvas.getGraphicsContext2D 54 | toUpdate.foreach { case (color, cells) => 55 | graphics.setFill(color) 56 | cells.foreach { c => 57 | graphics.fillRect(c.pos.x * args.scale, c.pos.y * args.scale, args.scale, args.scale) 58 | } 59 | } 60 | }(Ui) 61 | } 62 | } 63 | 64 | override def next(): Boolean = { 65 | var t = System.currentTimeMillis 66 | val newBoard = auto.next() 67 | //logger.debug(s"--- auto next: ${System.currentTimeMillis - t}ms") 68 | if (currentTurn % args.step == 0) { 69 | updateBoard(newBoard) 70 | if (args.enforceGC) { 71 | t = System.currentTimeMillis 72 | System.gc() 73 | } 74 | } 75 | currentTurn += 1L 76 | true 77 | } 78 | 79 | override def init(): Unit = { 80 | FXGL.addUINode(canvas) 81 | 82 | canvas.setOnMouseDragged { (ev: MouseEvent) => 83 | val p = Pos2D(ev.getSceneX.toInt / args.scale, ev.getSceneY.toInt / args.scale) 84 | drag ! Some(p) 85 | } 86 | 87 | canvas.setOnMousePressed { (ev: MouseEvent) => 88 | ev.setDragDetect(true) 89 | val p = Pos2D(ev.getSceneX.toInt / args.scale, ev.getSceneY.toInt / args.scale) 90 | if (ev.getButton == MouseButton.PRIMARY) onUserEvent ! UserEvent(Some(p), UserEventType.LeftClick) 91 | else if (ev.getButton == MouseButton.SECONDARY) onUserEvent ! UserEvent(Some(p), UserEventType.RightClick) 92 | } 93 | 94 | canvas.setOnMouseReleased { (_: MouseEvent) => drag ! None } 95 | 96 | Future { 97 | canvas.getGraphicsContext2D.setFill(Color.WHITE) 98 | canvas.getGraphicsContext2D.fillRect(0.0, 0.0, args.windowSize.toDouble, args.windowSize.toDouble) 99 | }(Ui) 100 | } 101 | } 102 | 103 | abstract class WorldNoGlobal[C <: Cell[C]] extends World[C, Empty[C]] { 104 | override protected val auto: AutomatonNoGlobal[C] 105 | } 106 | 107 | trait GameContract { 108 | def next(): Boolean 109 | def init(): Unit 110 | } -------------------------------------------------------------------------------- /src/main/scala/caart/visualisation/examples/ChaseWorld.scala: -------------------------------------------------------------------------------- 1 | package caart.visualisation.examples 2 | 3 | import caart.Arguments 4 | import caart.engine.Automaton 5 | import caart.engine.fields.RGB 6 | import caart.examples.{Chase, ChaseGlobal} 7 | import caart.visualisation.{UserEvent, UserEventType, World} 8 | import com.typesafe.scalalogging.LazyLogging 9 | import javafx.scene.paint.Color 10 | 11 | import scala.util.Random 12 | 13 | final class ChaseWorld(override protected val args: Arguments) extends World[Chase, ChaseGlobal] with LazyLogging { 14 | override protected val auto: Automaton[Chase, ChaseGlobal] = Chase.automaton(args.dim) 15 | 16 | override protected def processUserEvent(event: UserEvent): Unit = event match { 17 | case UserEvent(Some(pos), UserEventType.LeftClick) => 18 | val color = RGB.rainbow(Random.nextInt(RGB.rainbow.size)).toCMYK 19 | auto.eventHub ! (pos, Chase.CreateChaser(color)) 20 | case UserEvent(Some(pos), UserEventType.RightClick) => 21 | auto.eventHub ! Chase.SetPlayer(pos) 22 | auto.eventHub ! (pos, Chase.SetPlayerHere) 23 | case _ => 24 | } 25 | 26 | override protected def toColor(cell: Chase): Color = { 27 | val rgb = auto.updatedByEvents(cell).getOrElse(cell).color.toRGB 28 | Color.rgb(rgb.r, rgb.g, rgb.b) 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/main/scala/caart/visualisation/examples/GameOfLifeWorld.scala: -------------------------------------------------------------------------------- 1 | package caart.visualisation.examples 2 | 3 | import caart.Arguments 4 | import caart.engine.AutomatonNoGlobal 5 | import caart.examples.GameOfLife 6 | import caart.visualisation.{UserEvent, WorldNoGlobal} 7 | import javafx.scene.paint.Color 8 | 9 | final class GameOfLifeWorld(override protected val args: Arguments) extends WorldNoGlobal[GameOfLife] { 10 | override protected val auto: AutomatonNoGlobal[GameOfLife] = GameOfLife.automatonNoGlobal(args.dim) 11 | 12 | override protected def toColor(cell: GameOfLife): Color = 13 | auto.updatedByEvents(cell) match { 14 | case Some(newCell) if newCell.life => Color.RED 15 | case None if cell.life => Color.BLACK 16 | case _ => Color.WHITE 17 | } 18 | 19 | override protected def processUserEvent(event: UserEvent): Unit = 20 | event.pos.foreach(auto.eventHub ! (_, GameOfLife.FlipCell)) 21 | } 22 | -------------------------------------------------------------------------------- /src/main/scala/caart/visualisation/examples/LangtonsAntWorld.scala: -------------------------------------------------------------------------------- 1 | package caart.visualisation.examples 2 | 3 | import caart.Arguments 4 | import caart.engine.AutomatonNoGlobal 5 | import caart.examples.LangtonsAnt 6 | import caart.visualisation.{UserEvent, WorldNoGlobal} 7 | import javafx.scene.paint.Color 8 | 9 | final class LangtonsAntWorld(override protected val args: Arguments) extends WorldNoGlobal[LangtonsAnt] { 10 | override protected val auto: AutomatonNoGlobal[LangtonsAnt] = LangtonsAnt.automatonNoGlobal(args.dim) 11 | 12 | override protected def toColor(cell: LangtonsAnt): Color = { 13 | val c = auto.updatedByEvents(cell).getOrElse(cell) 14 | (c.color, c.dir) match { 15 | case (_, Some(_)) => Color.RED 16 | case (false, _) => Color.WHITE 17 | case (true, _) => Color.BLACK 18 | } 19 | } 20 | 21 | override protected def processUserEvent(event: UserEvent): Unit = 22 | event.pos.foreach(auto.eventHub ! (_, LangtonsAnt.CreateAnt)) 23 | } 24 | -------------------------------------------------------------------------------- /src/main/scala/caart/visualisation/examples/LangtonsColorsWorld.scala: -------------------------------------------------------------------------------- 1 | package caart.visualisation.examples 2 | 3 | import caart.Arguments 4 | import caart.engine.AutomatonNoGlobal 5 | import caart.engine.fields.{CMYK, Dir2D} 6 | import caart.examples.LangtonsColors 7 | import caart.visualisation.{UserEvent, WorldNoGlobal} 8 | import javafx.scene.paint.Color 9 | 10 | import scala.util.Random 11 | 12 | final class LangtonsColorsWorld(override val args: Arguments) extends WorldNoGlobal[LangtonsColors] { 13 | override val auto: AutomatonNoGlobal[LangtonsColors] = LangtonsColors.automatonNoGlobal(args.dim) 14 | 15 | override protected def toColor(cell: LangtonsColors): Color = { 16 | val c = auto.updatedByEvents(cell).getOrElse(cell) 17 | if (c.colors.isEmpty) Color.WHITE 18 | else { 19 | val rgb = CMYK.sum(c.colors).toRGB 20 | Color.rgb(rgb.r, rgb.g, rgb.b) 21 | } 22 | } 23 | 24 | override protected def processUserEvent(event: UserEvent): Unit = event.pos.foreach { pos => 25 | val dir = Dir2D.dirs4(Random.nextInt(Dir2D.dirs4.length)) 26 | val color = CMYK.colors(Random.nextInt(CMYK.colors.length)) 27 | auto.eventHub ! (pos, LangtonsColors.CreateAnt(color, dir)) 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/main/scala/caart/visualisation/examples/SnakeWorld.scala: -------------------------------------------------------------------------------- 1 | package caart.visualisation.examples 2 | 3 | import caart.Arguments 4 | import caart.engine.fields.{Dir2D, Pos2D} 5 | import caart.engine.{Automaton, GlobalUpdateStrategy, UpdateStrategy} 6 | import caart.examples.Snake.{Body, Head, Tail, globalCell} 7 | import caart.examples.{Snake, SnakeGlobal} 8 | import caart.visualisation.{UserEvent, World} 9 | import com.almasb.fxgl.dsl.FXGL 10 | import com.typesafe.scalalogging.LazyLogging 11 | import javafx.scene.input.KeyCode 12 | import javafx.scene.paint.Color 13 | 14 | final class SnakeWorld(override protected val args: Arguments) extends World[Snake, SnakeGlobal] with LazyLogging { 15 | import Snake.{TurnLeft, TurnRight} 16 | import UserEvent.{MoveUp, MoveDown, MoveLeft, MoveRight} 17 | 18 | override protected val auto: Automaton[Snake, SnakeGlobal] = 19 | Snake.automaton( 20 | dim = args.dim, 21 | updateStrategy = UpdateStrategy.onlySelf[Snake], 22 | globalUpdateStrategy = GlobalUpdateStrategy.onlyEvents[Snake, SnakeGlobal] 23 | ) 24 | 25 | override protected def toColor(c: Snake): Color = c.cellType match { 26 | case Snake.Empty => Color.WHITE 27 | case Snake.Treat => Color.ORANGE 28 | case Snake.Head(_) => Color.BROWN 29 | case Snake.Body(_, _) => Color.BLACK 30 | case Snake.Tail(_) => Color.BLACK 31 | } 32 | 33 | override protected def processUserEvent(event: UserEvent): Unit = { 34 | val headDir = auto.globalCell.headDir 35 | val turn: Option[Snake.GlobalEvent] = event match { 36 | case MoveUp if headDir == Dir2D.Right => Some(TurnLeft) 37 | case MoveUp if headDir == Dir2D.Left => Some(TurnRight) 38 | case MoveDown if headDir == Dir2D.Right => Some(TurnRight) 39 | case MoveDown if headDir == Dir2D.Left => Some(TurnLeft) 40 | case MoveLeft if headDir == Dir2D.Up => Some(TurnLeft) 41 | case MoveLeft if headDir == Dir2D.Down => Some(TurnRight) 42 | case MoveRight if headDir == Dir2D.Up => Some(TurnRight) 43 | case MoveRight if headDir == Dir2D.Down => Some(TurnLeft) 44 | case _ => None 45 | } 46 | turn.foreach(auto.eventHub ! _) 47 | } 48 | 49 | override def init(): Unit = { 50 | super.init() 51 | val center = Pos2D(args.dim / 2, args.dim / 2) 52 | auto.updateCell(center) { _.copy(cellType = Body(Dir2D.Right, Dir2D.Left)) } 53 | auto.updateCell(center.move(Dir2D.Left)) { _.copy(cellType = Tail(Dir2D.Right)) } 54 | auto.updateCell(center.move(Dir2D.Right)) { _.copy(cellType = Head(Dir2D.Right)) } 55 | 56 | FXGL.onKeyUp(KeyCode.UP, () => onUserEvent ! MoveUp) 57 | FXGL.onKeyUp(KeyCode.DOWN, () => onUserEvent ! MoveDown) 58 | FXGL.onKeyUp(KeyCode.LEFT, () => onUserEvent ! MoveLeft) 59 | FXGL.onKeyUp(KeyCode.RIGHT, () => onUserEvent ! MoveRight) 60 | } 61 | 62 | override def next(): Boolean = 63 | if (auto.globalCell.gameOver) { 64 | logger.info(s"Game over! Your score: ${auto.globalCell.score}") 65 | false 66 | } else 67 | super.next() 68 | } 69 | -------------------------------------------------------------------------------- /src/main/scala/caart/visualisation/package.scala: -------------------------------------------------------------------------------- 1 | package caart 2 | 3 | import caart.engine.fields.Pos2D 4 | 5 | package object visualisation { 6 | sealed trait GameState 7 | 8 | object GameState { 9 | case object Pause extends GameState 10 | case object Play extends GameState 11 | case object End extends GameState 12 | } 13 | 14 | sealed trait UserEventType 15 | 16 | object UserEventType { 17 | case object LeftClick extends UserEventType 18 | case object RightClick extends UserEventType 19 | case object MoveUp extends UserEventType 20 | case object MoveDown extends UserEventType 21 | case object MoveLeft extends UserEventType 22 | case object MoveRight extends UserEventType 23 | } 24 | 25 | final case class UserEvent(pos: Option[Pos2D], eventType: UserEventType) 26 | object UserEvent { 27 | val MoveUp: UserEvent = UserEvent(None, UserEventType.MoveUp) 28 | val MoveDown: UserEvent = UserEvent(None, UserEventType.MoveDown) 29 | val MoveLeft: UserEvent = UserEvent(None, UserEventType.MoveLeft) 30 | val MoveRight: UserEvent = UserEvent(None, UserEventType.MoveRight) 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/test/scala/caart/engine/fields/CMYKSpec.scala: -------------------------------------------------------------------------------- 1 | package caart.engine.fields 2 | 3 | class CMYKSpec extends munit.FunSuite { 4 | test("CMYK color should multiply by a coefficient") { 5 | val c = CMYK(1.0, 0.0, 0.0, 0.0) 6 | assertEquals(c * 0.5, CMYK(0.5, 0.0, 0.0, 0.0)) 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /src/test/scala/caart/engine/fields/Dir2DSpec.scala: -------------------------------------------------------------------------------- 1 | package caart.engine.fields 2 | 3 | class Dir2DSpec extends munit.FunSuite { 4 | test("Dir2D should approximate to the nearest von Neumann's neighbor") { 5 | assertEquals(new Dir2D(1.0, -2.0).approx4, Up) 6 | assertEquals(new Dir2D(-1.0, -2.0).approx4, Up) 7 | 8 | assertEquals(new Dir2D(2.0, -1.0).approx4, Right) 9 | assertEquals(new Dir2D(2.0, 1.0).approx4, Right) 10 | 11 | assertEquals(new Dir2D(1.0, 2.0).approx4, Down) 12 | assertEquals(new Dir2D(-1.0, 2.0).approx4, Down) 13 | 14 | assertEquals(new Dir2D(-2.0, -1.0).approx4, Left) 15 | assertEquals(new Dir2D(-2.0, 1.0).approx4, Left) 16 | 17 | assertEquals(new Dir2D(-1.0, 0.0).approx4, Left) 18 | assertEquals(new Dir2D(1.0, 0.0).approx4, Right) 19 | assertEquals(new Dir2D(0.0, -1.0).approx4, Up) 20 | assertEquals(new Dir2D(0.0, 1.0).approx4, Down) 21 | } 22 | 23 | test("Dir2D should approximate to the nearest Moore's neighbor") { 24 | assertEquals(new Dir2D(1.0, -3.0).approx8, Up) 25 | assertEquals(new Dir2D(-1.0, -3.0).approx8, Up) 26 | 27 | assertEquals(new Dir2D(1.5, -2.0).approx8, UpRight) 28 | assertEquals(new Dir2D(2.0, -1.5).approx8, UpRight) 29 | 30 | assertEquals(new Dir2D(3.0, -1.0).approx8, Right) 31 | assertEquals(new Dir2D(3.0, 1.0).approx8, Right) 32 | 33 | assertEquals(new Dir2D(1.5, 2.0).approx8, DownRight) 34 | assertEquals(new Dir2D(2.0, 1.5).approx8, DownRight) 35 | 36 | assertEquals(new Dir2D(1.0, 3.0).approx8, Down) 37 | assertEquals(new Dir2D(-1.0, 3.0).approx8, Down) 38 | 39 | assertEquals(new Dir2D(-1.5, 2.0).approx8, DownLeft) 40 | assertEquals(new Dir2D(-2.0, 1.5).approx8, DownLeft) 41 | 42 | assertEquals(new Dir2D(-3.0, -1.0).approx8, Left) 43 | assertEquals(new Dir2D(-3.0, 1.0).approx8, Left) 44 | 45 | assertEquals(new Dir2D(-1.5, -2.0).approx8, UpLeft) 46 | assertEquals(new Dir2D(-2.0, -1.5).approx8, UpLeft) 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /system/Readme.txt: -------------------------------------------------------------------------------- 1 | This directory contains FXGL system data files. --------------------------------------------------------------------------------