touchdevelop R Nigel Horspool University of Victoria Judith Bishop Arjmand Samuel Nikolai Tillmann Michał Moskal Jonathan de Halleux Manuel Fähndrich

Size: px
Start display at page:

Download "touchdevelop R Nigel Horspool University of Victoria Judith Bishop Arjmand Samuel Nikolai Tillmann Michał Moskal Jonathan de Halleux Manuel Fähndrich"

Transcription

1

2 touchdevelop programming on a phone R Nigel Horspool University of Victoria Judith Bishop Arjmand Samuel Nikolai Tillmann Michał Moskal Jonathan de Halleux Manuel Fähndrich Microsoft Research Version 1 March 2012

3 ii

4 Who the book is for Programming in a new language is relatively easy for a beginner, given a knowledgeable teacher. But how do teachers acquire such knowledge when we face a paradigm shift in programming? Programming on a phone with TouchDevelop is such a paradigm shift, so this very first book is aimed at teaching the teachers. It assumes that readers know how to program, and want to quickly acquire an understanding of the capabilities of the Windows Phone and how they can be accessed through TouchDevelop. Reference is made to other languages, and some of the chapters require an understanding of mathematics and physics to get the most out of the powerful sensors that a phone has. That said, the book is comprehensive in its treatment of the language, and follows a logical structure from simple constructs to more advanced ones. It would also be suitable for students who want to learn the system and need a reference next to them. Chapter 2, on editing, should be particularly helpful for anyone who has not used a phone as a touch device much before. Status of this version This is the first version of the book, and is produced as limited version of 50 copies for the ACM SIGCSE Conference in Raleigh, NC, March, The book is based on the recently released Version 2.6 of TouchDevelop. Future versions of the book are planned. Details are available on touchdevelop.com/book The book is also available at the moment for free download from that site. Additional exercises will become available there too. Comments are very welcome. To contact the TouchDevelop team or the authors, you can Send to touchdevelop@microsoft.com Post on facebook.com/touchdevelop Post on the forum in the app Acknowledgments We would like to thank Microsoft Research Connections who supported this work with a generous financial grant and logistic support. See research.microsoft.com/connections Grant Branson assisted with the preparation of many of the scripts in these notes, and in the entering and publishing of the code. Thanks to Michał Moskal for the cover design. Important websites touchdevelop.com research.microsoft.com/touchdevelop iii

5 The authors Nigel Horspool is a professor of computer science at the University of Victoria. His main focus for research and teaching has been programming languages and compilers. He is the author or co-author of three books, which cover the C language, Unix and the C# language. He is currently the co-editor of the journal Software: Practice and Experience. He has a PhD from the University of Toronto, Canada in Computer Science. Judith Bishop is Director of Computer Science at Microsoft Research, based in Redmond, USA. Her role is to create strong links between Microsoft s research groups and universities globally, through encouraging projects, supporting conferences and engaging directly in research. Her expertise is in programming languages and distributed systems, with a strong practical bias and an interest in compilers and design patterns. She initiated the Software Engineering Innovation Foundation (SEIF) and is currently working on a new way of running programs in browsers (especially F#). She is the author or editor of 17 books on programming languages. She has a PhD from the University of Southampton, UK in Computer Science. Arjmand Samuel is a Senior Research Program Manager at Microsoft Research Connections. Arjmand is responsible for building academic research partnerships related to Mobile Computing and Software Engineering. He has published in a variety of publications on topics of privacy and security in the healthcare domain and social media. He has published several patents and contributed to books on access control models. His recent research interests are in the areas of abuse-prevention and privacy in social media, and, cloud-enhanced mobile computing. Arjmand has a PhD in Information Security from Purdue University. Nikolai Tillmann is a Principal Research Software Design Engineer, Microsoft Research. His main areas of research are program authoring on mobile devices, program analysis, testing, optimization, and verification. He started the TouchDevelop project, which enables end-users to write programs for mobile devices on mobile devices. He leads the Pex project, in which he develops together with Peli de Halleux a framework for runtime verification and automatic test case generation for.net applications based on parameterized unit testing and dynamic symbolic execution. Try out Pex on the web: Nikolai is also involved in the Spur project, tracing a Just-In-Time compiler for.net and JavaScript code. Nikolai has a Dipl. Inf. in Computer Science from TU Berlin, Germany. Michał Moskal is a Researcher in Redmond. He is in the RiSE group working on software verification, automated theorem proving, and programming languages. He works on a formal verifier for concurrent C programs called VCC, while also taking on other projects including Boogie intermediate verification language, SPUR tracing JIT, and DKAL authorization engine. In late 2010, Nikolai Tillmann and Michał started TouchDevelop an effort to create an integrated development environment for writing programs on the phone for the phone. He has a PhD from the University of Wrocław, Poland. iv

6 Jonathan Peli de Halleux. Peli is a Senior Research Software Design Engineer in the Research in Software Engineering group at Microsoft Research in Redmond, USA. He is actively working on TouchDevelop, Moles and Pex, and collaborates with his colleagues from CHESS and Contracts. Peli also wanders around building 99 shooting videos for Channel9 about the RiSE group. Every morning, Peli teaches Web Design at his local high school. From 2004 to 2006, he worked in the Common Language Runtime (CLR) as a Software Design Engineer in Test in charge of the Just In Time compiler. He has a PhD in Applied Mathematics from the Catholic University of Louvain, Belguim. Manuel Fähndrich is a Senior Researcher in the RiSE group at Microsoft Research in Redmond. He works on programming language design, static type systems, program analysis and verification, as well as runtime techniques and optimizations. His past and current project involvments include the Singularity OS and Sing# language, CodeContracts for.net, and TouchDevelop. He has a PhD from the University of California, Berkeley. v

7 vi

8 VERSION 1 WHAT IS TOUCHDEVELOP? CHAPTER 1 WHAT IS TOUCHDEVELOP? In this chapter we present an overview of how TouchDevelop works within your phone and the larger ecosystem the cloud, the communities you are involved in, and the websites you normally access. We conclude with a brief introduction to the Windows Phone WHAT IS TOUCHDEVELOP? 1.2. INSTALLING TOUCHDEVELOP QUICK START 1.3. WHY TOUCHDEVELOP? 1.4. IS TOUCHDEVELOP A PROGRAMMING LANGUAGE? 1.5. THE TOUCHDEVELOP ECOSYSTEM 1.6. AN INTRODUCTION TO THE WINDOWS PHONE 1.7. A QUICK QUIZ 1.1. WHAT IS TOUCHDEVELOP? TouchDevelop is a novel application development environment for anyone to script their smartphones anywhere you do not need a separate PC. TouchDevelop allows you to develop Windows Phone applications that can access your data, your media, your sensors, and allows using cloud services including storage, computing, and social networks. TouchDevelop targets students, hobbyists, power users, and developers. TouchDevelop applications are written for fun, for personalizing the phone, and for creating productivity tools. TouchDevelop brings the excitement of the first programmable personal computers to the now ubiquitous mobile devices. Scripts developed using TouchDevelop allow users to engage with personal interests and possessions, by showing and manipulating music and pictures stored on their own mobile device, the sensors of the phone, and the friends in their social networks. 1

9 WHAT IS TOUCHDEVELOP? VERSION 1 TouchDevelop programs are not large (typically less than 100 lines of code), and evolve over time with other users adding to shared scripts. Figure 1.1 (a) below shows a screen shot of TouchDevelop application in the Windows Phone. Figure 1.1(b) shows script listing of a simple program, and (c) depicts execution of a script within the TouchDevelop application. Figure 1.1: Screen shots of (a) TouchDevelop application for Windows Phone (b) code listing of a TouchDevelop program; (c) execution of a script. TouchDevelop can be used to develop games such as missile defense, which is a full featured game where you defend cities against incoming missiles ( Script for this sample game can be downloaded to TouchDevelop application installed on a Windows Phone, and executed or tailored. An example of TouchDevelop scripts being used for productivity is the meet now script, which finds the active online meetings for you and joins it through the Microsoft Lync application installed on your Windows Phone ( You can find numerous TouchDevelop samples on the TouchDevelop site ( This site also hosts scripts shared by other users to learn from, or to adapt INSTALLING TOUCHDEVELOP QUICK START If you are about to use TouchDevelop for the first time on your Windows phone, you will first need to install it. There are two easy ways to proceed, you can use either one. 2

10 VERSION 1 WHAT IS TOUCHDEVELOP? Touch the Marketplace tile on the Windows phone, then press the search icon at the bottom of the screen, and type the text touchdevelop into the MARKETPLACE SEARCH menu page which comes us. Before you finish typing all the letters, the TouchDevelop app should appear as a choice on the screen. Touch that choice, and then touch INSTALL. Touch the BING search button at the bottom right of your phone, and type the text touchdevelop into the Bing search window, then touch the right arrow key at the bottom right of the keyboard to cause bing to perform its search. The first hit which comes back from Bing should be TouchDevelop at the URL Touch that selection. The webpage which is displayed has a download button in the top right-hand corner, which you should touch. It looks like the picture below WHY TOUCHDEVELOP? We are in the midst of a revolution in computing technology. In 2011, more touchscreen-based mobile devices like smartphones and tablets were sold than desk-tops, laptops, and netbooks combined. In fact, in many cases incredibly powerful and easy-to-use smart phones are going to be the first, and possibly, the only computing device many of us will own. In addition to touch screens, smart phones are also equipped with sensors such as camera, accelerometers, Global Positioning Systems (GPS), and light detectors, to name a few. Furthermore, we carry smart phones wherever we go, and constantly interact with these devices, making our daily lives more productive and interesting. However, professionally developed mobile apps available on most smart phones through the respective AppStore and Marketplaces restrict end-users to developer defined interactions and scenarios. While these interactions may be useful and interesting to the application developer, these may not be most interesting and useful for all users. TouchDevelop allows any phone user to create customized scripts, easily and in much less time compared to traditional app development models, allowing all end users to address their unique needs. With TouchDevelop, the user does not need to own a personal computer, nor does the user require knowledge into deep programming constructs. Since all development takes place on the smart phone, without the need for a personal computer, a user may program, anywhere and anytime. Finally, TouchDevelop scripts can be shared with other users using the TouchDevelop Script Bazaar IS TOUCHDEVELOP A PROGRAMMING LANGUAGE? TouchDevelop is a language for writing scripts using the TouchDevelop Windows Phone application. This application is also a runtime environment for executing TouchDevelop scripts. The TouchDevelop language is a typed, structured programming language built around the idea of only using a touchscreen as the input device to author code. It has built-in primitives which makes 3

11 WHAT IS TOUCHDEVELOP? VERSION 1 it easy to access the rich sensor data available on a mobile device. The TouchDevelop language mixes imperative, object-oriented, and functional features. The imperative parts are most visible: users can update local variables, and state of global objects. Object-orientation is dictated by auto completion requirements - properties of objects are an easily accessible and intuitive concept. However, for the sake of simplicity, the language itself does not have built-in constructs which would allow users to define new types or properties. A TouchDevelop script consists of a number of actions (procedures) and the global state (global variables). The TouchDevelop script editor is part of the TouchDevelop Windows Phone application designed for efficient entry of scripts using only the touch screen. Further details can be found in Chapter 2. TouchDevelop scripts execute within the TouchDevelop application on Windows Phone. This execution is reactive - actions are run in response to events. Events can be raised by user input (e.g., interacting with a UI element, changing the orientation of the phone, or shaking it), events from the phone (e.g., change of active song in the song player) or passage of time. TouchDevelop uses cooperative multi-threading. Actions and events are executed single-threaded 1.5. THE TOUCHDEVELOP ECOSYSTEM TouchDevelop scripts developed using the TouchDevelop Windows application can be shared with other users using TouchDevelop cloud infrastructure (TouchDevelop.com). Figure 1.2 depicts a high level architectural overview of the TouchDevelop ecosystem. Figure 1.2: TouchDevelop ecosystem, including the community of developers using the Windows Phone, website and cloud infrastructure. 4

12 VERSION 1 WHAT IS TOUCHDEVELOP? TouchDevelop scripts are developed by users on their Windows Phones and executed within the TouchDevelop run time environment on the phone. These scripts can be shared with other users. The TouchDevelop cloud infrastructure allows this sharing amongst a community of TouchDevelop users. These scripts can also be searched, viewed, and installed into a user s account using the TouchDevelop website. The cloud infrastructure enables sharing, and, acts as a repository of all scripts developed and published by users. In order to publish scripts developed on the Windows Phone, you will have to sign-in and accept the current TouchDevelop Cloud Services Agreement; please also read the TouchDevelop Privacy Statement. Detailed steps are available in Chapter 2. Once your script is published to the TouchDevelop cloud infrastructure, other TouchDevelop users can view your script in the new section of the website or the app (Figure 1.3). Users can also see author s username used to publish the script from the Windows Phone. Scripts in this list are sorted by the time of publication, with most recently posted scripts on the top. Figure 1.3: Listing of TouchDevelop scripts on touchdevelop.com in three pre-defined orders. The TouchDevelop website allocates a stable unique web address relative to touchdevelop.com for your script which can be used to navigate to the script directly. You can share this link with other people. Following this link leads to a webpage dedicated to the script. This webpage provides further statistics for the script such as the number of users who have installed your script on their phone and the number of runs. This page also lists usernames of TouchDevelop users who have reviewed your script as well as detailed comments. Figure 1.4: TouchDevelop website page for each script 5

13 WHAT IS TOUCHDEVELOP? VERSION 1 Once users like your script, they can review it by giving hearts. The webpage shows the number of user reviews (hearts) given to each script by other users. The website also shows the number of discussion posts on your script started by other users. See Figure 1.4. Users cannot review your scripts or give comments related to your scripts on the TouchDevelop website. These two activities are possible on the phone within the Windows Phone TouchDevelop application. Once a user navigates to your script on the phone, by either searching for it, or finding it in the new, top, or featured lists, a user has the option to either review (by clicking the heart), or provide comments. Figure 1.5: Searching, installing, reviewing and commenting on scripts using the TouchDevelop application on the Windows Phone. The selected script can be installed and executed locally by tapping on the down-pointing arrow at the bottom of the screen. The script page (on the touchdevelop.com website and in the app) may show a previously published script on which the current script is based on. TouchDevelop keeps track of the base scripts when you are editing it. Similarly, this page (on the website and in the app) also displays details for other scripts which are based on the current one. In the following chapters you will learn more about writing TouchDevelop scripts on the Windows Phone. 6

14 VERSION 1 WHAT IS TOUCHDEVELOP? Figure 1.6: Forward and backward relationship between current script and other scripts as displayed for all scripts on the script webpage AN INTRODUCTION TO THE WINDOWS PHONE TouchDevelop is a Windows Phone application and can be installed and executed on the Windows Phone versions 7.5, or later. For a quick introduction to the Windows Phone visit the Windows Phone website ( Figure 1.7: Pivot control allowing navigation to multiple screens using the drag gesture.* * 7

15 WHAT IS TOUCHDEVELOP? VERSION 1 Like all smart phones today, Windows Phone supports touch interface allowing TAP (a finger touches the screen and releases), and DRAG (A finger touches the screen and moves in any direction). In addition to these basic gestures, allowing easy navigation, Windows Phone also supports a host of additional gestures. Read the details on MSDN ( All applications on the Windows Phone allow navigation to multiple screens, made possible by using the concept of a PIVOT (see Figure 1.7). Swiping sideways or tapping a different pivot point (for example tapping the word installed in Figure 1.7) changes the pivot point and causes different information to be displayed on the screen A QUICK QUIZ Take this quick quiz to see if you understand the concepts discussed in this chapter. i 1. TouchDevelop s language is a) JavaScript for the phone b) A brand new language especially designed for touchscreen phone use c) A simplified language suitable for teaching, but not for real applications d) Purely object-oriented 2. To use TouchDevelop, you only need a) A Windows phone b) Any mobile phone c) A phone and a computer d) Just a computer 3. TouchDevelop is a) A simple system that does not yet access the phone s sensors or media content b) Fully able to access all media content and sensors of the phone, and the internet c) Only able to access media content on the phone such as songs and pictures d) Not able to access the internet yet 4. Typically, new users can write their first TouchDevelop script using sensors in a) A day b) Half a day c) After a week d) An hour and a half 5. Scripts in TouchDevelop can be shared by 8

16 VERSION 1 WHAT IS TOUCHDEVELOP? a) ing them b) Publishing them on the Marketplace c) Saving them on to a computer d) Publishing them on the Bazaar 6. To use the TouchDevelop Bazaar, you need a) A Windows Live ID b) A Windows Live or FaceBook Account c) An AppHub Developer account d) None of the above 7. Scripts in the Script Bazaar can be viewed a) Only on the phone through TouchDevelop b) Only on a browser c) On the phone through TouchDevelop and through a browser d) On TouchDevelop, a browser, and print outs 8. Reviewing and giving comments to scripts is possible a) Only on the phone through TouchDevelop b) Only on a browser c) On the phone through TouchDevelop and through a browser d) Only on Facebook 9. A code such as /aoxd is a a) Part of a stable web address in the Bazaar for a script b) Not relevant for most programmers, and can be ignored c) A checksum for the script to ensure that it is not corrupt on downloading d) A conversion code needed to get a script from the Bazaar to the Marketplace. 10. TouchDevelop is a project from a) Microsoft Windows division b) Researchers and engineers at Microsoft Research c) Academics with a grant from Microsoft Research d) All of the above 9

17 WHAT IS TOUCHDEVELOP? VERSION 1 i Answers: 1. b) 2. a) 3. b) 4. d) 5. d) 6. b) 7. c) 10

18 VERSION 1 WHAT IS TOUCHDEVELOP? 8. a) 9. a) 10. b) 11

