Home > Articles > Programming > Games

Building a Game from Scratch, Part 2: Coding the Game Logic

  • Print
  • + Share This
By the conclusion of Part 1 of this two-part mini-series, we had the skeleton of an Asteroids clone game in place. Now it’s time to take our nascent game to the next level, adding enemy sprites, collision detection, and a custom "Game Over" screen. IT professional and author of Sams Teach Yourself Scratch 2.0 in 24 Hours Timothy Warner prepares you to have fun and learn a bunch about programming computer games!
Like this article? We recommend

Hello again. This is the second of a two-part article series in which we use the MIT Scratch development environment to build a video game from…well, scratch.

If you haven’t read the first article in the series, then I strongly suggest that you do so before studying this piece; I want to ensure that you have the proper context for what we’re doing.

The first iteration of our case study project, “Space Game,” can be found at the Scratch website.

The game at this point involves the following play mechanics:

  • Click the Green Flag to start the game.
  • Use the keyboard arrow keys to fly the Spaceship around the playfield.
  • Press SPACE to fire the cannon.

By the end of this article, we’ll add a bunch of additional functionality to the game. Specifically, we’ll:

  • Add “enemy” sprites to the playfield.
  • Program the game such that it ends if your Spaceship makes contact with an enemy sprite.
  • Allow the Spaceship to destroy enemy sprites with its laser cannon.

If you want to get a sneak peek at the second iteration of Space Game, I have one published to the online Scratch Project Gallery.

An in-game screenshot from Space Game 2 is shown in Figure 1.

Figure 1 The Space Game 2 in action

In the meantime, we have a lot of work to do—let’s begin!

Adding the Star Sprite

Because our Space Game is intended to pay tribute to classic space shooter games like Atari Asteroids, we need to add an “enemy” sprite that will serve as a target for our Spaceship’s laser cannon.

Open up your active Scratch project in the online editor (I gave you instructions for doing this, as well as a nutshell tour of the editor interface, in Part 1 of this series; you can also purchase my Sams Teach Yourself Scratch 2.0 in 24 Hours book if you’d like end-to-end instruction).

Open the Sprite Library and add an instance of the Star2 shape from the Things category to your project. Rename the sprite Star. So far, so good.

We have three main challenges to overcome in coding the game logic behind the Star sprite:

  • We need to spawn multiple copies of the Star to fill the playfield and give the player a challenge.
  • We need the stars to appear on-screen in random locations.
  • We need to end the game if the Spaceship sprite makes contact (that is, collides) with a Star.

How can we accomplish all this game logic? Put on your programmer hat, my friend—we’ll take it one step at a time.

Use the annotated Scratch code in Figure 2 as you work through the following procedures. Concentrate on why we’re coding the Star sprite the way we are. Remember that in programming, there are almost always multiple ways to accomplish the same result.

Figure 2 The Scratch code behind our Star sprite

Setting the Stage

In Figure 2, annotation A, we make the star 50 percent smaller than its original size by default, and we remove any graphic effects that may be active on the sprite from a previous run of the program. These Green Flag blocks are what I refer to as “housekeeping” or “cleanup” blocks because they reset the game environment each time the player clicks the Green Flag.

After a one-second delay (shown in annotation B), we kick off a broadcast I called StarAppear that triggers the main in-game behavior of the Star sprites. I like to add stop this script blocks wherever possible to “tie up loose ends,” as it were, with my block stacks.

Making Stars Appear

To program the stars to appear on the Stage, we’ll discuss Figure 2, annotation C. Here we set up a Forever loop that performs the following actions:

  • We bump up the size of the Star by a factor of 2 and explicitly reveal the sprite on the Stage.
  • We place the sprite in a random location on the Stage (recall that the Stage measures 480 pixels wide by 360 pixels high).
  • We spin the star to a random angle.

In annotation D, you’ll see that I backed off the sprite from the top, bottom, left, and right borders of the Stage to prevent Stars from showing up partially off-playfield. In annotation E, we instruct Scratch to wait one second after spawning the first Star before creating a clone; this clone follows the logic of the forever loop, resulting in an ever-increasing number of stars visible on the playfield. The point here is to gradually ramp up the difficulty of the game, like any self-respecting arcade videogame does.

Handling Collision Detection

Oh, there are so many ways for handling collision detection in graphical computer programs. What we’re doing in annotation F is specifying that when the hit broadcast is received by a Star sprite (and no, we haven’t yet defined the hit broadcast—be patient!), the pop sound fires and that particular clone is removed from the playfield.

What we’ll see later is that the hit event is fired when the Spaceship’s laser beam makes contact with a Star sprite.

Of course, we recall that we add the pop sound (or any other, as your preferences dictate) by visiting the Sounds palette for the Star sprite.

Finally, check out annotation G. Here we hide all Stars if the EndGame broadcast is triggered. Again, we’ll program that particular event momentarily.

Programming the Spaceship

Now let’s turn our attention to the player’s Spaceship sprite. Our first challenge is to think about how we’ll handle the collision detection between the Spaceship’s laser beam and a Star.

