Programming with Scratch – Relative Motion

scratch1

Programming with Scratch

By Majed S. Marji

Scratch is a simple, yet powerful, programming language that is intended to make computer programming easy and fun. It is different from the other programming languages in that it is visual. Instead of typing in your commands, you create your program by connecting graphical blocks together. In this article based on chapter 2 of Programming with Scratch, author Majed Marji shows you how to move sprites on the stage using the relative motion command blocks.

Relative Motion

Figure 1 shows a Scratch program that displays “Hello!” on the screen. The result from running this program is also shown in the figure.

scratch-fig1

Figure 1 This figure shows: (a) a simple Scratch program that contains a single command block, and (b) the result of running this program.

The cat that you see in figure 1.1(b) is called a sprite. You can think of a sprite as a small robot that understands and obeys a predefined set of commands. You can give a sprite a different look by commanding it to use a different image, called costume. You can use an image of an airplane, snowman, your own photo, or anything else you like. The applications you create would typically contain more than one sprite, and your program will command these sprites to do certain things like move, turn, say something, play music, perform mathematical calculations, and so on. The area of the screen where your sprite move and interact with one another is called the stage.

Programming in Scratch is performed by snapping together “colored” command blocks, similar to putting together jigsaw puzzles or LEGO pieces. The stacked blocks that you create are called scripts.

Consider the grid depicted in figure 2, which shows a rocket sprite and a target (star) sprite. Here, the exact positions of these sprites on the stage are unknown as indicated by the absence of their (x,y) coordinates. If you were asked to give instructions to the rocket to hit the target, you might say, “First, move three steps, then turn right, then move two steps.” The effect of executing these instructions is also illustrated in the figure.

scratch-fig2

Figure 2 You can move a sprite on the stage using relative motion commands.

Commands like “move” and “turn” are examples of relative motion commands. The first “move” command, for example, caused the rocket to move up, whereas the second “move” command caused the sprite to move to the right. In essence, the motion depends on (or is relative to) the current direction (or heading) of the sprite.

In addition to its current (x,y) position on the stage, the state of a sprite is also determined by its current direction. The direction convention used in Scratch is illustrated in figure 3. You can explicitly set the direction of a sprite using the scratch2 command. You specify the direction by clicking the down arrow and selecting (up, right, down, or left) from the dropdown list or by typing in any value you want in the white edit box. Note that you can use negative values if you want. Typing 45 or -315, for example, causes the sprite to point northeast.

scratch-fig3

Figure 3 Direction convention used in Scratch: 0 (up), 90 (right), 180 (down), and -90 (left).

With this newfound knowledge, let me introduce Scratch’s relative motion commands. These commands are summarized in table 1. I’ll demonstrate how to use these commands with the aid of simple examples.

Table 1 Relative motion commands in Scratch

Command

Description

scratch-tab1

Moves the sprite in a straight line in the direction of its current heading. It takes an input number that indicates how far the sprite should move. A positive number causes the sprite to move forward, whereas a negative value causes the sprite to move backward.

scratch-tab2

Changes the sprite’s x-position by a specified amount. This causes a horizontal (left or right) movement of the sprite.

scratch-tab3

Changes the sprite’s y-position by a specified amount. This causes a vertical (up or down) movement of the sprite.

scratch-tab4

Rotates the sprite clockwise in reference to its current direction. It takes an input number that indicates the required turn angle. A negative value results in a counterclockwise motion.

scratch-tab5

Rotates the sprite counterclockwise in reference to its current direction. It takes an input number that indicates the required turn angle. A negative value results in a clockwise motion.

You can see the current direction of a sprite in the “sprite info area” of Scratch’s user interface (see figure 4).

scratch-fig4

Figure 4 Current sprite info area

Another way to see this information is provided by the scratch3 block. Clicking the checkbox next to this block allows you to see the sprite’s direction on the stage.

Using move and turn commands

Figure 5 illustrates how the move and turn commands work in relation to the current direction of the sprite. The first command causes the sprite to point up. The second command turns the sprite 45° clockwise. Then, the sprite moves 100 steps in its current direction (in other words, northeast). The last command turns the sprite 45° counterclockwise, which changes the sprite’s direction to the up position.

scratch-fig5