19 VERSION 1 EDITING IN TOUCHDEVELOP CHAPTER 2 EDITING IN TOUCHDEVELOP In this chapter we describe how to set up TouchDevelop on your phone, how to enter scripts from scratch, and how to extend existing scripts. At the end of the chapter, you should be familiar with the tiles and buttons that TouchDevelop uses on the phone, and the ones it provides to make programming feasible, and in fact really easy and quick. You will also be shown how to publish your script in the TouchDevelop Bazaar. 2.1 THE TOUCHDEVELOP SCRIPT EDITOR 2.2 CREATING A SCRIPT 2.3 EXAMPLE: DRAWING RANDOM CIRCLES 2.4 MODIFYING A SCRIPT 2.5 MORE EDITING ACTIONS 2.6 USING THE TOUCHDEVELOP BAZAAR 2.7 CAUTION! PROTECTING YOUR INFORMATION 2.8 EXERCISES 2.1 THE TOUCHDEVELOP SCRIPT EDITOR TouchDevelop includes an editor for creating its scripts. It has been optimized for use with a small touch-sensitive screen as found on a phone. It works by presenting you with only a small number of choices at a time. At every stage, only relevant choices are presented to the user. If there are too many choices to fit on the screen, the most frequently used choices will appear on the first screen and then there will be more choices on a second screen, and so on. The editor takes a little bit of getting used to. For that reason, it is suggested that you try to follow the sequence of steps shown below for entering a new script named add n numbers. However, before you do that, let s introduce one piece of terminology. The phone has an arrow button at the bottom left, below the screen. We will call that the phone back button; it will be used a lot when entering scripts. Remember this button is not on the screen itself! Do not confuse it with any other left arrow buttons which may be displayed on the screen. 11

20 EDITING IN TOUCHDEVELOP VERSION 1 phone back button home button bing button The editor actions given in the examples below provide just one way of entering the script. There are many alternative paths for getting to the same end result, and you should play around with the editor to find what works best for you. MISTAKES! If you make a mistake when entering a script, do not worry. There is an UNDO button on every edit menu. Failing that, the PHONE BACK BUTTON will always return you to the previous screen where you can delete an unwanted line of code and try again. The first script we have chosen is the familiar one to add n numbers and the second one is to draw some random circles on the screen. Entering these programs will use several of the different editor actions that you will need later on, so that you can refer back to these steps later when you are entering other scripts. Because the TouchDevelop editor anticipates the possible options that follow on from any given command, and gives you a choice of the next items, you end up actually typing in less than half of the keystrokes that you would for a traditional program on a computer, laptop or tablet. This is the beauty of TouchDevelop, and one we hope you will appreciate as your experience grows. While reading this material, it might also be useful to watch the Channel 9 video of entering a program, which can be found on: CREATING A SCRIPT Our first example is a sequence of steps which cause a simple program to be entered as a TouchDevelop script. The program has the following structure: set the variable SUM to zero; for each of the numbers from 1 to N: add the number to SUM display the final value of SUM It simply sums the integers. If we run such a program with N equal to 5, the answer displayed on the screen would be 15 because sums to

21 VERSION 1 EDITING IN TOUCHDEVELOP START A NEW SCRIPT 1. Start TouchDevelop. (On the home screen, tap the right-pointing arrow at the top right and scroll down to TouchDevelop in the list of apps, and select it.) 2. Tap the plus button at the bottom of the screen it means you want to add a new TouchDevelop script. 3. Enter the title for the program which, for this example, is add n numbers in the pop up text box. Then tap the CREATE box. The screen now contains the following: START THE MAIN ACTION 4. Tap the word main in the list of actions. Do not tap the right-pointing arrow in the green square because that causes the script to be played and, at the moment, it does not do very much. You should now be looking at the code for an action named main. This is a default line of code which displays Touchdevelop is cool! if you play the script. Note that in the code, you will see that the full text of the string constant "TouchDevelop is cool!" is not shown on the screen. That s because the screen is too narrow to display it all. It is shortened to "TouchDevelop is ". If you were to later modify that scree, you will find that all the characters of the string constant are actually there. We choose to leave this line of code in the script for now and delete it only after we have finished adding our own statements to the script. ADD A NEW PARAMETER TO AN ACTION If the main action has a parameter, the user will be prompted to enter a value for that parameter whenever the script is run. We are now going to add that parameter and give a reasonably meaningful name to that parameter. (We ll choose n, because it is short.) 5. Tap the top line of the code for the main action this is the SIGNATURE LINE (the line which begins with the keyword action). The screen display should change to look like the following: 13

22 EDITING IN TOUCHDEVELOP VERSION 1 6. Now tap the button labeled edit and the screen should display a list of ACTION PROPERTIES for the main action, looking like this. 7. Tap the params tab. This selects params as the pivot point for the display. 8. Tap the plus button at the bottom of the screen, and a new parameter named x1 with type Number is added to the action. The name and the type are both supplied as defaults and both can be subsequently changed. We will change only the name. 9. Tap the name x1 and enter a new name n into the textbox. Tap the phone back button to exit the keyboard mode. 10. Tap the phone back button again to return to the screen showing the code for the main action. INSERT AN ASSIGNMENT To enter an assignment, we can first choose the assignment operator, then enter the right hand side expression. A new variable for the left hand side is generated automatically. We will change the name of that variable afterwards. 11. Tap anywhere on the line of code which says "TouchDevelop is"... post to wall and then tap the edit button. A bar colored with your theme accent color should appear to the immediate left of this line. 14

23 VERSION 1 EDITING IN TOUCHDEVELOP 12. Tap the plus button in the LOWER ROW to add a line below the current line, and then tap the expression button. (The plus button in the upper row is for inserting a new line above the current line.) An edit menu for constructing an expression is now displayed. 13. Tap the button with the label (the NUMBERS button). 14. The menu changes to show characters needed for entering a number. Select the 0 button, and now an assignment statement of the form x0 := 0 has been created. (If we keep tapping digits or the decimal point, the number on the right-hand side changes.) 15. Tap in the fix-it bar on the screen to accept the new expression as being the right-hand side of an assignment to a new variable (whose name has now defaulted to x). 16. We choose not to retain the default name for the left-hand side. So tap the phone back button to return to the edit-expressions menu where there is a button labeled RENAME. We tap the button and the name x appears and is highlighted in red. 17. We set the new name sum by tapping letters on the keyboard. 18. To see the modified line of code, tap the phone back button. INSERT A FOR STATEMENT 19. Tap in the black space below that line of code again and the edit menu changes. There are only two possible choices, both for adding a new statement to the main action. Tap the choice labeled if/foreach.... It s called the add flow button. 15

24 EDITING IN TOUCHDEVELOP VERSION The edit menu and its placement changes. There is a thick red line below the assignment statement to indicate where we are about to insert a new line of code. Tap the button labeled for and the first line of a for loop is inserted. Although you cannot see it yet, the loop index variable has been given a default name of i. The cursor position indicates that the editor expects us to enter the upper bound for the loop index next. ENTER A SIMPLE EXPRESSION We are going to enter the expression n+1 as the loop s upper bound in three steps. (It is n+1 because the loop only repeats while i has a smaller value, so the last iteration occurs with i equal to n.) 21. Find a button labeled n in the edit menu and tap it. The button represents the parameter n which we added to the main action back in steps 6 to 8. If n isn t on the first screen of choices, tap the right arrow, NEXT SUGGESTIONS, to see a second set of choices. 22. Tap the button labeled with the operators + - * /..., and then select Tap the numbers button and select 1. ADD A LINE TO THE LOOP BODY We are going to provide the statement sum := sum+i as the body of the loop. 24. Tap between the line of code and the number entry pad, in the blank area, and two edit choices appear below. Select the add expression button which is labeled with a big In the edit menu, select the sum button. 26. Select the named operators button labeled and, or not, wall,..., and then select the := button. 27. The cursor position indicates that we should enter the right-hand side of the assignment next. We will construct sum+i as that expression in three steps. This is very similar to entering the n+1 expression above. (I.e., Select the sum button. Select the operators + - * /... and choose +. Finally, select the i button.) 16

