├── .gitignore ├── LICENSE ├── README.md ├── activator.properties ├── build.sbt ├── lib ├── tg-src.jar └── tg.jar ├── project ├── build.properties └── plugins.sbt ├── src └── main │ ├── resources │ ├── common.conf │ ├── reactive-turtle.conf │ └── turtle-rc.conf │ └── scala │ └── com │ └── github │ └── ktonga │ └── reactiveturtle │ ├── example │ ├── AkkaAppExample.scala │ ├── ImportRcExample.scala │ └── ScalaAppExample.scala │ ├── internal │ ├── ReactiveTurtle.scala │ ├── TGW.scala │ └── TurtleGraphicsActor.scala │ ├── package.scala │ └── rc.scala ├── tg.sbt └── tutorial ├── activator-tg-start.png ├── console.png ├── index.html ├── run-akka.png ├── run-scala.png └── tg-start.png /.gitignore: -------------------------------------------------------------------------------- 1 | /RUNNING_PID 2 | /logs/ 3 | /tags 4 | 5 | /src/main/java/ 6 | 7 | ### Scala template 8 | *.class 9 | *.log 10 | *.sc 11 | 12 | # sbt specific 13 | .cache/ 14 | .history/ 15 | .lib/ 16 | dist/* 17 | target/ 18 | lib_managed/ 19 | src_managed/ 20 | project/boot/ 21 | project/plugins/project/ 22 | 23 | # Scala-IDE specific 24 | .scala_dependencies 25 | .worksheet 26 | 27 | ### JetBrains template 28 | # Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm 29 | 30 | ## Directory-based project format 31 | .idea/ 32 | /*.iml 33 | # if you remove the above rule, at least ignore user-specific stuff: 34 | # .idea/workspace.xml 35 | # .idea/tasks.xml 36 | # .idea/dictionaries 37 | # and these sensitive or high-churn files: 38 | # .idea/dataSources.ids 39 | # .idea/dataSources.xml 40 | # .idea/sqlDataSources.xml 41 | # .idea/dynamic.xml 42 | # and, if using gradle:: 43 | # .idea/gradle.xml 44 | # .idea/libraries 45 | 46 | ## File-based project format 47 | *.ipr 48 | *.iws 49 | 50 | ## Additional for IntelliJ 51 | out/ 52 | 53 | # generated by mpeltonen/sbt-idea plugin 54 | .idea_modules/ 55 | 56 | # generated by JIRA plugin 57 | atlassian-ide-plugin.xml 58 | 59 | # generated by Crashlytics plugin (for Android Studio and Intellij) 60 | com_crashlytics_export_strings.xml 61 | 62 | ### Eclipse template 63 | *.pydevproject 64 | .metadata 65 | .gradle 66 | bin/ 67 | tmp/ 68 | *.tmp 69 | *.bak 70 | *.swp 71 | *~.nib 72 | local.properties 73 | .settings/ 74 | .loadpath 75 | 76 | # External tool builders 77 | .externalToolBuilders/ 78 | 79 | # Locally stored "Eclipse launch configurations" 80 | *.launch 81 | 82 | # CDT-specific 83 | .cproject 84 | 85 | # PDT-specific 86 | .buildpath 87 | 88 | # sbteclipse plugin 89 | .target 90 | 91 | # TeXlipse plugin 92 | .texlipse 93 | 94 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | 203 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | reactive-turtle 2 | =============== 3 | 4 | Teach Typesafe Stack (Scala and Akka) to the kids the funny way 5 | 6 | - Launch the Turtle Graphics in a separate window 7 | - Command the Turtle from a separate JVM with the Remote Control 8 | - Defer side-effects to the very end of the program 9 | - Define your program in a Functional way composing simple Functions 10 | - Define your program based on Akka Actors 11 | - Use the IDE of your choise. Vim + SBT, REPL, Idea, Eclipse, etc. 12 | 13 | The Story 14 | --------- 15 | 16 | This, is a story, about a father and his son, then about the father the father the father, and then again his son. 17 | 18 | #### The father and his son part 19 | 20 | I have a son called Elian, he’s 11 and he’s very smart, so I decided to teach him programming. 21 | Obviously I love him, so I choose to go with **Scala**. 22 | I started with some basics, vals and defs for doing some maths, but it quickly became boring so my son lost the interest. 23 | 24 | The first thing that came to my mind was LOGO, playing with the turtle is great for learning programming. Since I use KDE (that’s why the K stand for in my nickname ktonga) I’ve installed KTurtle, it’s a nice educational app, but sadly as every LOGO’s clone out there, it’s based on an imperative language. And I wanted to teach my son FP. 25 | 26 | 27 | #### So this is the father the father the father part of the story 28 | 29 | I started researching turtle programming environments, I found many for Java and a very nice one for Scala, but with a pretty imperative approach, so I didn’t like it. 30 | 31 | I decided to create my own, but I didn’t want to focus in the IDE part as all the rest does. So much effort on syntax highlight, auto-complete, errors marks, etc.. Nothing of that is needed since lot of environments already exist that do it fantastically. 32 | I was lucky, and one of the Java based environments has a standalone graphics part which I use to command remotely from a program developed in the IDE of my choice. 33 | 34 | The idea of reactive turtle is to command the turtle in a functional way, so I designed a minimal API to separate the program’s instructions from the side effects (moving the turtle). You can compose pure functions to create a list of commands which then will be run by the turtle 35 | 36 | #### The son part again 37 | 38 | Once I finished, I resumed the teaching to my son again. 39 | 40 | Try it out and let me know what you think! 41 | 42 | 43 | Get Started 44 | ----------- 45 | 46 | ```sh 47 | git clone https://github.com/ktonga/reactive-turtle.git 48 | cd reactive-turtle 49 | sbt compile 50 | ``` 51 | 52 | Playing with the Turtle 53 | ----------------------- 54 | 55 | ### Start the Turtle Graphics (TG) Window 56 | 57 | The first you need to do in order to use `Reactive Turtle` is to start the TG, it will open a window with the canvas and will start listening for remote `Commands`. You do it by launching the SBT shell and executing the task `tg-start`. It will run in a background JVM and will return back the SBT shell prompt. Optionaly you can pass width and height args. They are 600 600 by default. 58 | 59 | ```sh 60 | sbt 61 | [info] Set current project to reactive-turtle 62 | > tg-start 500 500 63 | ``` 64 | 65 | You can terminate it, closing the window or executing the task `tg-stop` in the SBT shell. 66 | 67 | ```sh 68 | > tg-stop 69 | ``` 70 | 71 | ![tg-start](https://raw.githubusercontent.com/ktonga/reactive-turtle/master/tutorial/tg-start.png) 72 | 73 | 74 | ### Scripting with the Turtle 75 | 76 | We have the turtle, now we want to tell it some movements. The fastest way to start commanding the turtle is by launching the Scala REPL. You can do it right in the SBT session you have open for the TG window. Execute the console task, it will start with all the needed imports already evaluated. 77 | You have many ways to send Commands to the turtle, the easiest ones are the synchronous. When you'r done with the console, type `:q` for going back to SBT shell prompt. 78 | 79 | ```scala 80 | // run var args Commands 81 | runAndWait(SetXY(100, 400), Clean) 82 | 83 | // run a Seq of Commands 84 | val commands = Seq.fill(4)(Seq(Forward(300), Right(90))).flatten 85 | runAllAndWait(commands) 86 | 87 | // run a single Command 88 | PenUp.rnw 89 | Home.rnw 90 | ``` 91 | 92 | You can take a look at [`TurtleRC`](https://github.com/ktonga/reactive-turtle/blob/master/src/main/scala/com/github/ktonga/reactiveturtle/rc.scala) trait for available methods and [`Commands`](https://github.com/ktonga/reactive-turtle/blob/master/src/main/scala/com/github/ktonga/reactiveturtle/package.scala) object for available commands. 93 | 94 | ![tg-start](https://raw.githubusercontent.com/ktonga/reactive-turtle/master/tutorial/console.png) 95 | 96 | 97 | ### Functional Programming in Scala with the Turtle 98 | 99 | I'm using the [Turtle Graphics](http://www.bfoit.org/itp/JavaTurtleGraphics.html) implemented by [BFOIT](http://www.bfoit.org/) which is done in Java, obviously in imperative programming, so all the turtle methods have side-effects. But thanks to a piece of advice from the excelent book [Functional Programming in Scala](http://manning.com/FunctionalProgramminginScala) writen by @pchiusano and @runarorama I've separated the program's logic from the movements that actually has to do the turtle at the end of the program. 100 | 101 | You will be able to define the `Seq[Command]` composing all the pure functions you want. For writting your Turtle Scala Program you have to extend the [ScalaApp](src/main/scala/com/github/ktonga/reactiveturtle/rc.scala) trait and implement the `def commands: Seq[Command]` method. 102 | 103 | ```scala 104 | package com.github.ktonga.reactiveturtle.example 105 | 106 | import com.github.ktonga.reactiveturtle._ 107 | import Commands._ 108 | 109 | object ScalaAppExample extends ScalaApp with Shapes { 110 | 111 | def commands: Seq[Command] = 112 | layout( 113 | Seq((200, 200), (400, 200), (300, 400)), 114 | Seq(square(50), circle(5), spiral(20)) 115 | ) 116 | 117 | } 118 | 119 | trait Shapes { 120 | 121 | type Shape = Seq[Command] 122 | 123 | def square(size: Int): Shape = { 124 | (1 to 4).flatMap(_ => Seq(Forward(size), Right(90))) 125 | } 126 | 127 | def spiral(size: Int): Shape = { 128 | (1 to 100).flatMap(a => Seq(Forward(size), Right(110 - a))) 129 | } 130 | 131 | def circle(size: Int): Shape = { 132 | (1 to 90).flatMap(a => Seq(Forward(size), Right(4))) 133 | } 134 | 135 | def layout(points: Seq[(Int, Int)], shapes: Seq[Shape]): Seq[Command] = 136 | points.zip(shapes).flatMap {case ((x, y), cmds) => PenUp +: SetXY(x, y) +: PenDown +: cmds} 137 | 138 | } 139 | 140 | ``` 141 | 142 | You can run your programs, or any of the included [examples](src/main/scala/com/github/ktonga/reactiveturtle/example), executing the `run` task in the SBT session and chosing one from the list. 143 | 144 | ![tg-start](https://raw.githubusercontent.com/ktonga/reactive-turtle/master/tutorial/run-scala.png) 145 | 146 | ### hAkking with the Turtle 147 | 148 | Once your child becomes a Scala expert, you can introduce him/her into the wonderful world of [Akka](http://akka.io/). The TG is represented by an `Actor` and you'll have to implement your own `Actor` to interact with the TG, sending Commands and receiving [`States`](src/main/scala/com/github/ktonga/reactiveturtle/package.scala). The way to do it, is extending the [`AkkaApp`](src/main/scala/com/github/ktonga/reactiveturtle/rc.scala) trait, defining the `Actor` and implementing the `def props: Props` method which must return a `Props` of your `Actor`. The first message the `Actor` will receive will be a `State` case class and the sender will be the TG `Actor`. The program ends when your `Actor` terminates. 149 | 150 | ```scala 151 | package com.github.ktonga.reactiveturtle.example 152 | 153 | import akka.actor.{PoisonPill, Actor, Props} 154 | import com.github.ktonga.reactiveturtle._ 155 | import internal.TurtleGraphicsActor.Execute 156 | import Commands._ 157 | 158 | 159 | object AkkaAppExample extends AkkaApp { 160 | override def props: Props = Props[CommandsActor] 161 | } 162 | 163 | class CommandsActor extends Actor { 164 | 165 | val step = 5 166 | val inclination = 5 167 | 168 | val heading2right = 90 + inclination 169 | val heading2left = 270 - inclination 170 | 171 | def receive: Receive = { 172 | case state @ State(Canvas(w, _), _) => 173 | sender ! Execute(Seq(Clean, PenUp, SetXY(0, 0), PenDown, Heading(heading2right))) 174 | context.become(left2right(w)) 175 | } 176 | 177 | val right2left = moving(x => x - step <= 0) { 178 | sender ! Heading(heading2right) 179 | context.unbecome() 180 | } 181 | 182 | def left2right(w: Int) = moving(x => x + step >= w) { 183 | sender ! Heading(heading2left) 184 | context.become(right2left, discardOld = false) 185 | } 186 | 187 | def moving(stop: Int => Boolean)(next: => Unit): Receive = { 188 | case State(Canvas(_, h), Turtle(_, y, _, _, _)) if y + 10 >= h => 189 | self ! PoisonPill 190 | case State(_, Turtle(x, _, _, _, _)) if stop(x) => 191 | next 192 | case s => 193 | sender ! Forward(step) 194 | } 195 | } 196 | 197 | ``` 198 | 199 | The way for running it is the same as for the Scala example. 200 | 201 | ![run-akka](https://raw.githubusercontent.com/ktonga/reactive-turtle/master/tutorial/run-akka.png) 202 | 203 | ### Ready! 204 | 205 | Now, enjoy of quality time with your children. 206 | -------------------------------------------------------------------------------- /activator.properties: -------------------------------------------------------------------------------- 1 | name=reactive-turtle 2 | title=Reactive Turtle 3 | description=Scala and Akka for kids. A Functional Programming approach for the well known LOGO. 4 | tags=tutorial,scala,akka,kids 5 | -------------------------------------------------------------------------------- /build.sbt: -------------------------------------------------------------------------------- 1 | import spray.revolver.AppProcess 2 | 3 | name := """reactive-turtle""" 4 | 5 | version := "1.0" 6 | 7 | scalaVersion := "2.11.1" 8 | 9 | // Change this to another test framework if you prefer 10 | libraryDependencies ++= Seq( 11 | "com.typesafe.akka" %% "akka-actor" % "2.3.4", 12 | "com.typesafe.akka" %% "akka-remote" % "2.3.4" 13 | ) 14 | 15 | Revolver.settings 16 | 17 | mainClass in Revolver.reStart := Some("com.github.ktonga.reactiveturtle.internal.ReactiveTurtle") 18 | 19 | initialCommands in console := 20 | """ 21 | |import com.github.ktonga.reactiveturtle._ 22 | |import Commands._ 23 | |import TurtleRC._ 24 | """.stripMargin 25 | 26 | cleanupCommands in console := 27 | """ 28 | |shutdown() 29 | """.stripMargin 30 | 31 | addCommandAlias("tg-start", "re-start") 32 | 33 | addCommandAlias("tg-stop", "re-stop") 34 | -------------------------------------------------------------------------------- /lib/tg-src.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ktonga/reactive-turtle/a0f6f15e22a7019b358f3bd248285279aa543c16/lib/tg-src.jar -------------------------------------------------------------------------------- /lib/tg.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ktonga/reactive-turtle/a0f6f15e22a7019b358f3bd248285279aa543c16/lib/tg.jar -------------------------------------------------------------------------------- /project/build.properties: -------------------------------------------------------------------------------- 1 | sbt.version=0.13.5 2 | -------------------------------------------------------------------------------- /project/plugins.sbt: -------------------------------------------------------------------------------- 1 | 2 | addSbtPlugin("io.spray" % "sbt-revolver" % "0.7.2") 3 | 4 | -------------------------------------------------------------------------------- /src/main/resources/common.conf: -------------------------------------------------------------------------------- 1 | akka { 2 | 3 | loglevel = OFF 4 | log-dead-letters-during-shutdown = off 5 | 6 | actor { 7 | provider = "akka.remote.RemoteActorRefProvider" 8 | } 9 | 10 | remote { 11 | netty.tcp { 12 | hostname = "127.0.0.1" 13 | } 14 | } 15 | 16 | } 17 | -------------------------------------------------------------------------------- /src/main/resources/reactive-turtle.conf: -------------------------------------------------------------------------------- 1 | include "common" 2 | 3 | akka.remote.netty.tcp.port = 2552 4 | -------------------------------------------------------------------------------- /src/main/resources/turtle-rc.conf: -------------------------------------------------------------------------------- 1 | include "common" 2 | 3 | akka.remote.netty.tcp.port = 2553 4 | -------------------------------------------------------------------------------- /src/main/scala/com/github/ktonga/reactiveturtle/example/AkkaAppExample.scala: -------------------------------------------------------------------------------- 1 | package com.github.ktonga.reactiveturtle.example 2 | 3 | import akka.actor.{PoisonPill, Actor, Props} 4 | import com.github.ktonga.reactiveturtle._ 5 | import internal.TurtleGraphicsActor.Execute 6 | import Commands._ 7 | 8 | 9 | object AkkaAppExample extends AkkaApp { 10 | override def props: Props = Props[CommandsActor] 11 | } 12 | 13 | class CommandsActor extends Actor { 14 | 15 | val step = 5 16 | val inclination = 5 17 | 18 | val heading2right = 90 + inclination 19 | val heading2left = 270 - inclination 20 | 21 | def receive: Receive = { 22 | case state @ State(Canvas(w, _), _) => 23 | sender ! Execute(Seq(Clean, PenUp, SetXY(0, 0), PenDown, Heading(heading2right))) 24 | context.become(left2right(w)) 25 | } 26 | 27 | val right2left = moving(x => x - step <= 0) { 28 | sender ! Heading(heading2right) 29 | context.unbecome() 30 | } 31 | 32 | def left2right(w: Int) = moving(x => x + step >= w) { 33 | sender ! Heading(heading2left) 34 | context.become(right2left, discardOld = false) 35 | } 36 | 37 | def moving(stop: Int => Boolean)(next: => Unit): Receive = { 38 | case State(Canvas(_, h), Turtle(_, y, _, _, _)) if y + 10 >= h => 39 | self ! PoisonPill 40 | case State(_, Turtle(x, _, _, _, _)) if stop(x) => 41 | next 42 | case s => 43 | sender ! Forward(step) 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /src/main/scala/com/github/ktonga/reactiveturtle/example/ImportRcExample.scala: -------------------------------------------------------------------------------- 1 | package com.github.ktonga.reactiveturtle.example 2 | 3 | import com.github.ktonga.reactiveturtle._ 4 | import Commands._ 5 | import TurtleRC._ 6 | 7 | object ImportRcExample extends App { 8 | 9 | import scala.concurrent.ExecutionContext.Implicits.global 10 | 11 | def withPenUp(cmds: Command*) = PenUp +: cmds :+ PenDown 12 | 13 | Clean.rnw 14 | 15 | await( 16 | for { 17 | State(Canvas(w, h), _) <- runAll( withPenUp( SetXY(0, 0), PenSize(8) )) 18 | _ <- run( SetXY(w, h) ) 19 | _ <- runAll( withPenUp( SetY(0) )) 20 | state <- run( SetXY(0, h) ) 21 | } yield state 22 | ) 23 | 24 | runAllAndWait( withPenUp( Home, Forward(50) )) 25 | shutdown() 26 | } 27 | -------------------------------------------------------------------------------- /src/main/scala/com/github/ktonga/reactiveturtle/example/ScalaAppExample.scala: -------------------------------------------------------------------------------- 1 | package com.github.ktonga.reactiveturtle.example 2 | 3 | import com.github.ktonga.reactiveturtle._ 4 | import Commands._ 5 | 6 | object ScalaAppExample extends ScalaApp with Shapes { 7 | 8 | def commands: Seq[Command] = 9 | layout( 10 | Seq((200, 200), (400, 200), (300, 400)), 11 | Seq(square(50), circle(5), spiral(20)) 12 | ) 13 | 14 | } 15 | 16 | trait Shapes { 17 | 18 | type Shape = Seq[Command] 19 | 20 | def square(size: Int): Shape = { 21 | (1 to 4).flatMap(_ => Seq(Forward(size), Right(90))) 22 | } 23 | 24 | def spiral(size: Int): Shape = { 25 | (1 to 100).flatMap(a => Seq(Forward(size), Right(110 - a))) 26 | } 27 | 28 | def circle(size: Int): Shape = { 29 | (1 to 90).flatMap(a => Seq(Forward(size), Right(4))) 30 | } 31 | 32 | def layout(points: Seq[(Int, Int)], shapes: Seq[Shape]): Seq[Command] = 33 | points.zip(shapes).flatMap {case ((x, y), cmds) => PenUp +: SetXY(x, y) +: PenDown +: cmds} 34 | 35 | } 36 | 37 | -------------------------------------------------------------------------------- /src/main/scala/com/github/ktonga/reactiveturtle/internal/ReactiveTurtle.scala: -------------------------------------------------------------------------------- 1 | package com.github.ktonga.reactiveturtle.internal 2 | 3 | import akka.actor.ActorSystem 4 | import com.typesafe.config.ConfigFactory 5 | 6 | object ReactiveTurtle extends App { 7 | 8 | implicit val system = ActorSystem("reactive-turtle", ConfigFactory.load("reactive-turtle")) 9 | 10 | val (width, height) = args.toList match { 11 | case w :: h :: Nil => (w.toInt, h.toInt) 12 | case _ => (600, 600) 13 | } 14 | 15 | system.actorOf(TurtleGraphicsActor.props(width, height), "tg") 16 | 17 | } 18 | -------------------------------------------------------------------------------- /src/main/scala/com/github/ktonga/reactiveturtle/internal/TGW.scala: -------------------------------------------------------------------------------- 1 | package com.github.ktonga.reactiveturtle.internal 2 | 3 | import com.github.ktonga.reactiveturtle._ 4 | import org.bfoit.tg.TurtleGraphicsWindow 5 | import Commands._ 6 | 7 | class TGW(width: Int, height: Int) 8 | extends TurtleGraphicsWindow(width, height) { 9 | 10 | def execute(command: Command) = command match { 11 | case Clean => clean() 12 | case Home => home() 13 | case PenDown => pendown() 14 | case PenUp => penup() 15 | case Forward(steps) => forward(steps) 16 | case Back(steps) => back(steps) 17 | case Right(degrees) => right(degrees) 18 | case Left(degrees) => left(degrees) 19 | case SetX(x) => setx(x2tg(x)) 20 | case SetY(y) => sety(y2tg(y)) 21 | case SetXY(x, y) => setxy(x2tg(x), y2tg(y)) 22 | case Heading(degrees) => setheading(degrees) 23 | case PenSize(penWidth) => setpensize(penWidth) 24 | } 25 | 26 | private def x2tg(x: Int) = x - (width / 2) 27 | private def y2tg(y: Int) = -(y - (height / 2)) 28 | private def tg2x(x: Int) = x + (width / 2) 29 | private def tg2y(y: Int) = (height / 2) - y 30 | 31 | def tgState = State( 32 | Canvas(width, height), 33 | Turtle(tg2x(xcor()), tg2y(ycor()), heading().toInt, ispendown(), pensize()) 34 | ) 35 | 36 | } 37 | 38 | object TGW { 39 | def apply(width: Int, height: Int) = new TGW(width, height) 40 | } 41 | -------------------------------------------------------------------------------- /src/main/scala/com/github/ktonga/reactiveturtle/internal/TurtleGraphicsActor.scala: -------------------------------------------------------------------------------- 1 | package com.github.ktonga.reactiveturtle.internal 2 | 3 | import akka.actor.{Actor, Props} 4 | import com.github.ktonga.reactiveturtle.Command 5 | 6 | object TurtleGraphicsActor { 7 | 8 | // Protocol 9 | case class Execute(commands: Seq[Command]) 10 | case object GetState 11 | 12 | // Props 13 | def props(width:Int, height: Int): Props = Props(new TurtleGraphicsActor(width, height)) 14 | } 15 | 16 | class TurtleGraphicsActor(width: Int, height: Int) extends Actor { 17 | import com.github.ktonga.reactiveturtle.internal.TurtleGraphicsActor._ 18 | 19 | val tgw = TGW(width, height) 20 | 21 | override def receive: Receive = { 22 | case Execute(cmds) => 23 | cmds.foreach(tgw.execute) 24 | sender ! tgw.tgState 25 | case cmd: Command => 26 | tgw.execute(cmd) 27 | sender ! tgw.tgState 28 | case GetState => sender ! tgw.tgState 29 | } 30 | 31 | } 32 | -------------------------------------------------------------------------------- /src/main/scala/com/github/ktonga/reactiveturtle/package.scala: -------------------------------------------------------------------------------- 1 | package com.github.ktonga 2 | 3 | package object reactiveturtle { 4 | 5 | sealed trait Command 6 | 7 | object Commands { 8 | case object Clean extends Command 9 | case object Home extends Command 10 | case object PenUp extends Command 11 | case object PenDown extends Command 12 | case class Forward(steps: Int) extends Command 13 | case class Back(steps: Int) extends Command 14 | case class Right(degrees: Int) extends Command 15 | case class Left(degrees: Int) extends Command 16 | case class SetX(x: Int) extends Command 17 | case class SetY(y: Int) extends Command 18 | case class SetXY(x: Int, y: Int) extends Command 19 | case class Heading(degrees: Int) extends Command 20 | case class PenSize(penWidth: Int) extends Command 21 | } 22 | 23 | case class Canvas(width: Int, height: Int) 24 | case class Turtle(x: Int, y: Int, heading: Int, 25 | penDown: Boolean, penSize: Int) 26 | case class State(canvas: Canvas, turtle: Turtle) 27 | 28 | } 29 | -------------------------------------------------------------------------------- /src/main/scala/com/github/ktonga/reactiveturtle/rc.scala: -------------------------------------------------------------------------------- 1 | package com.github.ktonga.reactiveturtle 2 | 3 | import akka.actor._ 4 | import akka.pattern.ask 5 | import akka.util.Timeout 6 | import com.github.ktonga.reactiveturtle.internal.TurtleGraphicsActor 7 | import com.typesafe.config.ConfigFactory 8 | import scala.concurrent.{Await, Future} 9 | import scala.concurrent.duration._ 10 | import scala.concurrent.ExecutionContext.Implicits.global 11 | import TurtleGraphicsActor._ 12 | 13 | trait TGRef { 14 | val remotePath = "akka.tcp://reactive-turtle@127.0.0.1:2552/user/tg" 15 | 16 | def configName = "turtle-rc" 17 | 18 | implicit val system = ActorSystem("turtle-rc", ConfigFactory.load(configName)) 19 | val tgRefFtr = system.actorSelection(remotePath).resolveOne(10.seconds) 20 | 21 | def shutdown() = system.shutdown() 22 | 23 | } 24 | 25 | trait TurtleRC extends TGRef { 26 | 27 | def runAll(commands: Seq[Command]): Future[State] = { 28 | implicit val askTimeout: Timeout = 1.minute 29 | tgRefFtr flatMap { ref => (ref ? Execute(commands)).mapTo[State] } 30 | } 31 | 32 | def run(commands: Command*): Future[State] = runAll(commands) 33 | 34 | def runAllAndWait(commands: Seq[Command]): State = await(runAll(commands)) 35 | 36 | def runAndWait(commands: Command*): State = runAllAndWait(commands) 37 | 38 | def getState: Future[State] = { 39 | implicit val askTimeout: Timeout = 1.minute 40 | tgRefFtr flatMap { ref => (ref ? GetState).mapTo[State] } 41 | } 42 | 43 | def awaitState: State = await(getState) 44 | 45 | def await[T](ftr: Future[T]): T = Await.result(ftr, Duration.Inf) 46 | } 47 | 48 | object TurtleRC extends TurtleRC { 49 | 50 | implicit class CommandOps(val cmd: Command) extends AnyVal { 51 | def r = run(cmd) 52 | def rnw = runAndWait(cmd) 53 | } 54 | 55 | } 56 | 57 | trait ScalaApp extends App with TurtleRC { 58 | 59 | def commands: Seq[Command] 60 | 61 | runAllAndWait(commands) 62 | shutdown() 63 | } 64 | 65 | trait AkkaApp extends App with TGRef { 66 | 67 | def props: Props 68 | 69 | val commandsRef = system.actorOf(props, "commands") 70 | 71 | val finisher = system.actorOf(Props(new Actor { 72 | def receive: Receive = { 73 | case watched: ActorRef => context.watch(watched) 74 | case Terminated(_) => context.system.shutdown() 75 | } 76 | }), "finisher") 77 | 78 | finisher ! commandsRef 79 | 80 | tgRefFtr onSuccess { 81 | case tgRef => tgRef.tell(GetState, commandsRef) 82 | } 83 | 84 | } -------------------------------------------------------------------------------- /tg.sbt: -------------------------------------------------------------------------------- 1 | import java.io.File 2 | 3 | val manifest = new java.util.jar.Manifest() 4 | def jar(base: File, dir: String, include: String, out: File) = { 5 | val files = (base / dir) ** include 6 | val target = files pair relativeTo(base :: Nil) 7 | IO.jar(target, out, manifest) 8 | out 9 | } 10 | 11 | lazy val tgJar = TaskKey[(File, File)]("tg-jar", "Jar TG classes and sources into lib folder") 12 | 13 | tgJar := { 14 | val lib = unmanagedBase.value 15 | ( 16 | jar((classDirectory in Compile).value, "org", "*.class", lib / "tg.jar"), 17 | jar((javaSource in Compile).value, "org", "*.java", lib / "tg-src.jar") 18 | ) 19 | } 20 | 21 | lazy val tgUnjar = TaskKey[Set[File]]("tg-unjar", "Unjar TG sources into src/main/java folder") 22 | 23 | tgUnjar := { 24 | val jar = unmanagedBase.value / "tg-src.jar" 25 | val dir = (javaSource in Compile).value 26 | //Seq(jar, dir) 27 | IO.unzip(jar, dir) 28 | } 29 | 30 | 31 | -------------------------------------------------------------------------------- /tutorial/activator-tg-start.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ktonga/reactive-turtle/a0f6f15e22a7019b358f3bd248285279aa543c16/tutorial/activator-tg-start.png -------------------------------------------------------------------------------- /tutorial/console.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ktonga/reactive-turtle/a0f6f15e22a7019b358f3bd248285279aa543c16/tutorial/console.png -------------------------------------------------------------------------------- /tutorial/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | Reactive Turtle 4 | 5 | 6 |
7 |