Figure 5 A simple script that illustrates using the move and turn commands

There are many other ways to implement this script and still have the same end result. For example, instead of commanding the sprite to point up then turn right 45°, we can directly command it to point in the direction of 45° using the scratch4 command. Another way is to have the sprite point right, move some distance, turn left 90°, then move the same distance up. The scripts for these two alternatives are shown in figure 6. As you can see, the second script used the Pythagorean Theorem to calculate the horizontal and vertical distances.

scratch-fig6

Figure 6 Different scripts that produce the same result as the script of figure 5

TRY IT OUT (1) – What do you think would happen if you used negative values in motion commands? Try the script shown in figure 7 to check your answer. (2) To know the direction of the sprite, check the box next to the scratch5 block, then turn the sprite by different angles (using the turn commands). What values are displayed in the direction monitor box on the stage?

scratch-fig7

Figure 7 Using negative parameters in motion blocks

Using “change x by” and “change y by” commands

Figure 8 shows a simple script that illustrates the effect of the scratch-change1 and scratch-change2 commands. The first command moves the rocket sprite to the center of the stage, setting its x-coordinate to 0 and its y-coordinate to 0. The scratch-change3 command changes the x-coordinate to 50 (in other words, 0+50), which causes the sprite to move 50 steps to the right. The next command (scratch-change4) changes the y-coordinate to 50, which causes the sprite to move up 50 steps. The (x,y) coordinates of the sprite after executing this command will be (50,50). When the second scratch-change5 command is executed, the sprite will move additional 50 steps to the right ending at point (100,50). You should now be able to trace the motion of the sprite caused by this script, which is also illustrated in the figure.

scratch-fig8

Figure 8 A simple script that illustrates using the “change x by” and “change y by” commands

Summary

Scratch programs (also called scripts) are created by snapping together command blocks that control graphical objects called sprites. You can give a sprite a different look by assigning it a different image, called costume. Sprites move and interact with one another on a background area called the stage. You can change the appearance of the stage by assigning it a different image, called background. Scratch has four kinds of blocks: command blocks, function blocks, trigger blocks, and control structure blocks.

In this article, you learned how to use relative motion commands to move sprites with reference to their own position and direction.

 

Here are some other Manning titles you might be interested in:

arduino

Arduino in Action

Martin Evans, Joshua Noble, Mark Sproul, and Jordan Hochenbaum

java

The Well-Grounded Java Developer

Benjamin J. Evans and Martijn Verburg

machinelearning

Machine Learning in Action

Peter Harrington

 

 

del.icio.us Tags: ,,,

Morning Dew Giveaway – Programming with Scratch (eBook)

[EDIT: The two winners have been selected and will be notified very soon Thanks!]

 

It’s giveaway time.

Manning has released a new book by Dr. Majed S. Marji titled Programming with Scratch. Scratch is a programming language developed at the MIT Media Lab. You can learn more about it at http://scratch.mit.edu/.

 

Here’s a little more about Manning’s book on Scratch:

Too often, the unfamiliar appearance and intimidating vocabulary of a standard programming language gets in the way of learning to think like a programmer. The Scratch programming language turns the tables, offering instead a colorful, comfortable programming environment designed especially for young coders. You build programs by snapping together graphical components, each of which corresponds to a standard programming concept. Scratch users get results immediately and are encouraged to keep exploring.

Morning Dew readers have a chance to win one of two eBook copies of Programming with Scratch. Just leave a comment below, any comment will do. You have until 11:59pm on Monday, August 27, 2012 to enter.

Just a reminder that multiple comments will not increase your chances of winning, and comments for unregistered users are moderated so your comment may not immediately appear.

Good luck!

Alvin

 

del.icio.us Tags: ,,

Building an Offline HTML5 Application

clip_image002

HTML5 for .NET Developers

By Jim Jackson II and Ian Gilman

The idea that you can browse to an application while online and then go back to it when you are offline to continue reading, working, or playing goes against everything most people have learned about how the internet works. This offline capable concept is, however, gaining momentum and familiarity with users. This article based on chapter 9 of HTML5 for .NET Developers talks about building offline applications.