25 VERSION 1 EDITING IN TOUCHDEVELOP ADD A LINE AFTER ANOTHER ONE We now want to add a final statement to the script, one which displays the final value of the variable sum. 28. Tap the phone back button below the screen. This causes all the code for the main action, as entered so far, to be displayed. 29. Tap anywhere on the line which begins with the word for. It causes the entire loop to be selected for editing. 30. Tap the + button below the loop (it reads ADD BELOW as its name), and then select the expression button. CONSTRUCT A STRING EXPRESSION FROM SEVERAL PIECES 31. Select the operators button labeled + - * /... and then choose the left parenthesis (. This causes a parenthesis pair ( ) to be inserted with the blinking cursor in between. 32. Now tap the button named STRINGS, ART and labeled... pic snd color, and select the STRING button labeled "abc". Enter the text The sum of the first (but without the quote characters these are supplied automatically). 33. Tap the phone back button. 34. Tap the named operators button and select the operator (string concatenate). 35. Tap the "n" button. 36. Tap the named operators button and, or not, wall. 37. Tap the button (string concatenate). 38. Tap the strings, art button. 39. Tap the string button and enter the text numbers is. 40. Tap the phone back button. 41. Tap the named operators button and then the button (string concatenate). 42. Tap the sum button. At this point, the entire string expression should read ("The sum of the first " n " numbers is " sum) ADD A POST-TO-WALL CALL TO THE STRING 43. Tap the right-hand move cursor button (the RIGHT pointing arrow) to get the cursor to the desired position which is just to the right of the right parenthesis. 44. Tap the post to wall button. 45. Tap the phone back button to see all the code for the main action at this point. 17

26 EDITING IN TOUCHDEVELOP VERSION 1 CUT A STATEMENT (AND PASTE THE STATEMENT ELSEWHERE) The main action still contains the default first line which displays the message TouchDevelop is awesome when the script is played. Let s cut that line and, just for demonstration purposes, we will paste that line back in at the end of the main action. 46. Tap anywhere on the line we want to move or delete. This causes editing options to appear on the screen, surrounding the line to be edited. The line is highlighted with a red bar to its immediate left. 47. Tap the cut button and the line of code is deleted. However, it has not been lost, it has been temporarily remembered by TouchDevelop. 48. If we want to paste the line of code back into the script at the end of the main action, tap the + button at the bottom of the screen. This causes the expression editor pad to be displayed. 49. Keep tapping the next suggestions button until you see a key named paste. Tap the paste button. 50. Tap the phone back button to see the new code for the main action. Your script is now complete. The code after step 50 above should look like that shown in Figure2.1. Figure 2.1: The Final Program action main(n) var sum := 0 for 0 i < n + 1 do sum := sum + i ("The sum of the "... n " numbers is " sum) post to wall "TouchDevelop is"... post to wall PLAY THE SCRIPT You should test the script to make sure that it runs. 51. Look for the right pointing arrow at the bottom of the screen. That s the RUN BUTTON. Tap the run button. If it works, you should be prompted to enter a value for n and then the script should respond by displaying the sum of the integers from 0 to n. A sample run of the program is shown in Figure

27 VERSION 1 EDITING IN TOUCHDEVELOP Figure 2.2: A Successful Run of the Script Congratulations! You've just successfully implemented and run your first program! 2.3 EXAMPLE: DRAWING RANDOM CIRCLES If you completed the exercise of entering the script detailed in Section 2.3 and are ready for another one, here is an example of a script which uses some of the graphics drawing functions. It will display 20 randomly sized circles in randomly chosen colors. This time, the instructions for entering the script will not be given in such detail. (Please refer back to the previous example if you forget how to complete some editing action.) START A NEW SCRIPT 1. Begin a new script and name it draw random circles. ADD A NEW ACTION 2. On the main page for the script, tap the + button which appears to the far right of the word actions. A new action with the default name go will be created and displayed. 3. Tap the line which reads action go() and then select edit in the edit menu which appears. 4. Select the word go and enter the new name draw circle for this action. 5. Click the box labeled private. ADD PARAMETERS FOR THE NEW ACTION 6. Tap the word params at the top of the screen, and tap the + button at the bottom. 7. Rename the first parameter to have the name pic. (Tap in the blank area between the parameter and the keyboard to exit from keyboard entry mode.) 8. Tap the type of the first parameter in the text box (i.e. tap the word Number ). This causes the screen to display a list of possible types for the parameter. Scroll down and select Picture from this list. 19

28 EDITING IN TOUCHDEVELOP VERSION 1 9. Tap the + button to add a second parameter. Rename the parameter to x and leave its type as Number 10. Tap the + button to add a third parameter. Rename the parameter to y and leave its type as Number. 11. Tap the + button to add a fourth parameter. Rename the parameter to radius and leave its type as Number. 12. Tap the + button to add a fifth parameter. Rename the parameter to color and change its type to be Color. The resulting screen should be as shown in Figure 2.3. Figure 2.3: The Five Parameters of draw circle 13. Tap the phone back button. We are now ready to enter the code for the body of the draw circle action. When we have finished entering that code, the code should display on the screen as shown in Figure2.4. Important note: this particular way of drawing a circle as a series of dots is not recommended. There is a much more efficient method draw ellipse defined for the Picture type; it draws ellipses, which includes drawing circles, and should be used instead. Figure 2.4: Code for the draw circle Action action draw circle(pic, x, y, radius, color) for 0 i < 2 * math * radius do // the circle centre is at (x.y) // each dot is at (x+xofs, yofs) var xofs := radius * math cos(i / radius) var yofs := radius * math sin(i / radius) pic set pixel(x + xofs, y + yofs, color) do nothing 20

29 VERSION 1 EDITING IN TOUCHDEVELOP ADD A STATEMENT TO THE BODY OF THE DRAW CIRCLE ACTION 14. Tap anywhere in the current body which is simply a comment reading do nothing. This brings up the edit menu. 15. Tap the add below button and then select the for button. 16. Insert the expression 2*math as the upper bound of the for loop. (Do this by entering the number 2, then the operator *, then the global name math, then the symbol.) ADD A STATEMENT TO THE BODY OF THE FOR LOOP 17. Tap the blank area below the code. Now the editor actions are a choice of only two: add expression and add flow. Select add expression (indicated by the + button). 18. Construct the assignment statement for the first statement in the loop body refer to Figure 2.4. (It can be done by entering the right-hand side of the assignment and then tapping the FIX IT button.) ADD MORE STATEMENTS TO THE BODY OF THE FOR LOOP 19. With the cursor to the right of the statement just entered (use the right-arrow button on the edit pad), tap the area below the statement, then tap the add expression button. 20. Now construct the assignment statement for the second statement in the loop body. 21. Similarly construct the expression statement for the third and last statement in the body of the for loop. At this point, the code displayed on the screen should look like that in Figure2.4 only without the comments. What does this action do? It adds dots to a picture at regularly space intervals around the circumference of a circle whose center is at coordinates (x,y) and whose radius is as specified. Each dot is drawn by changing the color of a pixel to the color specified by the fifth parameter. (Optional: you can delete the do nothing comment line.) INSERT COMMENTS If we intend to let others see our script, it would be a good idea to add some helpful comments. It is easy to insert comments. Here is how we can add the comments shown in Figure Tap anywhere on the line which reads var xofs := This brings up the menu for editing a statement. 23..We want to add the comments above the selected line, so tap the + add above button. 24. Tap the button labeled // insert a comment 25. Enter the comment into the textbox which opens up. 26. Tap the phone back button when the comment is complete. 21

30 EDITING IN TOUCHDEVELOP VERSION 1 CHANGE THE MAIN ACTION 27. Tap the phone back button to return to the main screen for our draw circles script. Tap the action name main 28. Tap the settings button (the one which looks like a gear wheel) and then rename the action to Random circles. Tap the phone back button to return to the code listing for this action. 29. Now replace the default action body with the code shown in Figure2.5. At this point, you should not need the step-by-step instructions. Figure 2.5: Code for the Random circles Action action random circles() var pic := media create picture(400, 400) for 0 i < 20 do draw circle(pic, math random(400), math random(400), 5 + math random(95), colors random) pic post to wall What does this code for this action do? It first creates a blank picture which measures 400 pixels by 400 pixels. Then the for loop iterates 20 times and on each iteration, it invokes the draw circle action to draw a new random circle on the picture. The center of the circle is placed at a random position in the picture, the radius of the circle is chosen to be a random number of pixels in the range 5 to 49, and the color of each circle is randomly selected. Finally, the picture which contains the 20 random circles is displayed on the screen. PLAY THE SCRIPT 30. Finally, play the script by tapping the RUN button at the bottom of the editor window. 2.4 MODIFYING A SCRIPT Let us suppose that after entering the draw random circles script and running it, you are somewhat dissatisfied. The circles drawn with single pixels spaced around each circumference are barely visible on your screen. You want to modify the script so that each circle is filled with color, it s not an empty circle with a thin line around the outside. If we check the documentation for the TouchDevelop API documentation on the web or if we tap the pic variable in our draw circles action and see which methods the editor will allow us to invoke for a variable of type Picture, we see that there are functions for generating both hollow and solid ellipses. A circle is simply a special case of an ellipse. This will make the code much simpler and faster than the loop which displays individual pixels. 22

31 VERSION 1 EDITING IN TOUCHDEVELOP The fill ellipse function is documented as having these parameters: fill ellipse(left : Number, top : Number, width : Number, height : Number, angle : Number, color : Color) The first two parameters (left and top) control where the ellipse is drawn; the next two parameters (width and height) determine the dimensions of the ellipse but we will have width equal to height for a circle; the fifth parameter (angle) allows us to rotate the ellipse by some angle before it is drawn but this parameter is irrelevant when we draw circles; the last parameter specifies the color to fill the ellipse shape with. Having understood all that, we should replace the code for the draw circle action in our previous script with the new version shown in Figure 2.6. So let s begin. Figure 2.6: Replacement Code for draw circle action draw circle(pic, x, y, radius, color) var left := x-radius var top := y+radius var diameter := 2*radius pic fill ellipse(left, top, diameter, diameter, 0, color) OBTAIN THE SCRIPT 1. In the start screen of TouchDevelop, swipe right-to-left to show the list of installed scripts. 2. Select the script with the correct name from the list it should be at the top. Tapping it should cause the two actions of this script to be listed. MODIFY THE DRAW CIRCLE ACTION 3. Tap the name draw circle in the list of actions. The code for this action will be displayed. 4. Tap anywhere in the first line of code for the for loop. This will cause an edit window to appear, surrounding the whole for loop. 5. Tap the cut button and the for loop which is the entire action body is deleted and replaced with a do nothing comment. 6. Tap the do nothing comment and replace it with the first statement shown in Figure Now add each of the other statements one at a time. When you get to the fill ellipse function, the editor will supply default values for each of the parameters. You should select each parameter, one at a time, delete the parameter and then insert the desired parameter value. Running the modified script leads to a much more pleasing rendering of random circles. It should like something like that shown in Figure

32 EDITING IN TOUCHDEVELOP VERSION 1 Figure 2.7: Output of the Revised draw random circles Script 2.5 MORE EDITING ACTIONS ADDITIONAL EDITING FEATURES This chapter has not covered all the ways in which the editor can be used to enter statements, insert references to data variables, move statements from one place to another, and so on. It is a powerful editor which you can only become comfortable with using by practice and by experimentation. Amongst the features which we have not been covered in this chapter, we might mention these: Refactoring a group of one or more statements to become a separate action. This is covered in Chapter 7. Refactoring an expression or subexpression to become a new local variable. This too is covered in Chapter 7. Inserting a use of a global data variable into a statement, or insert a use of a local variable which does not appear as a button in the expression editor. Here, the answer is to find the button labeled EXPLORE ALL, as in the bottom row of this screenshot: 24

33 VERSION 1 EDITING IN TOUCHDEVELOP Tapping that button will expose a list of all the services provided in the TouchDevelop API. Also in the list, one can find a code and a data item, amongst others. Tapping on those will yields lists of all the actions and all the global data items the included so far in the script. Swiping from left to right will also change the pivot and yield other lists, including a list of all the local variables declared so far in the current script. RECOVERY FROM ERRORS Oops! I tapped the wrong button and now my code is messed up. How can we go back and try again? Sometimes it s easy to guess how to recover and sometimes you may have to play around until you have found a sequence of steps which work. As you gain familiarity with the editor, the less hard you will find it to recover. Table 2.1 lists some of the standard ways to undo a mistake. Table 2.1: Recovering from Errors in the Editor Button Effect Undo button If an editor pad with an undo button is being displayed (and the button is not grayed out), you are in luck. Tapping that button will undo the last editing operation you performed. 25

34 EDITING IN TOUCHDEVELOP VERSION 1 phone back button This is probably for use only as a last resort. Touching the phone back button will take you back up one level in the editor where you should be able to see all the code for the current action or event. You can look at that code and touch any line which needs to be deleted or modified. You can, alternatively, insert missing statements above or below the line you touch. delete button If an expression or statement contains an incorrect item, you can touch that item to select it and then touch the delete button in the expression editor menu to delete it, then carry on using the expression editor to insert the item(s) you really wanted to appear in that position. You can also use the cursor left and right buttons to position the cursor to the right of an incorrect item and then touch the delete button. trash can If you have added a parameter or a result parameter to an action or event which you do not want, you can select the properties of the action or event, then display the params or result listing, and then touch the parameter which is unwanted. There should be a trash can icon displayed at the bottom of the screen; touching that will remove the parameter. Touching any undesired item in a line should cause the expression editor menu to be displayed. You can often just enter a new item with the editor which will replace or modify the item you touched. If you entered an incorrect string or number value, you can touch the editor buttons for entering a string or number and you will be able to edit the value which had been erroneously entered. 2.6 USING THE TOUCHDEVELOP BAZAAR As discussed in Chapter 1, the Bazaar is a place where you can save and share your scripts so others can see them, use them, and adapt them. PUBLISHING A SCRIPT IN THE BAZAAR Here s how to publish your script to the cloud and let others use and view your brilliant script: Touch the phone back button, as needed, until you re on the main page for the script. Touch the publish button on the bottom (the one with an upward pointing arrow). Touch the publish box. 26

35 VERSION 1 EDITING IN TOUCHDEVELOP Log in, if necessary, with your Windows Live Id or Facebook credentials and... you re published! Once your script is published, run your script again and publish a screenshot by clicking on the take screenshot menu item in the script execution page. DOWNLOADING AND MODIFYING AN EXISTING SCRIPT The bazaar is full of useful scripts. You can access these scripts via TouchDevelop on your phone or with your web browser on a computer. When you start up TouchDevelop or when you visit the webpage the welcome screen shows a series of screenshots produced by some sample programs, plus there are lists of scripts provided under the headings new top and featured. Touching (or clicking if using a browser) one of these headings will display a list of TouchDevelop scripts in that category, with a show more link at the bottom if you wish to keep exploring. Each script has a title which is usually somewhat descriptive of what the script does. Selecting that title causes a lot more information about the script to be displayed. If you are viewing on a web browser, you can see the code for the script by scrolling down. Reading other people s code is a probably a good way to learn how to use features of the TouchDevelop API. However, there is no guarantee that it is good code! To get a sense of the code quality and the general usefulness of the script, take a look at the heart symbol and the number alongside. It s displayed on the webpage like this and almost identically on the phone. What we see is that the script was published 3 months ago and that since it was published, 17 TouchDevelop users have indicated that they like the script. This is a reasonably good endorsement. Tapping the name of the script displays some details of the script. Some scripts in the listings will say that they are based on another script. This is the normal way to create a TouchDevelop script. You search for an existing script which does at least some of the things you want your script to do, and then you edit it. This reduces the amount of work you have to do yourself! 27

36 EDITING IN TOUCHDEVELOP VERSION 1 DOWNLOADING A SCRIPT TO YOUR PHONE If you have identified a script you like amongst those displayed by TouchDevelop on the phone, you can touch the square icon for the script which appears on the left. Here is one such icon, reproduced on the right. Touching it will cause your phone to connect to the cloud and download it (possibly asking you to sign in first). Alternatively, if you are using a web browser to look through the scripts or if you want to download the script later, make a note of the 4 or 5 letter codename for the script. For example, you may see the notation /fpkj appear alongside the script. You should note that codename and then, later, when you have started TouchDevelop on your phone, you can touch the magnifying glass icon on the TouchDevelop screen (NOT the similar looking one on the phone s frame) to open a search window. Entering the letters fpkj into the search window and touching the even smaller magnifying glass at the right end of the search window will cause the script to be located and downloaded to your phone. After downloading has finished, the script.will run automatically. If you do not want to continue with that execution, tap the phone back button to stop the script (if it has not completed execution already) and then tap the phone back button to return to the main TouchDevelop window. You can tap (or swipe) to view the list of installed scripts (look for the installed tab along the top). The one you just downloaded will be at the top of the list. Tapping the icon or the name of that newly installed script will display a sentence describing the script (if provided by the script s author) followed by a list of all the components of the list, starting with the code component which is comprised of all the actions. It will look similar to Figure 2.8. Some possible actions are: If we want to view or edit the code of the action named main, we simply touch the name main. Touching anywhere within that code listing will activate the script editor. Then you have the opportunity to make changes to the line which was touched, or to insert new code above or below the line, or to cut the line (i.e. delete it with the possibility of pasting it somewhere else). If we want to view or edit the code of an event, we can touch its name. (However this script does not have any events.) Similarly, for viewing or editing the definitions for any global data variables. (Again, this particular script does not declare any.) If we want to add a completely new action to the script, we should touch the plus symbol to the right of the word code. (Similarly for adding new events or new global variables.) 28

37 VERSION 1 EDITING IN TOUCHDEVELOP Figure 2.8: Accessing Code and Other Components of the forgotten songs Script 2.7 CAUTION! PROTECTING YOUR INFORMATION Before you download a new script to your phone and begin using it or editing it, do take a few moments to check that this script does not transmit personal information about you to someone else. (At least, not unless that is the intended purpose of the script.) The information displayed about a script may include some special symbols. For example, you may see these two symbols included in the script s description: The symbols provide a summary of what kind of information is accessed by the script and what happens to it. If we see the two symbols shown above, we are being told that the script accesses the collection of music on the phone (the first symbol) and that the script makes unchecked accesses to the web (the second symbol). However, it would only be information about your music collection (the names of albums, etc.) that might escape. Most people would not worry about that potential loss of information. An explanation of the symbols and how the information flow analysis is performed can be found on the TouchDevelop website at this URL: 29

38 EDITING IN TOUCHDEVELOP VERSION 1 In addition to the analysis performed by TouchDevelop, there is a second level of protection. When you install a script and run it for the first time, you can configure whether TouchDevelop uses your real or anonymized information. For example, your anonymized location is a random place on earth. With the default configuration, TouchDevelop will use your real information only if you will get a chance to review the information before it escapes the phone and potentially be seen by someone else. The privacy settings can also be changed on the script properties page. 2.8 EXERCISES These exercises are aimed at giving you practice in editing. They are intended to be quite simple and to build only on the examples in this chapter. 1. In the Add n Numbers script in Figure 2.1, change the string to read ( The total is sum). 2. Consider the Add n Numbers script in Figure 2.1. It adds the numbers 1.. n. Follow the steps in Section 2.3 and change the variable name n to be limit instead. 3. The Add n Numbers script would be more interesting if we could enter different numbers to add, as in a calculator. We might want to enter prices we paid for gas recently, as in 23.95, 30.54, 42.60, 20.00, Change the line sum := sum+ i to be sum := sum + wall ask number("enter the next value") Note that with this data, we would still enter the number 5 for n at the start of the script. In Chapter 3, we ll look at while loops which are more flexible for entering a variable number of numbers. 4. The random circles action in Figure 2.5 is set to draw 20 circles. Add a parameter to the action, similar to that in the Add n Numbers script of Figure 2.1, so that you can say how many circles you want at the beginning. 5. Following on from Exercise 4, there is a statement to clear the screen that we can issue after the number is entered and before the circles start appearing at the start of the action. It is wall clear Add this as the first line of the draw circles action. 6. Section 2.3 describes how to add comments to a script. Add your name and today s date as comments to your scripts. 30

39 VERSION 1 LANGUAGE BASICS CHAPTER 3 TOUCHDEVELOP LANGUAGE BASICS Using the techniques described in the Chapter 2, you can input and edit scripts which perform actions on your Windows Phone. The script is just like a computer program and we can discuss the scripting language in terms of common programming language concepts. In this chapter we give a broad overview of the main features of the TouchDevelop scripting language by looking at an example A SAMPLE TOUCHDEVELOP SCRIPT 3.2. WHAT IS A TOUCHDEVELOP SCRIPT COMPOSED OF? 3.3. SOME LANGUAGE BASICS 3.4. VALUE TYPES VERSUS REFERENCE TYPES 3.5. THE NOTHING TYPE AND THE INVALID VALUE 3.6. THE WEBSITE VIEW OF A SCRIPT 3.1. A SAMPLE TOUCHDEVELOP SCRIPT A fairly simple small script is shown in Figure 3.1. The script looks at the songs on the phone and posts the names of the songs that have not been played yet. At the top level, a script is composed of actions, events and global data. An ACTION is just like a function in C or a method in Java or C#. It can take parameters, it can return results generated by some calculations, and it contains statements. The sample script has two actions named main and display song. An EVENT contains statements which are executed whenever the event occurs. The sample script has two events named shake and active song changed. The first event is triggered whenever the phone is shaken, the second event is triggered whenever our script starts playing a new song. GLOBAL DATA can be used to remember information between events happening or while the script is inactive (perhaps while taking a phone call). The script of Figure 3.1 shows a global data item named played. It does not appear in the code listing on the phone itself it has to be viewed separately from the code. 31

40 LANGUAGE BASICS VERSION 1 The statements used inside the actions and events of the sample script should look familiar to anyone who has written programs before. Let s quickly run through what the script does when it is executed. Figure 3.1: The new songs Script action main() Finds songs not played yet. var found := 0 var songs := media songs for each song in songs where true do found := found + display song(song) ("Songs played with this script: " played) post to wall ("Songs never played: " found) post to wall action display song(song) returns result Post a song to the wall if not played yet and returns 1; otherwise returns 0. if song play count = 0 then song post to wall result := 1 else result := 0 event active song changed() Increment the song played counter. played := played + 1 event shake() Pauses and resumes playing. if player is playing then player pause else player resume 32

41 VERSION 1 LANGUAGE BASICS STARTING THE ACTION AND DECLARING LOCAL VARIABLES 1. The script begins with the action named main. It must be this action because it is the only one not flagged as private. (If there are two or more public actions, then the one called main would be chosen; if none is called main, the alphabetically first will be chosen.) 2. The main action declares a local variable named found and initializes it to 0. This initialization causes found to always be a variable with the type Number. 3. Next another local variable named songs is declared. It is initialized to be a collection of all the songs (i.e. music files) that are held on the phone. The service named media is accessed from the TouchDevelop library; this service is an object with various properties and methods which allow a TouchDevelop script to access songs, song albums, song playlists, pictures, picture albums (as well as a few other things). The expression media songs retrieves a collection of all the songs on the phone. ITERATING OVER ALL SONGS IN THE COLLECTION 4. Now a for each loop accesses each element of the songs collection in turn and assigns it to a new local variable named song. 5. The body of the for each loop invokes the action named display song passing it song as a parameter. The result of the call is either the number 1 or the number 0 it is 1 if the song s play count is zero and 0 otherwise. Hence the assignment increments the local variable found each time the loop encounters a song which has never been played. 6. When the loop is finished, the local variable found contains a count of how many songs on the phone have never been played. DISPLAYING SOME MESSAGES 7. The next statement after the loop contains the expression "Songs played with this app: " played. That expression constructs a string by obtaining the value of the global data item named played(its value will be the integer 0 when the script is invoked for the first time), converting it to a string, and concatenating it after the end of the string constant "Songs played with this app: ". The constructed string is now displayed on the phone s screen. We can understand that action as being a result of the method call post to wall ; it is a method possessed by the String type. 8. Finally, the script similarly constructs a string value from the expression "Songs never played: " found and displays that on the phone s screen too. WAITING FOR THE USER TO TERMINATE THE PROGRAM 9. After executing that last statement, the script keeps running and waits for events to occur; the script execution does not finish. (This is true for any script which declares an event; if 33

42 LANGUAGE BASICS VERSION 1 there were no events declared, the script would stop execution.) The script can be halted bu tapping the phone back button. 10. Now, what did the display song action do? As well as looking up the play count property of the song passed in as a parameter, it also invokes the post to wall method on each song whose play count is equal to zero. As one would expect, the post to wall method displays the name of the song. However it also displays additional information about the song and it displays a button named play. Figure 3.2 shows the details and play buttons for two songs as they might be listed on the screen when the script has finished checking all the songs held on the phone. EVENT HANDLING CODE 11. If, while the script is active, we shake our phone, the shake event is activated. The code inside this event first tests to see if the phone is currently playing any music. If it is, the music is paused and if not, the playback of any paused music is resumed. 12. How do we play a song while the script is active? We simply have to tap one of the play buttons which have been displayed. As well as starting the playback of that song, the active song changed event is triggered in our script. Its only action is to increment the global data variable named played. Figure 3.3: Figure 3.2: Songs as Displayed on the Screen 3.2. WHAT IS A TOUCHDEVELOP SCRIPT COMPOSED OF? A TouchDevelop script contains four main components which are CODE, EVENTS, DATA and ART. The script also has access to resources on the phone and on the internet which are made available through the TouchDevelop API (short for Application Program Interface ). The code component consists of actions. A reference to a particular action in the program is made with a triangle symbol used like this 34

43 VERSION 1 LANGUAGE BASICS display song(song) An action with or without parameters can be invoked from another action in the script or from the code for an event. An action which has not been marked as PRIVATE can be called directly from the TouchDevelop environment to start up execution of the script with that action. (If parameters are needed for that initial action, the user will be prompted for them.) Events are similar to actions except that they are invoked by something happening outside the script, such as the phone being shaken. The data component consists of global variables, declared externally to any action or event in the script. The example script seen in Figure 3.1 has one such variable named played. Access to the variable in actions and events uses a special symbol to indicate that a global data item is coming, like this played A global data variable can have any of the datatypes listed in the TouchDevelop API. This list includes the simple types as well as a rich selection of composite types which are useful for accessing the features of a Windows phone. The Art component consists of pictures and sounds which are special kinds of data values used by the script (and which can be shared with other scripts). Services available to a script include math, media, senses and maps. A more complete list will be covered in the following chapters. These services are similar to classes in Java or C# which have only static members. Access to the methods and properties of these services is obtained via an arrow notation. Whereas languages like Java or C# would use a dot to separate an object or class from a method name, TouchDevelop uses an arrow for its better visibility on the screen. Some examples of the arrow notation are as follows. math sin(0.5) math π media choose picture senses camera For example, the script shown in Figure 3.1 uses the expression media songs to retrieve a collection of all the songs held on the Windows phone SOME LANGUAGE BASICS For anyone who has programmed in a modern language such as Java, C# or Python, Table 3.1 summarizes the main features of the scripting language. More details will be provided in this and later chapters. 35

44 LANGUAGE BASICS VERSION 1 Table 3.1: TouchDevelop Scripting Language Summary Feature Type System Datatypes Description The language uses static typing for variables (i.e. a variable has a datatype which cannot change as the script runs). The language uses strict type checking (i.e., any attempt to apply an operation to a value of the wrong type is reported as an error before the script begins execution). The types include Number, Boolean, DateTime and String. There are many other datatypes provided by the TouchDevelop API. The Number type contains both integers and real numbers (i.e. IEEE floating point numbers). Some types, such as Number, are known as value types while others, such as the String Collection type, are known as reference types. (This is terminology borrowed from C#.) The distinction between value types and reference types, and its relevance to how assignments and parameter passing work, are explained below. All datatypes contain a special value called invalid which indicates an error. Variables A local variable is declared with an assignment of an initial value. That value determines the variable s datatype. Variable s Scope Actions Statement Types Assignment statement A variable is accessible from its point of declaration down to the end of the enclosing block of statements. A parameter or a result variable is visible throughout the body of an action. Actions are similar to procedures and functions in other languages. They accept zero or more arguments and they return zero or more result values. The parameter passing mechanism is similar to that used in the Java and C# languages. It is explained in more detail below. An action can return zero or more result values. Result variables can be named as a property of the action and the final values of these variables are used as the results. Result variables are initialized with the invalid values of their respective types. A statement can be an expression which is simply evaluated for its side-effects (such as an invocation of an action or displaying a value on the screen). Other forms of statement are: assignment statement, if statement, for each loop, for loop, and while loop. The assignment operator is :=. It can assign multiple values to several variables if the right-hand expression is a call to an action which returns multiple results. An assignment copies either a value or a reference to a value to a left-hand side varia- 36

45 VERSION 1 LANGUAGE BASICS Feature Description ble depending on whether the datatype of the value is one of the value types or is a reference type. This is explained in more detail below, If statement For each loop For loop Uses an expression of Boolean type to select between a then clause and an else clause (which may be empty). A loop which steps through each value in a collection. The current value being accessed is held by the loop s index variable. A loop which has an index variable that steps through an increasing sequence of integer values starting at 0 and continuing up to but not including a specified limit value. While loop Arithmetic Operators Comparison Operators A loop controlled by an expression which is re-evaluated on each iteration and must yield true for one more iteration of the loop body to be performed. These are the usual operators + - * and / For numbers, the comparison operators are < = > To compare strings, the compare or equals method must be used. String Operators Boolean Operators The only operator is and is used for string concatenation. It can be used with non-string operands too; they will be converted to the String type before concatenating. The Boolean operators are and, or, and not. Events Statements can be provided which execute whenever a particular event occurs. (For example, shaking the phone or changing the phone s orientation triggers events.) The code for an event will be completed before control is returned to an action or before another event is executed. Events are executed in the same order as they occur VALUE TYPES VERSUS REFERENCE TYPES TouchDevelop implements datatypes in a similar manner to Java and C#. Therefore the following explanation should be unnecessary for anyone who has programmed in these languages. 37

46 LANGUAGE BASICS VERSION 1 Consider the following short fragment of code which manipulates values of type Number. var num1 := 99 var num2 := num1 num2 := num2 + 1 num1 post to wall // displays 99 num2 post to wall // displays 100 The numbers displayed, 99 and 100, are as you would expect. When num2 was incremented, it had no effect on the value of num1. That is because num1 and num2 hold two distinct Number values. Now consider the following fragment of code. var list1 := collections create string collection // assign an empty list of strings to list1 list1 add("hello") // add one string to the list var list2 := list1 list2 add("goodbye") // add one string to the list list1 post to wall // displays Hello;Goodbye list2 post to wall // displays Hello;Goodbye Here, when we added one more string to the list2 collection, it changed the list1 collection too. How is that possible? The explanation is that the script created only one string collection, doing that in the first line. The assignment line1 := line2 causes these two variables to both refer to the same list of strings. To understand the scripting language fully, it is important to know when an assignment is copying a value and when it is copying a reference to a value. Fortunately, there are many datatypes where the distinction simply does not matter. These are the immutable types. For example, String is an immutable type. When a String value is copied, as in this code fragment var s1 := "abc" var s2 := s1 there is no way to alter the string instance referenced by s2. String values cannot be changed. We can assign s2 a new string value, as in s2 := s2 "def" but that simply creates a new string and assigns a reference to that new string to s2. The other variable, s1, is completely unaffected. Finally, we should observe that when an action is invoked, the caller supplies values which are assigned to the parameters of the action. Whether the action can affect the values being passed depends on whether the values are mutable and, if they are, whether the types of these parameters are value types or reference types. 38

47 VERSION 1 LANGUAGE BASICS 3.5. THE NOTHING TYPE AND THE INVALID VALUE The name Nothing represents a datatype similar to void in C# or Java. It is used to describe the result datatype of a method which is invoked purely for its side-effects and returns no useful result. For example, the statement player next causes the music player to move to the next song in a list, and no useful result is returned by that invocation. The type of the next method of the player service is shown as NOTHING in the API documentation. All types have a special value (or be in a special state) which is described as INVALID in the API documentation. For example, the statement pic := senses take camera picture should cause the phone s camera to take a picture and assign that picture to the variable pic. However the user has an opportunity to cancel the camera capture so that pic does not receive a valid picture as the result. The script can (and should) test for this situation by testing whether the expression pic is invalid has a true or false value. It would not be incorrect to consider the INVALID value to be similar to null for an object reference in a language like C# or Java THE WEBSITE VIEW OF A SCRIPT The current version of the TouchDevelop website shows scripts in a slightly different format from those seen on the phone and in this book. It is expected that the displayed formats for scripts on the website will be changed in the near future to be much closer to the format used on the Windows phone. The differences are very minor, and you should not have any trouble reading scripts on the website. 39

48 LANGUAGE BASICS VERSION 1 40

49 VERSION 1 CONTROL FLOW CHAPTER 4 CONTROL FLOW We now start our journey into real programming with TouchDevelop. TouchDevelop is not just a language, but also an environment that lets you access everything on your phone songs, pictures, contacts and so on. We shall be showing examples of how this is done in the next few chapters. A list of songs is called a collection, and in this chapter we shall talk about the variety of collections that are available. To work through a collection, we need loop constructs. By the end of this chapter, you will have been introduced to the different kinds of loops The three kinds of looping statements are explained using some simple examples. The bodies of these loops contain code which tests the values held by loop index variables, so this chapter also provides examples of IF statements. One kind of loop, the FOR EACH loop, is used with instances of collection types, so that topic should be covered first OVERVIEW OF COLLECTIONS 4.2. THE FOR EACH LOOP 4.3. THE WHILE LOOP 4.4. THE FOR LOOP 4.1 OVERVIEW OF COLLECTIONS The TouchDevelop API provides access to several kinds of collection. The collection types currently supported by the API are listed in Tables (a) The TouchDevelop Mutable Collection Types to 4.2. As in other high level languages, a collection is exactly as it sounds a collection of values. An array provides one way to implement a collection in a program; a linked-list is another common implementation for a collection. In TouchDevelop, the implementation of collections is hidden from the user. A script can step through the values in a collection or index the collection to access, say, the 15 th item. Some kinds of collections are MUTABLE. These are the ones listed in Table 4.1(a). It means that a script can create a new collection and add or remove elements from it. Other kinds of collection are IMMUTABLE. These are the ones listed in Table 4.1(b).Since there are many collection types in the table, they have been grouped into three categories. Immutable means that a collection (such as a list 41

50 CONTROL FLOW VERSION 1 of songs on the phone or a list of home network devices) can be obtained, but the elements of the collection can only be accessed. There are no methods for adding or removing elements from an immutable collection. Table 4.1: (a) The TouchDevelop Mutable Collection Types Type Description Link Collection A list of links; each link is a reference to a video, image, , or phone number Location Collection A list of locations; each location is a coordinate pair Message Collection A list of messages Place Collection A collection of places Sprite Set A collection of sprites String Collection A collection of strings There are a few methods which are common to all collections. These are described in Table 4.2. In the left-hand column of this table, each entry shows the complete signature for the method. For example, the at method takes a single argument of type Number and it returns a single result of the element type (denoted by the word ELEMTYPE). This is similar to how methods are documented on the TouchDevelop website. Note the table omits two methods which are also available for all collection types. That is because these two methods can be used with all datatypes. They are is invalid and post to wall. The is invalid method tests whether a usable value has been assigned to the variable being tested (or has been returned from a method that was invoked) and yields a true or false value. The post to wall method displays some representation of the value on the screen. The nature of the representation depends on the datatype. 42

51 VERSION 1 CONTROL FLOW Table 4.1: (b) The TouchDevelop Immutable Collection Types Type Description Social Details Collections Appointment Collection A collection of appointments Contact Collection A collection of contacts Media Collections Picture Albums A collection of picture albums Pictures A collection of pictures Playlists A collection of song playlists Songs A collection of songs Home Network Collections Device Collection A collection of devices on the home network Media Link Collection A list of links to media on the home network Media Player Collection A list of devices for playing media on the home network Media Server Collection A list of media servers on the home network Printer Collection A collection of printers on the home network 43

52 CONTROL FLOW VERSION 1 Table 4.2: Standard Methods for Mutable and Immutable Collection Types Method at(pos: Number): ELEMTYPE Description retrieves an element of the collection at a particular position (the first element is at position 0). The type of the result is the same type as the elements in the collection. count: Number returns the number of elements in the collection random: ELEMTYPE selects and returns a random element of the collection (this method is provided for many but not all collection types) There are a few more methods which are common to all mutable collection types. These are listed in Table 4.3. Other methods for collections are specific to each collection type and will only be described as we come to them. Table 4.3: Additional Standard Methods for all Mutable Collections Method create XX: COLLECTIONTYPE Description The method is accessed via the collections service. There is one create method for all mutable collection types except sprite set; for example create place collection is one such method, and the result has type Place Collection. add(e: ELEMTYPE): Nothing Adds a new element e to the end of the collection of ELEMTYPE values clear: Nothing removes all elements from the collection Figure Creating and Using a Mutable Collection shows some sample code which creates a mutable collection, adds some elements to it, displays the size, removes an element, and then gives the size again. 44

53 VERSION 1 CONTROL FLOW Figure 4.1: Creating and Using a Mutable Collection action main( ) var names := collections create string collection names add("joan") names add("jane") names add("jill") names count post to wall names remove("jane") names count post to wall 4.2 THE FOR EACH LOOP It is frequently the case that we want our script to examine or use each element of one of these collections. The FOR EACH loop is used exactly for that purpose. EXAMPLE: ITERATING OVER ALL PICTURES HELD ON THE PHONE Figure First for-each Example (pictures and dates) shows a script which checks each picture held on the phone and displays the picture and the date it was taken. Figure 4.2: First for-each Example (pictures and dates) action main( ) for each pic in media pictures where true do pic resize(64,64) pic post to wall pic date post to wall The local variable pic is assigned a reference to a different picture in the collection on each iteration of the loop. The WHERE clause component of the FOR EACH loop can be used to select a subset of values in the collection. In this example, we want to display information about every element in the collection and so the test provided after the keyword where is the Boolean constant true. Note that pic is a read-only variable, assignments to pic are not allowed. 45

54 CONTROL FLOW VERSION 1 EXAMPLE: FIND ALL PICTURES ON THE PHONE LESS THAN ONE DAY OLD This example is very similar to the previous one, but we are selecting only those pictures which are less than 24 hours old to display. We have two obvious ways to test whether a picture should be displayed or not. We can use an IF statement in the scripting language or we can take advantage of the WHERE clause attached to the FOR EACH loop. Both versions are shown in Figure Second FOR EACH Example (selecting recent pictures). Figure 4.3: Second FOR EACH Example (selecting recent pictures) action main() version 1 of the program for each pic in media pictures where true do if (time now subtract(pic date)) (24 * 60 * 60) then pic resize(64,64) pic post to wall pic date post to wall else do nothing action main() version 2 of the program for each pic in media pictures where (time now subtract(pic date)) (24 * 60 * 60) do pic resize(64,64) pic post to wall pic date post to wall Some explanation of how the script tests the age of each picture is probably required. The expression time now returns the current time of day; it is returned as a DateTime value. Similarly the expression pic date returns the time at which the picture was taken as a DateTime value. The DateTime datatype provides a method named subtract which computes the difference between two DateTime values as a number of seconds. We simply have to compare this difference with the number of seconds in a day. EXAMPLE: DISPLAY THE DURATIONS OF ALL SONGS HELD ON THE PHONE Figure Third FOR EACH Example (durations of songs) shows the code for a script which displays some simple information about each song found on the phone namely the name of the song and its duration. Note the similarity with Figure First for-each Example (pictures and dates): iterating over the elements in a collection tends to look much the same no matter what kind of elements are held in that collection. 46

55 VERSION 1 CONTROL FLOW Figure 4.4: Third FOR EACH Example (durations of songs) action main( ) for each song in media songs where true do song name post to wall song duration post to wall EXAMPLE: FINDING AND PLAYING THE SHORTEST SONG HELD ON THE PHONE As another illustration of the use of if statements, Figure Fourth FOR EACH Example (shortest song) shows a script which searches through all the songs to find the one with the shortest duration and then starts playing that song. The variable shortest holds the duration of the shortest song found so far. Using a value provided in the math resource, we initialize its value to PLUS INFINITY. The variable named which holds the shortest song found so far. Since the scripting language requires an initial value for that variable, we assign it a special INVALID value. The body of the loop tests whether the current song being inspected is shorter than the shortest found so far. If the test succeeds, we update the shortest and which variables. Figure 4.5: Fourth FOR EACH Example (shortest song) action main( ) var shortest := math + var which := invalid song for each song in media songs where true do if song duration shortest then which := song shortest := song duration else do nothing the loop has terminated which play This script can of course be modified so that the where clause is used instead of an if statement. 4.3 THE WHILE LOOP The WHILE loop in the TouchDevelop scripting language looks syntactically similar to WHILE loops in many programming languages and also behaves similarly. 47

56 CONTROL FLOW VERSION 1 EXAMPLE: USING A WHILE LOOP TO IMPLEMENT A COUNTDOWN TIMER To illustrate a WHILE loop, we show a countdown timer. It starts at 10.0 seconds and displays the time remaining as a descending sequence in tenths of a second: At this point, the Windows phone takes a picture. The script is shown in Figure A while Loop Example (countdown timer).. Figure 4.6: A while Loop Example (countdown timer) action main( ) var timer := 10.0 while timer > 0 do wall clear timer post to wall timer := timer time sleep(0.1) the loop has terminated var pic := senses camera preview pic post to wall In this script, we clear the wall before displaying the new time duration. If we did not do that, each of the time durations would be written as a separate line, inserted one above the other. Better still, we should display the remaining time using very large digits. However that requires the use of a textbox or some graphics programming. We will display large digits in the new version of the program which is coming next. 4.4 THE FOR LOOP A FOR loop uses an index variable which takes on successive integer values starting from zero and continuing up to some limit. The index variable is read-only. EXAMPLE: USING A for LOOP TO IMPLEMENT A COUNTDOWN TIMER The script shown in Figure A FOR Loop Example (countdown timer) is functionally equivalent to the previous script (Figure A while Loop Example (countdown timer)) except that it uses a FOR loop to iterate 100 times and it draws the remaining time in large characters at random positions and in random colors on the screen. 48

57 VERSION 1 CONTROL FLOW Figure 4.7: A FOR Loop Example (countdown timer) action main() for 0 i < 100 do wall clear var pic := media create picture(480, 800) pic draw text(math rand(350), math rand(575), i, 150, 0, colors rand) pic post to wall time sleep(0.1) the loop has terminated senses camera preview post to wall 49

58 CONTROL FLOW VERSION 1 50

59 VERSION 1 STRINGS AND NUMBER MAPS CHAPTER 5 STRINGS AND NUMBER MAPS Traditional programming frequently involves arithmetic on the one hand, and string handling on the other hand. In this chapter, we show how these topics are done in TouchDevelop. TouchDevelop does have all the usual arithmetic operators, as well as functions for random numbers, and the example we explore here will enable you to learn what they are. If you enter the program yourself, you will also become more adept at choosing the options offered by Touch Develop as a statement unfolds. In older languages, lists of numbers were stored in arrays. We saw in Chapter 4 that lists of more complex objects like pictures and songs were stored in collections in Touch Develop. Arrays and collections are examples of data structures. The TouchDevelop scripting language does not provide arrays as a mechanism for building data structures. In most cases, collection types may be used instead. In the few cases where the collection type does not meet the needs of the problem, the Number Map type would likely provide a very satisfactory replacement STRINGS NUMBER MAPS DISPLAYING A LINE CHART CLOSEST NUMBER: AN EXAMPLE PROGRAM USING A NUMBER MAP AND STRINGS 5.1.STRINGS Strings in TouchDevelop are sequences of unicode characters, just as in Java or C#. The String type supports many of the same methods as found in Java or C#. In all cases, there is a subject string which might be a string constant or a variable with a String value. For example, var str := "the quick brown fox jumped over the dog" if str contains("fox") then "we have a fox!" post to wall. else "the crafty fox escaped!" post to wall The methods support searching a string for substrings or for patterns defined by regular expressions, extracting substrings, trimming characters from either end, splitting a string into smaller 51

60 STRINGS AND NUMBER MAPS VERSION 1 strings, and many more. Some of the more frequently used String methods are listed in Table Some Methods for the String type. The method descriptions are necessarily brief and may use some terminology you are unfamiliar with. In particular, three methods rely on a means for specifying patterns which is known as regular expression notation. More information about that notation can be found on the web; the.net webpage at provides an exact specification of the regular expression notation used by TouchDevelop (and contains links to additional explanations). Table 5.1: Some Methods for the String type Method Description at(i: Number): String returns the character (as a string of length 1) at position i in the string, where the first character is at position 0. compare(s: String): Number compares the string with another string s. The result is -1 if this string comes before s in a lexicographic ordering, +1 if it comes afterwards, and 0 if the two strings are equal. concat(s: String): String constructs a new string by concatenating s to the end of this string; it is the same as using the operator. contains(s: String): Boolean returns true if this string contains s, and false otherwise count: Number returns the length of this string (the number of characters) ends with(s: String): Boolean return true if this string ends with the string s, false otherwise equals(s: String) returns true if this string is equal to s, and false otherwise 52

61 VERSION 1 STRINGS AND NUMBER MAPS index of (s: String, p: Number): Number searches this string starting at position p for the first occurrence of s, returning its starting position if found and -1 if not found insert(p: Number, s: String): String constructs a new string by inserting s at position p inside this string is empty: Boolean returns true if this string contains 0 characters, false otherwise is match regex(r: String): Boolean matches the regular expression r against this string, returning true if there is a match and false otherwise last index of(s: String, p: Number): Number similar to index of except that it is the position of the last occurrence of s which is returned matches(r: String): String Collection returns a collection of all substrings of the string which match the regular expression r post to wall: Nothing displays a line chart of the index-value pairs in the map replace regex(r: String, s: String): String replaces all substrings which match the regular expression r with the string s split(d: String): String Collection breaks the string up into a collection of substrings which were delimited by characters in string d starts with(s: String): Boolean returns true if the string starts with s, and false otherwise substring(p: Number, len: Number): String returns a substring of length len starting at position p 53

62 STRINGS AND NUMBER MAPS VERSION NUMBER MAPS An array in a language like C, Java or C# provides a mapping from an integer, the index, to a value held in the array at the index position. The index would usually have to be a consecutive sequence of integers starting at zero. The Number Map type in TouchDevelop provides a mapping from an index which has the Number type to an element which also has the Number type. It is more powerful than an array of numbers because the index can be any floating point number, such as 2.718; it is by no means restricted to integers. The index values do not have to be restricted to a tight range either, any set of floating-point values can be used. A snippet of code which creates and initializes a Number Map value appears below. var conversion := collections create number map conversion set at(32.0, 0.0) conversion set at(98.6, 37.0) However, most of the time we will use integer values for the indexes and use the Number Map type as though it were a simple array of numbers. Many of the Number Map methods are listed in Table Some Methods for the Number Map type. Table 5.2: Some Methods for the Number Map type Method Description create number map: Number Map the method is accessed via the collections service, it creates an empty instance of a Number Map value at(i: Number): Number returns the value with index i (which may be any floating-point number). If no value with that index has been stored in the map, the result is 0. count: Number returns the number of entries in the map max: Number returns the maximum entry in the map min: Number returns the minimum entry in the map 54

63 VERSION 1 STRINGS AND NUMBER MAPS post to wall: Nothing displays a line chart of the index-value pairs in the map set at(i: Number, v: Number): Nothing stores value v at index position i sum: Number returns the sum of the entries 5.3.DISPLAYING A LINE CHART One very special use for the Number Map type is drawing charts. To illustrate that, we provide a trivial example. In Figure 5.1(a), we simply add some pairs of points to a Number Map variable and then post its value on the wall. The result of running this script is shown in Figure 5.1(b). Note that the pairs of numbers (the index, value pairs) are drawn in ascending order by the index value (not by the order they were added to the collection). The ranges of values in the X and Y directions on the chart are determined by the smallest and largest values found in the Number Map collection. Figure 5.1: (a) Script to draw a Line Chart; (b) The Displayed Result action main( ) Draw a line chart var graph := collections create number map graph set at(1.5, 3.15) graph set at(2.5, -2.7) graph set at(3.5, 5.6) graph set at(4.5, -6.3) graph set at(0.5, 1.3) graph post to wall 5.4.CLOSEST NUMBER: AN EXAMPLE PROGRAM USING A NUMBER MAP AND STRINGS The program presented in Figures 5.2 to 5.5 can be used to find a phone number which you don t quite remember. If you enter your best guess at the number, say , then the script will 55

64 STRINGS AND NUMBER MAPS VERSION 1 search through all the numbers associated with the contacts on your phone and return the number which is CLOSEST. Now, what do we mean by closest? This is a problem which has been well researched, especially in the field of bioinformatics where the computer may be asked to compare two DNA sequences and report on how similar they are. We compare the two phone numbers using a metric known as the Levenshtein Distance. This measure counts how many simple edits are needed to convert one string of characters into the other string, where a simple edit means an insertion, a deletion or a substitution of a single character. The concept is explained in a Wikipedia article at this URL: The algorithm for computing the Levenshtein Distance between our two phone numbers has been adapted from one given in that Wikipedia article. The algorithm needs a two-dimensional array of integers that would be declared as int d[m+1][n+1]; in the C language, where m and n are the lengths of the two phone numbers (where we count the digits to give the length). The TouchDevelop scripting language provides only the Number Map type and, if we use a range of integers for the index, it corresponds only to a one dimensional array. However we can simulate a two dimensional array if we allocate a map with (m+1) (n+1) elements and we use the element at index position i (n+1)+j to implement an array element at position d[i][j]. The code for the Closest Number app appears in Figures Error! Reference source not found. to Global Data. There are a few points in the script which are worth looking at. The main action uses ask string to prompt the user to enter a string as input. The main action uses the search contacts method of the social global to retrieve a collection of all the contacts held in the phone. The argument is a string whose normal purpose is to select only the subset of contacts where the name contains the supplied string. By providing an empty string as the argument, everything gets selected. The test number action calls normalize string to remove some extraneous characters from the phone number. In particular, we want to remove all white space characters (these would likely be spaces and tab characters) and we also want to remove parentheses and dashes. So, if the contacts list contains phone numbers in differing formats, such as (555) then all three will all be rendered as the string of characters The replace regex method, which uses regular expression notation to describe what should be matched in the string, is convenient for this purpose. 56

65 VERSION 1 STRINGS AND NUMBER MAPS In case one phone number has a country code prefix, such as +44 for the United Kingdom, and the other number does not, we try comparing only the trailing part of the sequences of digits. Figure 5.2: The main action action main( ) var searched num := wall ask string("enter what you think the phone number is") var searched num := normalize number(searched num) if searched num count = 0 then "Error: no number entered. Please try again. " post to wall time stop halt execution of the script else do nothing var list := social search contacts('') if list count = 0 then "No contacts found on phone. " post to wall else closest := list at(0) best distance := 1000 foreach contact in list where true do contact post to wall test number(contact, contact work phone, searched num) test number(contact, contact home phone, searched num) test number(contact, contact mobile phone, searched num) closest post to wall ("The number: " closest number) post to wall ("The nearest match we found needed " best distance " edits. ") post to wall; 57

66 STRINGS AND NUMBER MAPS VERSION 1 Figure 5.3: The test number and normal number Actions action test number(c: Contact, s: Link, t: String) var num := s address var num1 := normalize number(num) num1 post to wall var t1 := t // Compare only trailing character positions, in case one has a country // code prefix or area code and the other does not. var diff := num1 count - t count if diff < 0 then t1 := t substring(t count - num1 count, num1 count) if diff > 0 then num1 := num1 substring(num1 count - t count, t count) num1 post to wall var dist := levenshtein distance(num1, t1) if dist < best distance then closest := c closest number := num best distance := dist action normalize number(s: String) returns ss: String var ss := s ss := ss replace regex(" [()+ ] ", "") ss := ss replace regex('-', '') 58

67 VERSION 1 STRINGS AND NUMBER MAPS Figure 5.4: The levenshtein distance Action action levenshtein distance(s: String, t: String) returns dist: Number var m := s count var n := t count var n1 := n + 1 var d := collections create number map for 0 i < m + 1 do d set at(i * n1, i) for 0 i1 < n1 do d set at(i1, i1) var dist := 0 var vals := collections create number map var k := 0 for 0 i2 < m do for 0 i3 < n do if s at(i2) equals(t at(i3)) then dist := d at(k); else vals set at(0, d at(k + 1)) vals set at(1, d at(k + n1)) vals set at(2, d at(k)) dist := vals min + 1 k := k + 1 d set at(k + n1, dist) k := k + 1 Figure 5.4: Global Data var closest : Contact var closest number : String var best distance : Number 59

68 STRINGS AND NUMBER MAPS VERSION 1 60

69 VERSION 1 ACTIONS, METHODS, REFACTORING CHAPTER 6 ACTIONS, METHODS, REFACTORING In this chapter we cover ACTIONS in more depth and show how to easily create additional actions in a script by using a technique known as REFACTORING. The chapter covers two forms of refactoring supported in TouchDevelop. One form provides an easy way to create new actions, while the other form provides an easy way to add declarations for new variables to a script. We also show an extension to the second form of refactoring which promotes a local variable to become a new global data item. 6.1 ACTIONS 6.2 PARAMETER PASSING MECHANISMS 6.3 METHODS IN THE API 6.4 REFACTORING 6.1 ACTIONS An ACTION in TouchDevelop is very similar to a function in C or Python, or to a static method in Java or C#. It is an independent sequence of statements which has a name, it optionally has input parameters, and it optionally has result parameters. Let us take a look at the short example in Figure 6.1. This is similar to how the code would appear on the phone s screen. Figure 6.1: The send invite Action action send invite( recips, msg ) returns n n := 0 for each s in recips where true do social send (s, party invitation, msg) n := n + 1 This send invite action has some properties which can be viewed by tapping the first line of the action, tapping the edit button, and swiping left-to-right. The PARAMS property will show the names 61

70 ACTIONS, METHODS, REFACTORING VERSION 1 and the datatypes of all the input parameters. For the send invite action, the listing of the parameters is as shown in Figure 6.2. Figure 6.2: The send invite PARAMS Property Similarly, the RETURNS property provides more information about the result returned by the action. It is shown in Figure 6.3. Figure 6.3: The send invite RETURNS Property The input parameters work in a similar manner to parameters of methods in Java or C#. In other words, the parameters are considered to be local variables of the action and, each time the action is invoked, the parameters are initialized by copying values supplied by the caller. Suppose, for example, that one of the other actions in our script is bulk mailer as shown in Figure 6.4. This action creates a String Collection value as the value of variable addr list and initializes the variable msg to hold a String value. When send invite is invoked, its first parameter recips is initialized so that it refers to the same String Collection as addr list. Similarly, the second parameter msg is initialized to hold the same string as the caller s local variable named msg. Now that the parameters of send invite have been initialized, the body of the send invite action is executed. We will not go into any detail about what this action does (suffice to say it will likely annoy everyone whose name begins with j in the contacts collection held on your phone if you actually run it). However, while the action is running, it is computing a value held in the variable n. This variable is declared as an output parameter, but while the action is executing, it should be considered to be just like any local variable. When the action s body has finished executing, the value of this local variable is returned as the result. Its value will be assigned to variable cnt in the caller. 62

71 VERSION 1 ACTIONS, METHODS, REFACTORING Figure 6.4: A Caller of the send invite Action action bulk mailer( ) var my j friends := social search contacts("j") var addr list := collections create string collection for each c in my j friends where true do var addr := c address addr list add(addr) // a more realistic example would assign several lines // of text to the msg variable var msg := "Will you come to my party on Friday? " var cnt := send invite(addr list, msg) (cnt " friends have been invited") post to wall Unlike many programming languages, there is no return statement in TouchDevelop. Execution must reach the end of the action before control returns to the caller and any results are returned. Now for some details which serious script developers need to know. 6.2 PARAMETER PASSING MECHANISMS This is a topic which has been partially covered in Chapter 3 already. To recap, there are two kinds of datatypes in the TouchDevelop scripting language. There are VALUE TYPES, where the variable holds the value directly. For example, a variable of type Number corresponds to a word in the memory of the phone which holds the number directly (as a bit pattern). And there are REFERENCE TYPES. Every collection type in TouchDevelop is an example of a reference type. Suppose, for example, a variable has the Link Collection type. The link collection value is a data structure located somewhere in memory and the starting point for that data structure has a memory address (or a location number). A variable in the script which has the type Link Collection would correspond to a word in memory which holds the memory address of the data structure. When a variable which has a reference type is assigned to another variable or is passed as a parameter to an action, we have two references to the same data structure in memory. This situation is diagrammed in Figure 6.5 where the variable num1 has the Number type, while both links1 and links2 are variables with the Link Collection type. After creating a link collection as a list of three addresses and assigning it to links1, another assignment var links2 := links1 has been executed. Now any changes to the links1 link collection will change the links2 collection and vice versa, because they are both references to the same collection. 63

72 ACTIONS, METHODS, REFACTORING VERSION 1 Figure 6.5: Value Types and Reference Types Exactly the same behavior is observed for passing parameters to actions. If the parameter has one of the value types then the action has a completely independent copy. If the parameter has one of the reference types, then the caller and the action share references to the same value held in the phone s memory. Which are the value types exactly? They are Number, Boolean, DateTime and Vector3. Every other type is a reference type. RETURNING RESULTS The TouchDevelop editor allows an action to have any number of return parameters. What does this mean? It simply means that the action can return several results at once and they can have different types. As a highly contrived example, consider the action shown in Figure 6.6. Figure 6.6: An Action with Two Results action random stuff( ) returns song, pic var all songs := media songs var all pics := media pictures song := all songs random pic := all pics random 64

73 VERSION 1 ACTIONS, METHODS, REFACTORING All that matters for our example is that it has two result parameters, one of type Song and the other of type Picture. When it is invoked, the caller can assign the result to two variables simultaneously. Here is an example of how to write the calling code: var s, p := random stuff( ) s play p post to wall It declares s and p as local variables with type Song and Picture respectively, and then those variables are assigned the result of invoking the random stuff action. Not many programming languages support functions or methods which return multiple results. (Programmers in such languages must use various workarounds or less readable programming constructs.) This feature of TouchDevelop can be used to make scripts shorter and more readable. TouchDevelop treats a result parameter as a local variable with an invalid initial value. The action must assign a value to the result parameter before the action returns to the caller. To enforce that requirement, TouchDevelop analyzes the code of the action and checks that at least one assignment happens on every possible execution path through the action. 6.3 METHODS IN THE API The API provides various globals which have methods that can be invoked by a TouchDevelop script. For example, one such global is languages and one of its methods is detect language. (A Java or C# programmer might think of languages as being a class type and detect language as being a static method of the class.) The API also provides a number of datatypes, and values possessing those datatypes have associated methods. For example, chapter 2 used the Picture datatype in an example and it created a local variable named pic with that type. One of the examples used the set pixel method on that pic variable. (A Java or C# programmer might consider pic to be a reference to a class instance and set pixel to be an instance method.) When we write code to invoke these methods, parameter values may be passed into the methods and results may be returned from them. Although the API s methods are all implemented in the C# language (as is the whole TouchDevelop application), the methods all behave similarly to Touch- Develop actions. Value types are passed in to the methods using the call-by-value mechanism and reference type values are passed in using call-by-reference. Although methods provided by the API have the potential to return multiple results, none does. Every method provided in the API so far either returns a single value or it returns Nothing. 65

74 ACTIONS, METHODS, REFACTORING VERSION REFACTORING The word REFACTORING is used in software engineering to mean a reorganization of a program which does not change its behavior. Such a reorganization is normally performed to improve the quality of the software in some way, such as to make the code more efficient or to be more readable by humans. Most modern environments for software development, such as Visual Studio and Eclipse, provide a variety of tools to support different forms of refactoring. The TouchDevelop editor provides two forms of refactoring. One form extracts a group of statements from an action and creates a new action, with appropriate parameters, from those statements. We might want to perform such refactoring if we have an action which has become too long to comfortably display on the screen and we simply want to split the action up into smaller pieces. Or, perhaps we have recognized that there is a particular group of statements which we will need to execute several times with different parameterization. These are both excellent reasons to extract and create a new action. Finally, a TouchDevelop user is likely to find this form of refactoring to be a time saver because fewer taps and few swipes are needed to create a script composed of multiple actions. The second form of refactoring is to extract an expression or a subexpression, replace it with a newly created variable, and insert an initialization of that new variable with the extracted expression. A further step beyond extracting an expression and creating a new local variable is to convert that local variable into a new globally visible data item. This would make the value of the variable accessible to all the actions in the script (as well as preserving the value of the data item from one invocation of the script to the next invocation a feature known as persistence.) REFACTORING: EXTRACTION OF STATEMENTS TO A NEW ACTION Let s go through an example of refactoring in TouchDevelop. Chapter 2 contained an example, the Random circles script, which was constructed and entered as two separate actions. Suppose that we had entered the script as just one action. It would look like the script shown in Figure 6.7. There is nothing wrong with this version of the script, it is not too long and it runs perfectly well. However, we might decide that the group of statements which draws the circle is so useful that we want to extract that code and make a new action from it. 66

75 VERSION 1 ACTIONS, METHODS, REFACTORING Figure 6.7: A Monolithic Random circles Script action Random circles( ) pic := media create picture(400, 400) for 0 i < 20 do var radius := 5 + math random(95) var x := math random(400) // x coordinate of center var y := math random(400) // y coordinate of center var color := colors random for 0 i1 < 2 * math * radius do var xofs := x + radius * math cos(i1 / radius) var yofs := y + radius * math sin(i1 / radius) pic set pixel(x + xofs, y + yofs, color) pic post to wall Here are the steps we might perform extract the circle drawing code (which corresponds to the inner for loop). 1. Touch anywhere in the first line of the group of statements we wish to extract. For our example, that is the inner for loop (the one which uses i1 as the index variable). The screen should now look like this: 67

76 ACTIONS, METHODS, REFACTORING VERSION 1 2. Now touch the button labeled select more and the screen changes to look like this: 3. It so happens that everything we want has been selected because it is a single statement (the entire for loop) identified by the red bar on the left and show between the upper and lower rows of buttons. If we wanted to selected additional statements, we could drag the group of statements upward to increase the range of statements to be extracted. In our example, we do not need to do that, so we can proceed to tap the extract button. At this point, we are asked to provide a name for the extracted code (the new action). We enter the desired name, draw circle, and tap another extract button. 4. The screen should change to show the revised Random circles action after the refactoring has been performed. Here is a screenshot: 68

77 VERSION 1 ACTIONS, METHODS, REFACTORING 5. The editor has created an invocation of the new action, with the name we gave it and with whatever parameters were needed to transmit values of variables from the caller (the Random circles action) to the callee (the new draw circle action). At this point, the refactoring has been completed. The modified script should work just as before. Finally, here is a quick way to see the code of the new action (or of any action being invoked in a script). We touch the line of code containing the call to the action. This brings up the edit statement menu, which looks like the following for our example: The go to button will take us to the code for the action invoked in the selected statement. After touching it, the screen will show our refactored action: The code is remarkably similar to the code originally shown in Chapter 2. The only differences are the order in which the parameters appear and the name used for the index variable of the for loop. These would usually be considered to be trivial and unimportant differences. REFACTORING: EXTRACTION OF AN EXPRESSION TO A VARIABLE If you discover that you have constructed an expression whose value you would like to reuse, or if you have a complicated expression which you would like to break up into smaller pieces, this form of refactoring is just what you need. Let s take a small example. Suppose that you have just entered the following script which calculates the length of the diagonal side of a right-angled triangle whose sides are x1 and y2: 69

78 ACTIONS, METHODS, REFACTORING VERSION 1 Perhaps we are now going to extend this script to perform more calculations and we will need to reuse the values of x1*x1 and x2*x2 in some statements we will add to the bottom. Here are the steps to follow. 1. Tap the line containing the expression you wish to extract. In our sample script, that is the line beginning var x := 2. Tap the first element of the expression, which is the first x1 appearing in that line. 3. Swipe from left to right, to highlight all the elements of the selected expression. For our example, the screen should now look like this, with a menu of available editing actions at the bottom: 4. Tap the extract to local button. The statement shown on the screen changes to the following, indicating that a new local variable named x3 has been created. 5. Let s repeat steps 2 to 4 in the same way to extract the expression x2*x2 into a new local variable named x4. 6. We can tap the phone back button to see how the code for our script has been transformed. 70

79 VERSION 1 ACTIONS, METHODS, REFACTORING 7. If we do not like the default names provided for the new local variables, they are easy to rename. One just has to tap any line where the name appears, choose the option to edit the line, select an occurrence of the variable, and there will be a rename button provided on the screen. REFACTORING: PROMOTING A LOCAL VARIABLE TO A GLOBAL DATA ITEM Perhaps we are going to expand the example script by adding many new actions to it and lots of these actions will need access to the values of the new variables x3 and x4. One possibility is to pass x3 and x4 as parameters to the various actions. Another possibility is to convert x3 and x4 into global data items. TouchDevelop provides an easy way to make that transformation. The steps for converting the local variable x3 in the preceding example into a new data item are as follows. 1. Tap the line which declares and initializes the local variable. 2. Tap the edit button. 3. Tap the variable on the left-hand side. An edit menu like that shown below appears. 4. Tap the promote to button. The code displayed on the screen changes to that shown below, indicating that x3 is now being accessed as a global data item. A return to the main screen for the script would show that the script now includes x3 as a data item. 71

80 ACTIONS, METHODS, REFACTORING VERSION 1 72

81 VERSION 1 BASIC GRAPHICS, EVENTS AND GLOBAL DATA CHAPTER 7 BASIC GRAPHICS, EVENTS, AND GLOBAL DATA In this chapter, the graphics features of TouchDevelop are introduced and then combined with scripts when an action, such as turning the phone around, is performed. That topic leads very naturally to scripts which access the sensors built into a Windows phone. Providing code to be executed whenever an event is triggered then leads naturally into scripts which use global data items. 7.1 GRAPHICS FACILITIES 7.2 EVENTS AND SENSORS 7.3 GLOBAL DATA 7.1 GRAPHICS FACILITIES The phone s screen is composed of many dots which can be illuminated in different colors. All characters, all lines, all pictures seen on the screen are displayed as patterns of these dots where the phone s software has selected the color and intensity for each dot. Graphics programming is, in effect, a matter of writing code to set the color and intensity of each dot in an area of the screen. Anyone who has had some previous experience with graphics programming can skip the following brief introduction to the subject. After that introduction, we will move on to the facilities for graphics programming provided in TouchDevelop. COMPUTER GRAPHICS TERMINOLOGY Each dot on the screen is known as a PICTURE ELEMENT and that term is usually abbreviated to PIXEL or to PEL. We will use the term pixel. The TouchDevelop API for setting the pixel s color and intensity uses a triple of three numbers. In most graphics software, these three numbers are one-byte integers in the range 0 to 255, and they specify the intensity of the red, green and blue components of the color separately. However TouchDevelop scales these numbers to be in the range 0.0 to 1.0. The triple of three numbers is commonly called an RGB VALUE. An integer value of 0 means that the color component has zero intensity and a value of 1.0 means maximum intensity. Some typical combinations of integers as RGB values in TouchDevelop are: 73

82 BASIC GRAPHICS, EVENTS AND GLOBAL DATA VERSION 1 (0.0, 0.0, 0.0) black (0.0, 1.0, 0.0) green (1.0, 1.0, 1.0) white (0.0, 0.0, 1.0) blue (0.5, 0.5, 0.5) gray (1.0, 1.0, 0.0) yellow (1.0, 0,0, 0.0) red (1.0, 0.0, 1.0) purple The pixels on the screen are arranged in a rectangular grid. Each pixel has a coordinate position in this grid given by an x value and a y value. The x values start at 0 and increase from left-to-right across the screen; the y values start at 0 and increase from top to bottom down the screen. (Note that y-axis values grow in the opposite direction to how you would normally draw a graph.) The size of the displayable area on the screen is exactly 480 pixels wide by 800 pixels high for a Windows 7 phone. This means that the x and y coordinates can range from (0,0) in the top-left corner to (479,799) in the bottom right corner, as shown on the right. A TRIVIAL GRAPHICS PROGRAM Figure 7.1: Trivial graphics script A short graphics program was used as an example in Chapter 2. It begins by creating a new Picture value and assigning it to variable pic. It is an array of pixel values 480 wide and 300 wide. The width is the maximum which can be displayed on a Windows phone. The height of 300 is much less than the maximum 800 allowed for the phone. The pixels are initialized to be white. The second statement draws a solid rectangle in the Picture array. The top left corner of the rectangle is at (10,10) i.e. 10 pixels in from the left and 10 pixels down from the top. The width of the rectangle is 200 pixels and its height is 100 pixels. The fifth argument of 0 means that we do not want to rotate the rectangle before drawing it onto the picture object. (To be more precise, it is rotated by 0 degrees.) The last parameter specified the color to use for the rectangle. The colors red value is equivalent to using (1.0,0.0,0.0) as the RGB value for the pixels, and is much more readable. 74

83 VERSION 1 BASIC GRAPHICS, EVENTS AND GLOBAL DATA The third statement draws a solid ellipse inside the Picture array. One has to imagine that the ellipse fits inside a rectangle whose top left corner is at the coordinates (270,190). The width and height of that ellipse are set to be 200 and 100 respectively. Again, we rotate that containing rectangle by 0 degrees. The color for the ellipse is chosen to be blue. The fourth statement draws the four sides of a rectangle at approximately the extreme edges of the Picture array. The thickness of the lines used for the four sides has been set at 3 pixels. The color of the lines is whatever has been chosen in the phone s settings as the accent color; for the screen shot shown below, that accent color is magenta. The fifth statement draws a line from the bottom left corner up towards the top right corner, and the thickness of the line is chosen to be 3 pixels wide. Finally the last statement sends the picture to be displayed on the wall. A screen shot of our program s output appears in Figure 7.2. Figure 7.2: Output from trivial graphics script MORE DETAILS ABOUT PICTURES Any photograph held on the phone or downloadable from the web is held as a Picture value too. This means that you can write scripts which transform the photograph or overwrite them in some way. Anything is possible given enough effort spent developing a script. Just to introduce you to the possibilities, Figure 7.3 shows a script which first prompts the user to enter a string (to use as the value of the parameter msg), then asks the user to select a photograph from amongst those on the phone, overprints a text message diagonally across the picture from the bottom left to the top right and finally displays the picture. 75

84 BASIC GRAPHICS, EVENTS AND GLOBAL DATA VERSION 1 Figure 7.3: Script to Overprint a Photograph The script has to make some calculations to determine a suitable size for the characters in the message being displayed and what angle to draw the text at, if we want that text to be along the diagonal. The character size calculation is very approximate (as not all characters are the same width) and the formula used here was found by trial and error. The angle of the diagonal is found by computing the arctangent of height/width for the image. The math function atan2 provided in the TouchDevelop API performs that calculation but returns the result in radians. The angle argument to the draw text method requires the angle in degrees however, so a call to the rad to deg conversion function is needed too. Finally a minus sign is needed in front because we are drawing the text in a direction which ascends from left to right which corresponds to an anticlockwise rotation, whereas the draw text method normally performs a clockwise rotation on the text. A sample output from this script is shown in Figure 7.4. Note that the photograph selected for display in Figure 7.4 is too large to fit on the screen. Its width is 800 pixels yet the screen itself is only 480 pixels wide. The post to wall method scaled the image by a factor of 480/800 in both dimensions so that it would fit without having to scroll the image from side to side. 76

85 VERSION 1 BASIC GRAPHICS, EVENTS AND GLOBAL DATA Figure 7.4: Output from the Overprint Photograph Script Table 7.1 provides a description of most of the methods available for the Picture datatype. Table 7.1: Useful Picture Methods Method Description Operations on the Image as a Whole height: Number Returns the picture height in pixels width: Number Returns the picture width in pixels invert: Picture Inverts the R,G,B color components of every pixel clear(col:color): Nothing Sets all pixels to color col clone: Picture Returns a duplicate of the picture post to wall: Nothing Displays the picture on the screen, resizing it if necessary to fit within the maximum width of 480 pixels and a maximum height of 800 pixels. crop(x:number, y:number, w:number, Crops the picture to have width w and height h, selecting h:number): Nothing a subimage whose top left corner is at position x,y blend(other:picture, x:number, Overwrites this picture with picture, other, putting its top y:number, angle:number, left corner at position x,y and rotating about that corner alpha:number): Nothing by angle degrees in a clockwise direction; alpha is used as the transparency of all pixels in the other picture. resize(w:number, h:number): Nothing Scales the picture to have width w and height h 77

86 BASIC GRAPHICS, EVENTS AND GLOBAL DATA VERSION 1 Shape Drawing Methods draw ellipse(x:number, y:number, Draws the largest ellipse which fits inside a rectangle w:number, h:number, angle:number, with width w and height h; the top left corner of the rectangle is at position x,y; the rectangle is rotated about the c:color, th:number): Nothing top left corner by angle degrees in a clockwise direction; the line has a thickness of th pixels and is drawn in color c. draw line(x1:number, y1:number, Draws a line from position x1,y1 to position x2,y2; the x2:number, y2:number, c:color, line has thickness of th pixels and is drawn in color c. th:number): Nothing draw rect(x:number, y:number, w:number, h:number, angle:number, c:color, th:number): Nothing draw text(x:number, y:number, txt:string, fs:number, angle:number, c:color): Nothing fill ellipse(x:number, y:number, w:number, h:number, angle:number, c:color): Number fill rect(x:number, y:number, w:number, h:number, angle:number, c:color): Nothing pixel(x:number, y:number): Color set pixel(x:number, y:number, c:color): Nothing Draws a rectangle whose top left corner is at position x,y; it has width w and height h; the rectangle is rotated about the top left corner by angle degrees in a clockwise direction; the line has a thickness of th pixels and is drawn in color c. Draws text as pixels in color c on the picture; the top left of the first character is at position x,y; the size used for the characters is fs; the text is rotated by angle degrees about the x,y position. Like draw ellipse except that the ellipse is drawn as a solid object (not as a line surrounding an elliptically shaped area) Like draw rect except that the rectangle is drawn as a solid object (not as four lines surrounding a rectangular area) Access to Pixels Returns the color of the pixel at position x,y Sets the pixel at position x,y to have color c WORKING WITH PIXELS As explained earlier, each pixel has a color and an intensity determined by a triple of three numbers, the RGB values. There is an additional number attached to each pixel which comes into play if we want to superimpose one picture on top of another. This additional integer is known as the AL- PHA value and controls the degree of transparency of the pixel. Suppose that we want to overlay part of picture A with picture B. Should the pixels from Picture B replace the pixels of A? This is usually known as knockout overprinting. It means that you cannot see through the pixels from picture B and see any remnants of picture A in the overlaid area. However, perhaps the colors of the B picture pixels should be blended with the pixels of the A picture so 78

87 VERSION 1 BASIC GRAPHICS, EVENTS AND GLOBAL DATA that you can see both the A and B images combined? The alpha values associated with the B pixels determine their degrees of transparency. If alpha is 1.0, the pixel is fully opaque and the B pixel will knockout (replace) the A pixel. If alpha is 0.0, the pixel is fully transparent and no trace of picture B will be seen when overlaid on picture A. Intermediate values for alpha result in partial transparency for the B picture. Given a picture referenced by variable pic, the pixel at coordinates x,y can be retrieved by a statement like the following. var col := pic pixel(x,y) The value so obtained has the datatype Color. That value can be decomposed into its A (alpha), R, G and B components with statements like these: var red component := col R var green component := col G var blue component := col B var alpha component := col A We can change these color components in any way we like, as long as the values stay in the 0.0 to 1.0 range, and then recombine them to create a new color which can be stored back into the picture as a changed pixel value. For example, the following code inverts the color intensities, giving an effect similar to creating a color negative image: red component := red component green component := green component blue component := blue component col := colors from argb(alpha component, red component, green component, blue component) pic set pixel(x, y, col) However that particular sequence of statements would rarely be needed because the Picture datatype has an invert method which performs exactly that operation to every pixel in the image. Many of the methods used for working with colors and individual pixels are listed below in Table 7.2. They are accessed from the service named colors. For example, var y := colors yellow declares variable y to have the type Color and initializes it to the yellow color. 79

88 BASIC GRAPHICS, EVENTS AND GLOBAL DATA VERSION 1 Table 7.2: Methods provided by the colors Service Method Description Composing and Decomposing Color Values from argb(alpha:number, r:number, Constructs a color from the alpha and RGB values, which g:number, b:number): Color must all be in the range 0.0 to 1.0 from rgb(r:number, g:number, Constructs a color from the RGB values provided; the alpha component is set to 1.0 (totally opaque) b:number): Color Access to the Phone s Theme Colors accent: Color background: Color foreground: Color chrome: Color subtle: Color Returns the accent, background, foreground, chrome and subtle (light gray) colors selected for the phone s theme in its Settings menu Standard Colors black: Color blue: Color brown: Color cyan: Color dark gray: Color gray: Color green: Color light gray: Color magenta: Color orange: Color purple: Color red: Color white: Color yellow: Color Obtain standard colors by their usual names. Obtaining Special Colors random: Color linear gradient(c1:color, c2:color, alpha:number): Color Returns a random (opaque) color Computes a color in between c1 and c2 where c2 overlays c1 with the specified alpha factor for transparency. 7.2 EVENTS AND SENSORS The Windows phone contains a number of sensors, such as an accelerometer, which can trigger events that get passed on to the TouchDevelop script. In addition, a script which implements an interactive game needs to respond when the user taps certain items on the screen, and those taps can also trigger events. 80

89 VERSION 1 BASIC GRAPHICS, EVENTS AND GLOBAL DATA The various kinds of events recognized by TouchDevelop are listed in Table 7.3. Sensors are covered in some more detail in Chapter 8 as well as more examples which use events. The events grouped in the Game Playing category will be covered only in Chapter 9. Table 7.3: Events in TouchDevelop Scripts Event shake phone face up phone face down phone portrait phone landscape left phone landscape right active song changed camera button pressed camera button half pressed camera button released tap wall XX(item: XX) gameloop player state changed tap board: b(x,y) swipe: board: b(x, y, dx, dy) tap sprite in s(sprite, index, x, y) swipe sprite in s(sprite, index, x, y, delta x, delta y) drag sprite in s(sprite, index, x, y, delta x, delta y) Description Phone Movement Events Triggered when the phone is shaken Triggered when the phone is turned so that it is face up Triggered when the phone is turned so that it is face down Triggered when the phone is turned so the screen in portrait mode (such as when the phone is vertical) Triggered when the phone is turned so that its left side is facing down Triggered when the phone is turned so that its right side is facing down Media Events The names of these events describe the events Tap Wall Events XX represents any of the TouchDevelop datatypes, such as String or Location or Number Map, etc. The event is triggered when a user taps a display of a value of type XX on the wall (i.e. the screen). The value is passed as a parameter to the event. Game Playing Events An event which is triggered by a timer approximately every 50ms Triggered when a global data item named b with type Board is tapped; x and y are the coordinates of the tap. Similar to tap board, except that it is triggered by a swiping action starting at position x,y and with a distance vector dx,dy Sprites will be covered in Chapter 9. (They are graphics objects which can move around on the screen.) 81

90 BASIC GRAPHICS, EVENTS AND GLOBAL DATA VERSION 1 EXAMPLE EVENT HANDLING SCRIPT: PHONE ORIENTATION A script can optionally include code which is executed whenever a particular kind of event happens. As a simple example, let us construct a script which displays the words Portrait and Landscape in large letters on the screen according to the phone s current orientation. To reuse some of the graphics code covered earlier in this chapter, we will create Picture values and write text with suitable orientations for display into the pictures and display the pictures in the event code. The code for the main action and all three events is shown in Figure 7.5. As you can see, the main action has got absolutely nothing to do. Even though control returns from the main action, the script stays active waiting for events. The only way to stop this script is to tap the phone back button (or to tap the Windows button to exit from TouchDevelop completely). Figure 7.5: Code for the Orientation Event Script Two of the screen displays produced by this script as the phone is rotated are shown below in Figure

91 VERSION 1 BASIC GRAPHICS, EVENTS AND GLOBAL DATA Figure 7.6: Some Output Displayed by the Orientation Script 7.3 GLOBAL DATA Sometimes an event in a script needs to save information which is used later by an action or by another invocation of an event (perhaps the same event, perhaps a different event). Where can such information be saved? The only reasonable answer is to use a GLOBAL DATA VARIABLE. We have already seen some example programs which use global data items. Let us look at one more. EXAMPLE SCRIPT: A PEDOMETER If you carry your Windows phone with you when jogging or walking briskly, the phone s sensors should trigger a SHAKE event each time you take one step. We can therefore write a simple script which records how many steps you take, incrementing a counter each time the shake event occurs. With a little more coding, we can compute the number of steps per minute. By using access to the phone s GPS location, we can also compute your average speed. However that programming feature does not need to use any event code, so we will omit that feature in this version of the program. When we begin creating the Pedometer script, TouchDevelop provides a default action named main and that is all. No events and no global data items exist for the script. We could tap the plus button to the right of the data icon to create a global data item for the number of steps taken, but let s do it another way. We can use the promote to global data item form of refactoring explained in Chapter 6. The first thing we do in creating the script is to edit the code for the main action. We add the statement var steps := 0 83

CHAPTER 2 EDITING IN TOUCHDEVELOP

CHAPTER 2 EDITING IN TOUCHDEVELOP VERSION 1 CHAPTER 2 In this chapter we describe how to set up TouchDevelop on your phone, how to enter scripts from scratch, and how to extend existing scripts. At the end of the chapter, you should be

More information

CHAPTER 1 WHAT IS TOUCHDEVELOP?

CHAPTER 1 WHAT IS TOUCHDEVELOP? CHAPTER 1 In this chapter we present an overview of how TouchDevelop works within your phone and the larger ecosystem the cloud, the communities you are involved in, and the websites you normally access.

More information

Chapter 2 Editing in TouchDevelop

Chapter 2 Editing in TouchDevelop Chapter 2 In this chapter we describe how to set up TouchDevelop on your phone, how to enter scripts from scratch, and how to extend existing scripts. At the end of the chapter, you should be familiar

More information

touchdevelop R Nigel Horspool University of Victoria Judith Bishop Arjmand Samuel Nikolai Tillmann Michał Moskal Jonathan de Halleux Manuel Fähndrich

touchdevelop R Nigel Horspool University of Victoria Judith Bishop Arjmand Samuel Nikolai Tillmann Michał Moskal Jonathan de Halleux Manuel Fähndrich touchdevelop programming on a phone R Nigel Horspool University of Victoria Judith Bishop Arjmand Samuel Nikolai Tillmann Michał Moskal Jonathan de Halleux Manuel Fähndrich Microsoft Research Version 1.1

More information

touchdevelop tutorial

touchdevelop tutorial touchdevelop tutorial This document was written for touchdevelop v2.8 - more information at. This document is a step-by-step walkthrough of the in-app touchdevelop tutorial. This tutorial assumes little

More information

CHAPTER 6 ACTIONS, METHODS, REFACTORING

CHAPTER 6 ACTIONS, METHODS, REFACTORING VERSION 1 CHAPTER 6 In this chapter we cover ACTIONS in more depth and show how to easily create additional actions in a script by using a technique known as REFACTORING. The chapter covers two forms of

More information

TouchDevelop. Programming on the Go

TouchDevelop. Programming on the Go TouchDevelop Programming on the Go TouchDevelop Programming on the Go R Nigel Horspool University of Victoria Nikolai Tillmann Microsoft Research TouchDevelop: Programming on the Go by R. Nigel Horspool

More information

Windows 10: Part 1. Updated: May 2018 Price: $2.00

Windows 10: Part 1. Updated: May 2018 Price: $2.00 Windows 10: Part 1 Updated: May 2018 Price: $2.00 A Special Note on Terminology Windows 10 accepts both mouse and touch commands. This means that you could use either mouse clicks or touch gestures interchangeably.

More information

Game Board: Enabling Simple Games in TouchDevelop

Game Board: Enabling Simple Games in TouchDevelop Game Board: Enabling Simple Games in TouchDevelop Manuel Fähndrich Microsoft Research One Microsoft Way, Redmond WA 98052, USA maf@microsoft.com February 23, 2012 Abstract TouchDevelop is a novel application

More information

Google Drive. Lesson Planet

Google Drive. Lesson Planet Google Drive Lesson Planet 2014 www.lessonplanet.com Introduction Trying to stay up to speed with the latest technology can be exhausting. Luckily this book is here to help, taking you step by step through

More information

Prezi: Moving beyond Slides

Prezi: Moving beyond Slides [ Prezi: Moving beyond Slides ] by: Charina Ong Centre for Development of Teaching and Learning National University of Singapore Table of Contents About the Workshop... i Workshop Objectives... i Session

More information

Section 1. System Technologies and Implications. Modules. Introduction to computers. File management. ICT in perspective. Extended software concepts

Section 1. System Technologies and Implications. Modules. Introduction to computers. File management. ICT in perspective. Extended software concepts Section 1 System Technologies and Implications Modules 1.1 Introduction to computers 1.2 Software 1.3 Hardware 1.4 File management 1.5 ICT in perspective 1.6 Extended software concepts 1.7 Extended hardware

More information

FrontPage 98 Quick Guide. Copyright 2000 Peter Pappas. edteck press All rights reserved.

FrontPage 98 Quick Guide. Copyright 2000 Peter Pappas. edteck press All rights reserved. Master web design skills with Microsoft FrontPage 98. This step-by-step guide uses over 40 full color close-up screen shots to clearly explain the fast and easy way to design a web site. Use edteck s QuickGuide

More information

Windows 10: Part 2. Updated: May 2018 Price: $1.80

Windows 10: Part 2. Updated: May 2018 Price: $1.80 Windows 10: Part 2 Updated: May 2018 Price: $1.80 A Special Note on Terminology Windows 10 accepts both mouse and touch commands. This means that you could either use mouse clicks or touch gestures interchangeably.

More information

Chapter 2: Android Device Basics

Chapter 2: Android Device Basics Chapter 2: Android Device Basics 1 Chapter 2: Android Device Basics Android devices have a ton of cool features and are really fun to play with, but they have a very practical side as well. We ll touch

More information

A new clients guide to: Activating a new Studio 3.0 Account Creating a Photo Album Starting a Project Submitting a Project Publishing Tips

A new clients guide to: Activating a new Studio 3.0 Account Creating a Photo Album Starting a Project Submitting a Project Publishing Tips Getting Started With Heritage Makers A Guide to the Heritage Studio 3.0 Drag and Drop Publishing System presented by Heritage Makers A new clients guide to: Activating a new Studio 3.0 Account Creating

More information

A Document Created By Lisa Diner Table of Contents Western Quebec School Board October, 2007

A Document Created By Lisa Diner Table of Contents Western Quebec School Board October, 2007 Table of Contents A Document Created By Lisa Diner Western Quebec School Board October, 2007 Table of Contents Some Basics... 3 Login Instructions... 4 To change your password... 6 Options As You Login...

More information

Welcome to Book Display Widgets

Welcome to Book Display Widgets Welcome to Book Display Widgets Book Display Widgets allow you to create virtual book displays on your website, where covers link to that item s record in your catalog. As a subscriber to Ebook Central

More information

Spark Quick Reference Guide

Spark Quick Reference Guide Spark Quick Reference Guide Making Teamwork Simpler Spark simplifies teamwork by making communication seamless. Send messages, share files, and meet with different teams, all in one place. Easily pull

More information

Survey of Math: Excel Spreadsheet Guide (for Excel 2016) Page 1 of 9

Survey of Math: Excel Spreadsheet Guide (for Excel 2016) Page 1 of 9 Survey of Math: Excel Spreadsheet Guide (for Excel 2016) Page 1 of 9 Contents 1 Introduction to Using Excel Spreadsheets 2 1.1 A Serious Note About Data Security.................................... 2 1.2

More information

5. LAPTOP PROCEDURES

5. LAPTOP PROCEDURES 5. LAPTOP PROCEDURES Introduction This next section of the user guide will identify core essentials regarding your laptop turning it on, running the program, running the questionnaire, submitting the data,

More information

ipad app 2014 Attainment Company, Inc.

ipad app 2014 Attainment Company, Inc. ipad app 2014 Attainment Company, Inc. Table of Contents Overview... 1 Quick... Start 2... 2 Logging In... 2 Directories... 4 Reading Stories... 5 Adding a User Seeing... and Hearing the Stories 6... 6

More information

OpenForms360 Validation User Guide Notable Solutions Inc.

OpenForms360 Validation User Guide Notable Solutions Inc. OpenForms360 Validation User Guide 2011 Notable Solutions Inc. 1 T A B L E O F C O N T EN T S Introduction...5 What is OpenForms360 Validation?... 5 Using OpenForms360 Validation... 5 Features at a glance...

More information

The Fundamentals. Document Basics

The Fundamentals. Document Basics 3 The Fundamentals Opening a Program... 3 Similarities in All Programs... 3 It's On Now What?...4 Making things easier to see.. 4 Adjusting Text Size.....4 My Computer. 4 Control Panel... 5 Accessibility

More information

LEARN IT 1. Digital Identity Management Community Platform

LEARN IT 1. Digital Identity Management Community Platform LEARN IT 1 Digital Identity Management Community Platform Note: This document is for Fox BBA in MIS majors (only). The instructions and software described below will not work for others. Please contact

More information

Click Here to Begin OS X. Welcome to the OS X Basics Learning Module.

Click Here to Begin OS X. Welcome to the OS X Basics Learning Module. OS X Welcome to the OS X Basics Learning Module. This module will teach you the basic operations of the OS X operating system, found on the Apple computers in the College of Technology computer labs. The

More information

Welcome to Introduction to Microsoft Excel 2010

Welcome to Introduction to Microsoft Excel 2010 Welcome to Introduction to Microsoft Excel 2010 2 Introduction to Excel 2010 What is Microsoft Office Excel 2010? Microsoft Office Excel is a powerful and easy-to-use spreadsheet application. If you are

More information

Outlook Web Access. In the next step, enter your address and password to gain access to your Outlook Web Access account.

Outlook Web Access. In the next step, enter your  address and password to gain access to your Outlook Web Access account. Outlook Web Access To access your mail, open Internet Explorer and type in the address http://www.scs.sk.ca/exchange as seen below. (Other browsers will work but there is some loss of functionality) In

More information

Welcome to Book Display Widgets

Welcome to Book Display Widgets Welcome to Book Display Widgets Book Display Widgets allow you to create virtual book displays on your website, where covers link to that item s record in your catalog. Bring your own lists of books, or

More information

EXCEL BASICS: MICROSOFT OFFICE 2007

EXCEL BASICS: MICROSOFT OFFICE 2007 EXCEL BASICS: MICROSOFT OFFICE 2007 GETTING STARTED PAGE 02 Prerequisites What You Will Learn USING MICROSOFT EXCEL PAGE 03 Opening Microsoft Excel Microsoft Excel Features Keyboard Review Pointer Shapes

More information

This document should only be used with the Apple Macintosh version of Splosh.

This document should only be used with the Apple Macintosh version of Splosh. Splosh 1 Introduction Splosh is an easy to use art package that runs under both Microsoft Windows and the Macintosh Mac OS Classic or Mac OS X operating systems. It should however be noted that the Apple

More information

Bluetooth Keyboard Commands with VoiceOver on the ipad

Bluetooth Keyboard Commands with VoiceOver on the ipad Bluetooth Keyboard Commands with VoiceOver on the ipad ios 9.2 Chapter 5: Editing and Manipulating Text in Editable Text Fields using Bluetooth Keyboard Commands (Quick Nav is OFF) Module Objectives 5.1

More information

Excel Basics Rice Digital Media Commons Guide Written for Microsoft Excel 2010 Windows Edition by Eric Miller

Excel Basics Rice Digital Media Commons Guide Written for Microsoft Excel 2010 Windows Edition by Eric Miller Excel Basics Rice Digital Media Commons Guide Written for Microsoft Excel 2010 Windows Edition by Eric Miller Table of Contents Introduction!... 1 Part 1: Entering Data!... 2 1.a: Typing!... 2 1.b: Editing

More information

Introduction to Windows 10 Part 1

Introduction to Windows 10 Part 1 Introduction to Windows 10 Part 1 Higham and Rushden U3A In this presentation we will have a quick look at the following: Starting Windows 10 Typical desktop layout Start screen Cortana and Search Taskbar

More information

Go paperless by using OneNote 2013

Go paperless by using OneNote 2013 Work Smart by Microsoft IT Go paperless by using OneNote 2013 Customization note: This document contains guidance and/or step-by-step installation instructions that can be reused, customized, or deleted

More information

Table of Contents. Revu ipad. v3.6. Navigation. Document Manager. File Access. Markups. Signature Tool. Field Verification Measurements

Table of Contents. Revu ipad. v3.6. Navigation. Document Manager. File Access. Markups. Signature Tool. Field Verification Measurements Table of Contents Navigation Document Manager File Access Markups Signature Tool Field Verification Measurements Editing Properties Tool Sets & the Tool Chest Markups List Forms Studio Sessions Studio

More information

Workbook Also called a spreadsheet, the Workbook is a unique file created by Excel. Title bar

Workbook Also called a spreadsheet, the Workbook is a unique file created by Excel. Title bar Microsoft Excel 2007 is a spreadsheet application in the Microsoft Office Suite. A spreadsheet is an accounting program for the computer. Spreadsheets are primarily used to work with numbers and text.

More information

BrainStorm Quick Start Card for Microsoft OneDrive for Business

BrainStorm Quick Start Card for Microsoft OneDrive for Business BrainStorm Quick Start Card for Microsoft OneDrive for Business mso.harvard.edu Changing the Way the World Works Clear the path for your productivity goals! Using Microsoft OneDrive for Business, you have

More information

EXCEL BASICS: MICROSOFT OFFICE 2010

EXCEL BASICS: MICROSOFT OFFICE 2010 EXCEL BASICS: MICROSOFT OFFICE 2010 GETTING STARTED PAGE 02 Prerequisites What You Will Learn USING MICROSOFT EXCEL PAGE 03 Opening Microsoft Excel Microsoft Excel Features Keyboard Review Pointer Shapes

More information

Tutorial 1: Unix Basics

Tutorial 1: Unix Basics Tutorial 1: Unix Basics To log in to your ece account, enter your ece username and password in the space provided in the login screen. Note that when you type your password, nothing will show up in the

More information

AAG Mobile App User Manual

AAG Mobile App User Manual AAG Mobile App User Manual Tired of carrying a large printed program around the AAG Annual Meeting? Want to easily organize your AAG session schedule in a digital calendar format? Looking to save some

More information

Getting Started with Onshape

Getting Started with Onshape Getting Started with Onshape First Edition Elise Moss, Authorized Onshape Partner SDC PUBLICATIONS Better Textbooks. Lower Prices. www.sdcpublications.com Powered by TCPDF (www.tcpdf.org) Visit the following

More information

User Manual. pdoc Pro Client for Windows. Version 2.1. Last Update: March 20, Copyright 2018 Topaz Systems Inc. All rights reserved.

User Manual. pdoc Pro Client for Windows. Version 2.1. Last Update: March 20, Copyright 2018 Topaz Systems Inc. All rights reserved. User Manual pdoc Pro Client for Windows Version 2.1 Last Update: March 20, 2018 Copyright 2018 Topaz Systems Inc. All rights reserved. For Topaz Systems, Inc. trademarks and patents, visit www.topazsystems.com/legal.

More information

Math Dr. Miller - Constructing in Sketchpad (tm) - Due via by Friday, Mar. 18, 2016

Math Dr. Miller - Constructing in Sketchpad (tm) - Due via  by Friday, Mar. 18, 2016 Math 304 - Dr. Miller - Constructing in Sketchpad (tm) - Due via email by Friday, Mar. 18, 2016 As with our second GSP activity for this course, you will email the assignment at the end of this tutorial

More information

Adobe Illustrator. Quick Start Guide

Adobe Illustrator. Quick Start Guide Adobe Illustrator Quick Start Guide 1 In this guide we will cover the basics of setting up an Illustrator file for use with the laser cutter in the InnovationStudio. We will also cover the creation of

More information

MicroStrategy Academic Program

MicroStrategy Academic Program MicroStrategy Academic Program Creating a center of excellence for enterprise analytics and mobility. HOW TO DEPLOY ENTERPRISE ANALYTICS AND MOBILITY ON AWS APPROXIMATE TIME NEEDED: 1 HOUR In this workshop,

More information

Getting to Know Windows 10. Handout

Getting to Know Windows 10. Handout Handout Handout Session Overview We re excited to share the exciting new features of Windows 10 and look forward to answering any questions in real time as we learn more about this updated platform together.

More information

Version Android User's Guide. May-02-13

Version Android User's Guide. May-02-13 Version 12.5 Android User's Guide May-02-13 Table of Contents Chapter 1 Overview 1 Getting Help 2 Other Resources 3 Documentation and Learning Resources 3 Technical Support 4 Community 4 Blackboard Collaborate

More information

PDF Expert for ipad User guide

PDF Expert for ipad User guide PDF Expert for ipad User guide 2011 Readdle Inc. 2 Contents Introduction Chapter 1: Copying documents to PDF Expert USB file transfer using itunes File Sharing Saving attachments from Mail and other ipad

More information

AGENT123. Full Q&A and Tutorials Table of Contents. Website IDX Agent Gallery Step-by-Step Tutorials

AGENT123. Full Q&A and Tutorials Table of Contents. Website IDX Agent Gallery Step-by-Step Tutorials AGENT123 Full Q&A and Tutorials Table of Contents Website IDX Agent Gallery Step-by-Step Tutorials WEBSITE General 1. How do I log into my website? 2. How do I change the Meta Tags on my website? 3. How

More information

Windows 10. Page 1 of 15

Windows 10. Page 1 of 15 Windows 10 Microsoft Windows Microsoft makes the Windows operating system used in many computers. The operating system is a set of instructions that tells your computer how to run and how to manage the

More information

Useful Google Apps for Teaching and Learning

Useful Google Apps for Teaching and Learning Useful Google Apps for Teaching and Learning Centre for Development of Teaching and Learning (CDTL) National University of Singapore email: edtech@groups.nus.edu.sg Table of Contents About the Workshop...

More information

Art of the Apps Monthly Membership. JUNE 2018 Mobile App: Adobe Spark Post. at Scrapaneers.com. Companion Handouts

Art of the Apps Monthly Membership. JUNE 2018 Mobile App: Adobe Spark Post. at Scrapaneers.com. Companion Handouts Art of the Apps Monthly Membership Page 1 of 19 at Scrapaneers.com JUNE 2018 Mobile App: Adobe Spark Post Table of Contents Table of Contents 2 Welcome to Art of the Apps Monthly Membership June 2018 3

More information

The ICT4me Curriculum

The ICT4me Curriculum The ICT4me Curriculum About ICT4me ICT4me is an after school and summer curriculum for middle school youth to develop ICT fluency, interest in mathematics, and knowledge of information, communication,

More information

The ICT4me Curriculum

The ICT4me Curriculum The ICT4me Curriculum About ICT4me ICT4me is an after school and summer curriculum for middle school youth to develop ICT fluency, interest in mathematics, and knowledge of information, communication,

More information

GUARD1 PLUS Manual Version 2.8

GUARD1 PLUS Manual Version 2.8 GUARD1 PLUS Manual Version 2.8 2002 TimeKeeping Systems, Inc. GUARD1 PLUS and THE PIPE are registered trademarks of TimeKeeping Systems, Inc. Table of Contents GUARD1 PLUS... 1 Introduction How to get

More information

Forms for Android Version Manual. Revision Date 12/7/2013. HanDBase is a Registered Trademark of DDH Software, Inc.

Forms for Android Version Manual. Revision Date 12/7/2013. HanDBase is a Registered Trademark of DDH Software, Inc. Forms for Android Version 4.6.300 Manual Revision Date 12/7/2013 HanDBase is a Registered Trademark of DDH Software, Inc. All information contained in this manual and all software applications mentioned

More information

Photoshop World 2018

Photoshop World 2018 Photoshop World 2018 Unlocking the Power of Lightroom CC on the Web with Rob Sylvan Learn how to leverage the cloud-based nature of Lightroom CC to share your photos in a way that will give anyone with

More information

DOING MORE WITH EXCEL: MICROSOFT OFFICE 2013

DOING MORE WITH EXCEL: MICROSOFT OFFICE 2013 DOING MORE WITH EXCEL: MICROSOFT OFFICE 2013 GETTING STARTED PAGE 02 Prerequisites What You Will Learn MORE TASKS IN MICROSOFT EXCEL PAGE 03 Cutting, Copying, and Pasting Data Basic Formulas Filling Data

More information

Introduction to Google Apps for Education! page 1. Introduction to GAFE Documents (Drive)! page 4. Introduction to GAFE Calendars!

Introduction to Google Apps for Education! page 1. Introduction to GAFE Documents (Drive)! page 4. Introduction to GAFE Calendars! 2014 Table of Contents Introduction to Google Apps for Education! page 1 Introduction to GAFE Documents (Drive)! page 4 Introduction to GAFE Calendars! page 14 Introduction to GAFE GMail! page 27 Dublin

More information

Duplicate and customize an existing kahoot to fit your needs. Launch and host a kahoot game in your class

Duplicate and customize an existing kahoot to fit your needs. Launch and host a kahoot game in your class Course 1 Get started and discover with Kahoot! Welcome to the first course of the Kahoot! Certified program! Before we get started, please be sure not to share these guides further, as they are only for

More information

Apps Every College Student Should Have

Apps Every College Student Should Have Apps Every College Student Should Have Evernote Evernote makes it easy to remember things big and small from your everyday life using your computer, phone, tablet and the web. (All Platforms) myhomework

More information

FAQs. A guide for school app administrators

FAQs. A guide for school app administrators FAQs A guide for school app administrators Introduction myschoolapp is a simple and cost-effective way to engage with today s mobile parents and carers who run their lives from their phones. It helps you

More information

LionMail. for Administrative Assistants

LionMail. for Administrative Assistants LionMail for Administrative Assistants If you directly manage email on behalf of others or just send and receive dozens (or hundreds!) of messages a day in your role as an administrative assistant, this

More information

Part 1: Understanding Windows XP Basics

Part 1: Understanding Windows XP Basics 542362 Ch01.qxd 9/18/03 9:54 PM Page 1 Part 1: Understanding Windows XP Basics 1: Starting Up and Logging In 2: Logging Off and Shutting Down 3: Activating Windows 4: Enabling Fast Switching between Users

More information

1. Introduction P Package Contents 1.

1. Introduction P Package Contents 1. 1 Contents 1. Introduction ------------------------------------------------------------------------------- P. 3-5 1.1 Package Contents 1.2 Tablet Overview 2. Using the Tablet for the first time ---------------------------------------------------

More information

WINDOWS 8 CHEAT SHEET

WINDOWS 8 CHEAT SHEET WINDOWS 8 CHEAT SHEET FIVE BIG CHANGES IN WINDOWS 8 Windows 8 looks and behaves much differently from previous versions of Windows. Remember these five big changes, and you ll be well prepared for Windows

More information

End User Guide. 2.1 Getting Started Toolbar Right-click Contextual Menu Navigation Panels... 2

End User Guide. 2.1 Getting Started Toolbar Right-click Contextual Menu Navigation Panels... 2 TABLE OF CONTENTS 1 OVERVIEW...1 2 WEB VIEWER DEMO ON DESKTOP...1 2.1 Getting Started... 1 2.1.1 Toolbar... 1 2.1.2 Right-click Contextual Menu... 2 2.1.3 Navigation Panels... 2 2.1.4 Floating Toolbar...

More information

Table of Contents Getting Started... 2 Logging in to Digication... 2 Creating an eportfolio Settings... 4 Digication Menu Screen...

Table of Contents Getting Started... 2 Logging in to Digication... 2 Creating an eportfolio Settings... 4 Digication Menu Screen... Table of Contents Getting Started... 2 Logging in to Digication... 2 Creating an eportfolio... 2-3 Settings... 4 Digication Menu Screen... 4 Copy or Delete an eportfolio... 5 Publishing an eportfolio...

More information

Android (A1000) Y4 Classrooms: User Guide

Android (A1000) Y4 Classrooms: User Guide Android (A1000) Y4 Classrooms: User Guide Provided by the SDUSD Ed Tech Team i21 2014 Teachers - Version 3.25.2014 Table of Contents Basic Functionality... Navigation Tips... Taking a Screenshot... Finding

More information

Realize Reader. User Guide

Realize Reader. User Guide Realize Reader User Guide ios Version 3.0.0 7/19/2017 Contents Contents 2 What Is Realize Reader? 4 Access Realize Reader 4 Access Realize Reader Through Realize 4 Bookshelf 5 View Information About a

More information

Grade 8 FSA Mathematics Practice Test Guide

Grade 8 FSA Mathematics Practice Test Guide Grade 8 FSA Mathematics Practice Test Guide This guide serves as a walkthrough of the Grade 8 Florida Standards Assessments (FSA) Mathematics practice test. By reviewing the steps listed below, you will

More information

Excel 2013 Intermediate

Excel 2013 Intermediate Excel 2013 Intermediate Quick Access Toolbar... 1 Customizing Excel... 2 Keyboard Shortcuts... 2 Navigating the Spreadsheet... 2 Status Bar... 3 Worksheets... 3 Group Column/Row Adjusments... 4 Hiding

More information

Creating a Website with Publisher 2016

Creating a Website with Publisher 2016 Creating a Website with Publisher 2016 Getting Started University Information Technology Services Learning Technologies, Training & Audiovisual Outreach Copyright 2017 KSU Division of University Information

More information

Dynamic-Geometry Activities with GeoGebra for Virtual Math Teams VMT Project Team The Math Forum at Drexel University

Dynamic-Geometry Activities with GeoGebra for Virtual Math Teams VMT Project Team The Math Forum at Drexel University Dynamic-Geometry Activities with GeoGebra for Virtual Math Teams VMT Project Team The Math Forum at Drexel University Draft for review only page 1 Tuesday, May 1, 2012 Introduction Dynamic-Geometry Activities

More information

WideQuick Remote WideQuick Designer

WideQuick Remote WideQuick Designer FLIR ThermoVision CM training This manual is starting off with a quick instruction on how to start the system and after that there are instructions on how to make your own software and modify the FLIR

More information

Visual Guide to Online Campus

Visual Guide to Online Campus Contents Course Navigation... 2 Avatars..3 Text Editor... 4 Accessing Assignments... 6 Accessing Assessments... 9 Accessing and Participating in Discussions... 12 Discussion Forums and Threads... 14 Creating

More information

HTML/CSS Lesson Plans

HTML/CSS Lesson Plans HTML/CSS Lesson Plans Course Outline 8 lessons x 1 hour Class size: 15-25 students Age: 10-12 years Requirements Computer for each student (or pair) and a classroom projector Pencil and paper Internet

More information

Digital Content e-reader Features Overview

Digital Content e-reader Features Overview Digital Content e-reader Features Overview Announcing the launch of our new digital content e-reader. This brief overview will demonstrate some of the most important features of our new e-reader. Once

More information

Realize Reader Chrome App Version User Guide

Realize Reader Chrome App Version User Guide Realize Reader 18.0 Chrome App Version 3.2.0 User Guide 3/9/2018 Contents Contents ii What Is Realize Reader 1 Use Realize Reader Mobile Apps 1 Navigate the Bookshelf 2 View Information About a Book 2

More information

MICROSOFT WORD. Table of Contents. What is MSWord? Features LINC FIVE

MICROSOFT WORD. Table of Contents. What is MSWord? Features LINC FIVE Table of Contents What is MSWord? MSWord is a word-processing program that allows users to insert, edit, and enhance text in a variety of formats. Word is a powerful word processor with sophisticated editing

More information

Title of Resource Introduction to SPSS 22.0: Assignment and Grading Rubric Kimberly A. Barchard. Author(s)

Title of Resource Introduction to SPSS 22.0: Assignment and Grading Rubric Kimberly A. Barchard. Author(s) Title of Resource Introduction to SPSS 22.0: Assignment and Grading Rubric Kimberly A. Barchard Author(s) Leiszle Lapping-Carr Institution University of Nevada, Las Vegas Students learn the basics of SPSS,

More information

ArcView QuickStart Guide. Contents. The ArcView Screen. Elements of an ArcView Project. Creating an ArcView Project. Adding Themes to Views

ArcView QuickStart Guide. Contents. The ArcView Screen. Elements of an ArcView Project. Creating an ArcView Project. Adding Themes to Views ArcView QuickStart Guide Page 1 ArcView QuickStart Guide Contents The ArcView Screen Elements of an ArcView Project Creating an ArcView Project Adding Themes to Views Zoom and Pan Tools Querying Themes

More information

Bluetooth Keyboard Commands with VoiceOver on the ipad

Bluetooth Keyboard Commands with VoiceOver on the ipad Bluetooth Keyboard Commands with VoiceOver on the ipad ios 9.2 Chapter 4: App Navigation using Bluetooth Keyboard Commands (Quick Nav is ON) Module Objectives 4.1 Navigating Dropbox using Bluetooth Keyboard

More information

Excel Basic: Create Formulas

Excel Basic: Create Formulas Better Technology, Onsite and Personal Connecting NIOGA s Communities www.btopexpress.org www.nioga.org [Type Excel Basic: Create Formulas Overview: Let Excel do your math for you! After an introduction

More information

Page Topic 02 Log In to KidKare 02 Using the Navigation Menu 02 Change the Language

Page Topic 02 Log In to KidKare 02 Using the Navigation Menu 02 Change the Language Page Topic 02 Log In to KidKare 02 Using the Navigation Menu 02 Change the Language help.kidkare.com 03 Enroll a Child 03 Withdraw a Child 03 View Pending and Withdrawn Children 04 View Kids by Enrollment

More information

Atlassian Confluence 5 Essentials

Atlassian Confluence 5 Essentials Atlassian Confluence 5 Essentials Stefan Kohler Chapter No. 5 "Collaborating in Confluence" In this package, you will find: A Biography of the author of the book A preview chapter from the book, Chapter

More information

Introduction to Microsoft Excel 2010

Introduction to Microsoft Excel 2010 Introduction to Microsoft Excel 2010 THE BASICS PAGE 02! What is Microsoft Excel?! Important Microsoft Excel Terms! Opening Microsoft Excel 2010! The Title Bar! Page View, Zoom, and Sheets MENUS...PAGE

More information

ipad Training Field Management

ipad Training Field Management ipad Training Field Management ipad User Guide ipad Training Topics Overview Navigation Connectivity Field Apps Tips and Tricks Contacts FaceTime icloud imessage Email Safari Calendar Camera 2 Overview

More information

Built to keep you moving

Built to keep you moving B L A C K B E R R Y Z 1 0: R A I S I N G T H E B A R F O R B U S I N E S S BlackBerry 10 is an entirely new mobile computing platform that removes many of the barriers that slow down other devices. Here

More information

On the Web sun.com/aboutsun/comm_invest STAROFFICE 8 DRAW

On the Web sun.com/aboutsun/comm_invest STAROFFICE 8 DRAW STAROFFICE 8 DRAW Graphics They say a picture is worth a thousand words. Pictures are often used along with our words for good reason. They help communicate our thoughts. They give extra information that

More information

1 Introduction to Using Excel Spreadsheets

1 Introduction to Using Excel Spreadsheets Survey of Math: Excel Spreadsheet Guide (for Excel 2007) Page 1 of 6 1 Introduction to Using Excel Spreadsheets This section of the guide is based on the file (a faux grade sheet created for messing with)

More information

NETWORK THE HOME 10 FOLDERS APPS

NETWORK THE HOME 10 FOLDERS APPS NID-7006 NAXA NID Tablet User s Guide Table of Contents GETTING STARTED 4 CONNECTING TO A WIRELESS NETWORK 4 USING THE TOUCHSCREEN 4 USING THE HOME SCREENS 5 USING THE NAVIGATION ICONS 6 USING THE ALL

More information

Learning and Development. UWE Staff Profiles (USP) User Guide

Learning and Development. UWE Staff Profiles (USP) User Guide Learning and Development UWE Staff Profiles (USP) User Guide About this training manual This manual is yours to keep and is intended as a guide to be used during the training course and as a reference

More information

TJ s Art Studio: User Experience/Functionality Document for ios App

TJ s Art Studio: User Experience/Functionality Document for ios App TJ s Art Studio: User Experience/Functionality Document for ios App 1. Landing page a. Upon launching the app, user lands at this page, which has a Start button, and links to the Meet TJ and Pals and the

More information

ClassLink Student Directions

ClassLink Student Directions ClassLink Student Directions 1. Logging-in Open a web browser, any browser and visit https://launchpad.classlink.com/wssd Your username and password are the same as your WSSD login credentials that you

More information

Libraries. Multi-Touch. Aero Peek. Sema Foundation 10 Classes 2 nd Exam Review ICT Department 5/22/ Lesson - 15

Libraries. Multi-Touch. Aero Peek. Sema Foundation 10 Classes 2 nd Exam Review ICT Department 5/22/ Lesson - 15 10 Classes 2 nd Exam Review Lesson - 15 Introduction Windows 7, previous version of the latest version (Windows 8.1) of Microsoft Windows, was produced for use on personal computers, including home and

More information

EDGE, MICROSOFT S BROWSER

EDGE, MICROSOFT S BROWSER EDGE, MICROSOFT S BROWSER To launch Microsoft Edge, click the Microsoft Edge button (it s the solid blue E) on the Windows Taskbar. Edge Replaces Internet Explorer Internet Explorer is no longer the default

More information

SNOWFLAKES PHOTO BORDER - PHOTOSHOP CS6 / CC

SNOWFLAKES PHOTO BORDER - PHOTOSHOP CS6 / CC Photo Effects: Snowflakes Photo Border (Photoshop CS6 / CC) SNOWFLAKES PHOTO BORDER - PHOTOSHOP CS6 / CC In this Photoshop tutorial, we ll learn how to create a simple and fun snowflakes photo border,

More information

You can also search online templates which can be picked based on background themes or based on content needs. Page eleven will explain more.

You can also search online templates which can be picked based on background themes or based on content needs. Page eleven will explain more. Microsoft PowerPoint 2016 Part 1: The Basics Opening PowerPoint Double click on the PowerPoint icon on the desktop. When you first open PowerPoint you will see a list of new presentation themes. You can

More information