Introduction

8 | 9 |

10 | This template sets up a sandbox project so the kids can learn Functional Programming while they play drawing with the turtle. 11 |

12 |

13 | With the created project you will be able to: 14 |

15 | 23 |

24 | Note: This tutorial explains how to work with the Activator Shell. If you are working with an IDE you can launch all de App objects with your IDE's mechanism. 25 |

26 | 27 |
28 |
29 |

Start the Turtle Graphics (TG) Window

30 | 31 |

32 | The first you need to do in order to use Reactive Turtle is to start the TG, it will open a window with the canvas and will start listening for remote Commands. You do it by launching the Activator Shell and executing the task tg-start. It will run in a background JVM and will return back the Activator Shell prompt. Optionaly you can specify width and height args. They are 600 600 by default. 33 |

34 | 35 |

 36 | activator
 37 | [info] Set current project to reactive-turtle
 38 | > tg-start 500 500
 39 |   
40 | 41 |

42 | You can terminate it, closing the window or executing the task tg-stop in the Activator Shell. 43 |

44 | 45 |

 46 | > tg-stop
 47 |   
48 | 49 | 50 |
51 |
52 |

Scripting with the Turtle

53 |

54 | We have the turtle, now we want to tell it some movements. The fastest way to start commanding the turtle is by launching the Scala REPL. You can do it right in the Activator Shell session you have open for the TG window. Execute the console task, it will start with all the needed imports already evaluated.
55 | You have many ways to send Commands to the turtle, the easiest ones are the synchronous. When you'r done with the console, type :q for going back to Activator Shell prompt. 56 |