Remember from the Part 1 article, we programmed the Spaceship costume to switch when the player presses the SPACE (fire) key. In the original version of this game, the laser bolt is yellow, which is the same color as our Star.

If you’ve tried to do collision detection in Scratch before, then you’ll see the problem. We’re going to program a rule such that whenever the color of the Spaceship’s laser bolt connects with the color of the Star, the hit broadcast message is raised. Of course, this isn’t going to work if both sprites are yellow!

So…the long story short is that we need to change some colors around. Look at Figure 3 to see what we need to do.

Figure 3 The Scratch Paint Editor allows us to customize a sprite’s appearance

Select the Spaceship sprite, navigate to the Costumes palette, and click the spaceship-fire costume.

Next, use the Paint Bucket and color swatch controls to recolor the laser bolt. All you have to do is click the laser bolt once, and the Paint Bucket takes care of the rest. I chose blue to present a clear color contrast between the Spaceship, Stars, and playfield background colors.

All set? Great. Now please return to the Scripts palette and we’ll code the game logic for the Spaceship from end to end. Use Figure 4 as your reference as I walk you through the admittedly complex code.

Figure 4 The Scratch code behind our Spaceship sprite

Resetting the Environment

In Figure 4 annotation A, we perform various and sundry housekeeping tasks to ensure that the Spaceship is reset to default values every time that the game is started.

We covered much of the logic in annotation B in Part 1 of this article series. The code in the Forever loop executes continuously until a game-ending event occurs, which is specifically if or when the Spaceship connects with a Star sprite.

Programming Collision Detection, Revisited

In Figure 4 annotation C, we use the color is touching block to code the collision detection between the laser/lightning bolt color we selected earlier and the Star color. This block is particularly confusing, so let me give you the step-by-step on its use:

  • Click in the first color swatch in the color is touching block.
  • Now click on a sample of that color. To accomplish this procedure, you’ll need to have both a star and the Spaceship on Stage simultaneously. In this case, click the border color of the Spaceship sprite; you should see the first block in the color is touching block pick up that color.
  • Now perform the same two-step sequence on the second color is touching color block and the Star shape.

If we translate annotation C to what we programmers call psuedocode, then we can say that “if any part of the Spaceship’s border color touches the Star sprite color, then send out a broadcast called ‘EndGame.’”

Now have a look at annotation D. Here we specify that if any other part of the Spaceship (especially the lightning bolt) touches the Star’s yellow color, then we transmit the hit broadcast message. Recall earlier in this tutorial that when the Star receives the hit broadcast, it disappears.

We covered the code in annotation E in the previous article; here we handle the fire event that is raised when the player presses SPACE. In annotation F, we hide the sprite when we end the game.

Speaking of ending the game, I think it would be appropriate to show the player a formal “GAME OVER” screen to signal the final game state, wouldn’t you agree? Let’s take care of that now.

Customizing the Stage

Take a look at Figure 5 to see my vision for a “Game Over” screen.

Figure 5 Our Game Over screen

The point here is that we want to graphically show the user that the game has ended. The challenge here is that we need any on-screen elements, such as the Spaceship and the Stars, to disappear.

We actually handled that by attaching hide blocks to the EndGame message, so all we really need to do is actually create the screen and define its logic.

Drawing the Game Over Screen

Click the Stage and navigate to the Backdrops palette in the Scratch Online Editor. Visit the Backdrop Library and import the moon backdrop from the Space category. Rename the backdrop gameover.

You can then use the Brush and Text tools to draw a canvas and add the words GAME OVER, as shown in Figure 6.

Figure 6 Crafting our Game Over screen

Programming the Game Over Screen

Finally, take a look at the annotations in Figure 7 and I’ll walk you through the last bit of code in this project.

Figure 7 The Scratch code behind the Stage

In Figure 7 annotation A, we reset the backdrop to stars every time the player clicks the Green Flag to start a new game session. In annotation B, we respond to the EndGame broadcast message by performing the following actions:

  • Switching the backdrop to gameover.
  • Playing the spaceripple sound (naturally, you’ll need to add the sound clip to the Stage; you should know how to do this by now).
  • Wait three seconds and stop all scripts, effectively ending the game.

Next Steps

I’m sorry to use the cliché, but we truly have only scratched the surface of where we can take this simple game. You and I have reached the end of the road here, but I want to challenge you to enhance the game in at least the following ways:

  • Scoring. At the moment, we have no way to track the player’s progress. Flex your Scratch programming skills by implementing a scoring system. How about the player earns 1 point for every destroyed star?
  • Better Effects. Right now, the Star simply disappears when it is “hit” by the Spaceship’s lightning laser. Figure out a way to add graphical effects to the Stars such that they actually appear to explode when hit.
  • Diagonal Movement. At the moment, the Spaceship is limited to movement in four directions only. Find a way to support diagonal movement; believe me, it’s possible. For example, when the player presses the UP ARROW and RIGHT ARROW keys simultaneously, the ship points northeast and travels as such.

Good luck to you, and happy Scratching!

  • + Share This
  • 🔖 Save To Your Account

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020