Suppose your partner is upset because you never seem to remember to buy lettuce, carrots, and celery while you are at the grocery store. Perhaps your forgetfulness has to do with the fact that you do not like to eat vegetables; in any case, you know that the criticism is deserved and you have committed to never forget the lettuce again. To that end, we will design and build a simple shopping list application that can be edited either online or offline. This way, your partner can add vegetables to the list, and you can access it even when you are at the grocery store. Figure 1 shows the simple, usable interface that we will be creating.

clip_image004

Figure 1 The complete application will allow a user to add and remove shopping items regardless of whether or not they are currently connected.

The basic premise of an offline web application is that, with specific directives in the markup and careful site preparation, you can actually take your application with you even when you are not connected to a network. With this feature though come some unique challenges and important design decisions. To make your current site or HTML application available offline you must first inventory the resources that you currently use. Every file you include in your site will need to be evaluated against the following criteria:

  • Is the resource static or is it dynamically called?
  • If the resource is static, should it be available when the application is offline?
  • If not available when offline, should a substitute resource be provided?
  • If the resource is dynamic; how will the application handle requests for it when no network connection is available?

Going offline vs. being offline

There are two scenarios that you will have to consider when building your offline web site. The first occurs when a user is online and then loses connectivity. This could be because they were using a portable Wi-Fi device and walked out of range or because the airplane mode was switched on. Whatever the reason, the important part is that the page was not reloaded and the browser was not closed and reopened but the network connection was suddenly unavailable. In this scenario, you need to track the current connection status from within the page.

The second scenario is when the user visits an offline-accessible page and then closes the browser. When the user reopens the browser and navigates back to the page, there is no connection so nothing can be loaded from the server. At that stage, all content previously saved to the cache is loaded.

Both of these scenarios imply the ability for the page to suddenly come back online. When that happens, the page should be notified and any connection-related functions should fire. That brings us to the problem of data synchronization.

For your shopping list app, our first thoughts relate to design considerations. The application must show the user when they are connected or disconnected. A simple cue on the screen will help us there. Then, we must decide how to store the data generated locally so that it can be synchronized back and forth with the server. Our application will use LocalStorage and an MVC controller to handle the storage and synchronization. Finally, the client-side logic must work the same from the user’s perspective whether connected or disconnected and gracefully handle changing connectivity states internally. This is where the Offline HTML5 API and some smooth jQuery operations come in.

Using ASP.NET MVC with offline HTML5 applications

While this application will be built on an MVC (Model View Controller) platform using a simple JSON controller for the data synchronization and a singleton object to emulate a data storage server, the page we will be visiting will not be an MVC view. Instead we will use a simple HTML page. We must do it this way because offline web applications require a physical page to reference as the starting point for the offline cache. The standard MVC application, by comparison, only presents a URL end point, not a physical file.

With design considerations considered, in this article, we’ll create the basic site structure and then the offline JavaScript library.

Creating the basic site structure

Start by opening Visual Studio and creating a new ASP.NET MVC Web Application and call it ShoppingList. Be sure to make it an Internet Application that uses the Razor engine and HTML5 Semantic Markup when you come to the New Project Dialog. Using MVC allows us to create a controller to feed data to and from the client via Ajax, but remember that it does not allow us to use a Razor view for our offline application.

Inside the new solution, we first need to create our offline page. To do so:

  • Right-click on the solution node and select Add > New Item > HTML Page.
  • Name the new page Shopping.htm, after which your page should now appear in the application’s root folder.
  • Inside the new page, add the complete markup.

Much of the code within that file is unremarkable and not worth discussing here. One thing we do want you to note about the initial markup is the attribute in the opening <html> tag that points to a file named app.manifest.

<!DOCTYPE html>
<html manifest="app.manifest">

<head>
...
</head>

<body>
...
</body>

</html>

App.manifest is the file that, by its presence, tells the browser that this page should be available offline. More on the contents of that file shortly.

Next is the styling for the application. In Solution Explorer:

  • Right-click on the Content folder and select Add > New Item > Style Sheet.
  • Name the new stylesheet offline.css.
  • Grab the required markup and add it to the stylesheet (see HTML5 for .NET Developers for the code).

We will be creating a brand new set of styles for our offline application since it is not necessary to duplicate the normal tabbed interface in the rest of the application. This will give the user a cue that this page is different and allow us to keep things as streamlined as possible.