57 |

 58 | // run var args Commands
 59 | runAndWait(SetXY(100, 400), Clean)
 60 | 
 61 | // run a Seq of Commands
 62 | val commands = Seq.fill(4)(Seq(Forward(300), Right(90))).flatten
 63 | runAllAndWait(commands)
 64 | 
 65 | // run a single Command
 66 | PenUp.rnw
 67 | Home.rnw
 68 |   
69 |

70 | You can take a look at TurtleRC trait for available methods and Commands object for available commands. 71 |

72 | 73 |
74 |
75 |

Functional Programming in Scala with the Turtle

76 |

77 | I'm using the Turtle Graphics implemented by BFOIT which is done in Java, obviously in imperative programming, so all the turtle methods have side-effects. But thanks to a piece of advice from the excelent book Functional Programming in Scala writen by @pchiusano and @runarorama I've separated the program's logic from the movements that actually has to do the turtle at the end of the program. 78 |

79 |

80 | You will be able to define the Seq[Command] composing all the pure functions you want. For writting your Turtle Scala Program you have to extend the ScalaApp trait and implement the def commands: Seq[Command] method. 81 |

82 |

 83 | package com.github.ktonga.reactiveturtle.example
 84 | 
 85 | import com.github.ktonga.reactiveturtle._
 86 | import Commands._
 87 | 
 88 | object ScalaAppExample extends ScalaApp with Shapes {
 89 | 
 90 |   def commands: Seq[Command] =
 91 |     layout(
 92 |       Seq((200, 200), (400, 200), (300, 400)),
 93 |       Seq(square(50), circle(5), spiral(20))
 94 |     )
 95 | 
 96 | }
 97 | 
 98 | trait Shapes {
 99 | 
100 |   type Shape = Seq[Command]
101 | 
102 |   def square(size: Int): Shape = {
103 |     (1 to 4).flatMap(_ => Seq(Forward(size), Right(90)))
104 |   }
105 | 
106 |   def spiral(size: Int): Shape = {
107 |     (1 to 100).flatMap(a => Seq(Forward(size), Right(110 - a)))
108 |   }
109 | 
110 |   def circle(size: Int): Shape = {
111 |     (1 to 90).flatMap(a => Seq(Forward(size), Right(4)))
112 |   }
113 | 
114 |   def layout(points: Seq[(Int, Int)], shapes: Seq[Shape]): Seq[Command] =
115 |     points.zip(shapes).flatMap {case ((x, y), cmds) => PenUp +: SetXY(x, y) +: PenDown +: cmds}
116 | 
117 | }
118 | 
119 |   
120 |

121 | You can run your programs, or any of the included examples, executing the run task in the Activator Shell session and chosing one from the list. 122 |

123 | 124 |
125 |
126 |

hAkking with the Turtle

127 |

128 | Once your child becomes a Scala expert, you can introduce him/her into the wonderful world of Akka. The TG is represented by an Actor and you'll have to implement your own Actor to interact with the TG, sending Commands and receiving States. The way to do it, is extending the AkkaApp trait, defining the Actor and implementing the def props: Props method which must return a Props of your Actor. The first message the Actor will receive will be a State case class and the sender will be the TG Actor. The program ends when your Actor terminates. 129 |

130 |

131 | package com.github.ktonga.reactiveturtle.example
132 | 
133 | import akka.actor.{PoisonPill, Actor, Props}
134 | import com.github.ktonga.reactiveturtle._
135 | import internal.TurtleGraphicsActor.Execute
136 | import Commands._
137 | 
138 | 
139 | object AkkaAppExample extends AkkaApp {
140 |   override def props: Props = Props[CommandsActor]
141 | }
142 | 
143 | class CommandsActor extends Actor {
144 | 
145 |   val step = 5
146 |   val inclination = 5
147 | 
148 |   val heading2right = 90 + inclination
149 |   val heading2left = 270 - inclination
150 | 
151 |   def receive: Receive = {
152 |     case state @ State(Canvas(w, _), _) =>
153 |       sender ! Execute(Seq(Clean, PenUp, SetXY(0, 0), PenDown, Heading(heading2right)))
154 |       context.become(left2right(w))
155 |   }
156 | 
157 |   val right2left = moving(x => x - step <= 0) {
158 |     sender ! Heading(heading2right)
159 |     context.unbecome()
160 |   }
161 | 
162 |   def left2right(w: Int) = moving(x => x + step >= w) {
163 |     sender ! Heading(heading2left)
164 |     context.become(right2left, discardOld = false)
165 |   }
166 | 
167 |   def moving(stop: Int => Boolean)(next: => Unit): Receive = {
168 |     case State(Canvas(_, h), Turtle(_, y, _, _, _)) if y + 10 >= h =>
169 |       self ! PoisonPill
170 |     case State(_, Turtle(x, _, _, _, _)) if stop(x) =>
171 |       next
172 |     case s =>
173 |       sender ! Forward(step)
174 |   }
175 | }
176 | 
177 |   
178 |

179 | You can run this in the same way as for the Scala example. 180 |

181 | 182 | 183 |
184 | 185 | 186 | 187 | -------------------------------------------------------------------------------- /tutorial/run-akka.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ktonga/reactive-turtle/a0f6f15e22a7019b358f3bd248285279aa543c16/tutorial/run-akka.png -------------------------------------------------------------------------------- /tutorial/run-scala.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ktonga/reactive-turtle/a0f6f15e22a7019b358f3bd248285279aa543c16/tutorial/run-scala.png -------------------------------------------------------------------------------- /tutorial/tg-start.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ktonga/reactive-turtle/a0f6f15e22a7019b358f3bd248285279aa543c16/tutorial/tg-start.png --------------------------------------------------------------------------------