Telling the user that a site is available offline

The CSS file is a good opportunity to think about how to let your users know that the site they are visiting is available offline. Each application is different so it is more important to understand the scope and nature of the problem rather than specific suggestions for resolving it.

The first part of the problem is letting your users know in a fluent fashion that the site they are visiting will be available to them later even if they are not connected. It is unnatural for a user to consider opening a browser on a device when he or she knows that there is no connection. So what kinds of indicators on the site could provide that cue? Additionally, you will probably only be building a subset of the site’s functionality for offline consumption. How can this be indicated to the user?

Next, while a user is working with the site, it is reasonable to expect an occasional loss of connectivity. What are some ways that your application can tell the user what has happened and that there is no cause for concern because their work is being saved locally?

The area of offline web pages is still very new so little or no research has been done to standardize on a method of identifying these conditions to your users. This leaves the door open to practically any solution with your creativity being the only limitation. Chrome, for instance, will change its home page to monochrome icons if the system is not currently online. This is a very intuitive indicator but you might choose to include an icon or glyph in the corner of the browser window that shows the currently connected status. Even a banner that appears temporarily in your site is not unheard of, though some might consider it heavy handed. Your final solution should make it very clear to anyone visiting the site what is possible and what the current connectivity status is. Any less that this is a recipe for confusion or worse: an unused web site.

The offline JavaScript library

The next step is to build our JavaScript interface. This will help sort through which functions are responsible for which tasks during execution. Our offline HTML application will use local storage to contain two kinds of data. The first is the current list of shopping list items and the second is a listing of required actions to update the server to reflect the client state. We will also add some utility functions to keep things manageable and reduce duplication of code.

We have not created the main.js file in the Scripts folder of our site yet, so, do that now. Open it and add the code in listing 1 to stub out our entire API. This code creates the outline that you can fill in as you dig deeper into offline applications. (Remember, if you have any questions about where specific pieces of code fit in the main.js file, the complete listing is in the book.)

Listing 1 The JavaScript API for the offline web application
/// <reference path="http://ajax.aspnetcdn.com/ajax/jquery/jquery-1.7.1.js" />
/// <reference path="http://ajax.aspnetcdn.com/ajax/jquery/jquery-1.7.1-vsdoc.js" />

$(document).ready(function () {
    Main.init();
});

window.Main = {
    $status: null, #A
    $input: null, #A
    shoppingItems: [], #B
    itemActions: [], #C
    init: function () { #D
},

updateForNetStatus: function (connected) { #E
},

newItem: function (title) { #F
},

loadState: function () { #G
},

saveState: function () { #H
},

syncWithServer: function () { #I
}
};

#A The ShoppingList object will contain a place holder for the status and input elements to prevent us from having to requery the DOM every time

#B Keeps a list of current shopping items

#C Keeps a list of all items that must be synchronized to the server

#D Initializes the object

#E Starts listening for the current online status

#F The newItem function updates the user interface with a new element and then assigns that element’s delete key to an anonymous function

#G The loadState function is called when initializing the screen and pulls data from LocalStorage, calling newItem on each value

#H saveState takes all items in the local shoppingItems array and update LocalStorages with the same.

#I Finally, syncWithServer takes the all items cached for server updates and sends them off

This JavaScript file is the last client side file you need before starting the process of making the site available offline.

Summary

Offline web applications can be robust and responsive in most modern browsers and the proliferation of tablet-based devices with only Wi-Fi support should increase their popularity. The biggest drawback is still the fact that users are unaccustomed to using a web site while not connected. Once this barrier is overcome though, proper design and attention to details in an offline application will yield a rich experience and a web site that is usable in many more circumstances than has been traditionally possible in web development.

In this article, you learned about creating basic HTML and CSS structure and developing a JavaScript interface as part of the process of building an offline HTML5 application.



Here are some other Manning titles you might be interested in:

clip_image006

Quick & Easy HTML5 and CSS3

Rob Crowther

clip_image008

Sass and Compass in Action

Wynn Netherland, Nathan Weizenbaum, and Chris Eppstein

clip_image010

Secrets of the JavaScript Ninja

John Resig and Bear Bibeault