A7: Missile Shield

The final assignment for CS 1110 has always been to develop a game in Python. Game development ties together everything that we have learned in this class into one large project. While modern games are far too advanced for this class, classics of the original arcade era (like Pac-Man, Frogger, or Breakout) are well within your ability. This year, we are doing the 1980 game Missile Command.

If you have never played Missile Command before, there are a few versions online as HTML5 games. The Arcadium version is delightfully low-fi, while still having clean modern graphics. The Itch.io version has more traditional graphics. It is also more faithful because you have control over which missile silos you fire from. You can also watch a Youtube video for an accurate play-through of the original game.

One of the main challenges with this assignment is its scope is completely up to you. There is a bare minimum of functionality that you must implement. You must implement a complete, single wave of Missile Command. But after that point, you are free (and encouraged) to add more interesting features to your game. The video above shows our solution, which has several extra features such as sound, addition threats, and even the classic score counting screen. You can even implement power ups and other features if you want to get really crazy. You are permitted to do anything that you want, provided that the basic functionality is there.

Despite any difficulties you might have had with previous assignments, we know that this assignment is easily within your grasp. You just have to start early, break the problem up into manageable pieces, and program/test incrementally. Below, we discuss stages of the implementation and give suggestions for staying on top of the project. If you follow our advice and test each piece thoroughly before proceeding to the next, you should be successful.

Our bare minimum solution is about 995 lines of code (including specifications and comments). This is ~280 lines in app.py (including the ~135 lines already there), ~290 lines in wave.py (including the ~30 lines already there), and ~400 lines in models.py (including the ~105 lines already there). So you should expect to write just a little over 700 lines of code for the bare minimum solution. While this may seem intimidating, a good amount of that consists of headers and specifications (in fact, it is over half our code). Our minimum solution has ~30 methods across six classes, not including getters and setters.

This game does requires some familiarity with vectors. If you do not know how vectors work, we recommend that you read our short tutorial before reading the rest of these instructions

Author: W. White

Learning Objectives

This final assignment has several important objectives:

  • It gives you practice reading official class documentation and APIs.
  • It gives you experience with a complex, interactive application.
  • It gives you experience designing helper functions to structure your code properly.
  • It gives you experience using constants to make your code more readable.
  • It gives you experience with programming animation and simple collisions.
  • It gives you experience with an open-ended project that is not fully specified.

Table of Contents


Academic Integrity and Collaboration

Academic Integrity

This is a brand new assignment. We worked hard on bringing you this assignment. Please give this assignment the respect that is deserves. Follow our academic integrity policy and cite any collaborators on this project. In addition, you are not to use any agentic tools on this assignment.

Furthermore, because of the time that it takes to grade this assignment, any academic integrity hearings will have to be delayed until Spring semester (meaning that such students will receive an Incomplete for the course). Do not put yourself in this position. We also ask that you do not enable violations of academic policy. Do not post your code to Pastebin, GitHub, or any other publicly accessible site.

Collaboration Policy

You may do this assignment with one other person. If you are going to work together, form your group on CMS as soon as possible. If you do this assignment with another person, you must work together. While you might have gotten away separating the work by function on previous assignments, that was only because it was so well specified. This time, given how open ended the assignment is, you will be completely lost if you do not work together.

With the exception of your CMS-registered partner, we ask that you do not look at anyone else’s code or show your code to anyone else (except a CS1110 staff member) in any form whatsoever. This includes posting your code on Ed Discussions to ask for help. It is okay to post error messages on online, but not code. If we need to see your code, we will ask for it.

Copyrighted Material

There is another Academic Integrity issue with this assignment: copyrighted material. Gameplay cannot be copyrighted. You can make a game that plays the same as another. This was established in the early days of gaming when Space Invaders lost its court case against Galaxian and Galaga. However, artwork in a game is copyrighted (and in the case of Space Invaders, even trademarked). So you should be careful about adding additional artwork to this game.

While there might be an argument for fair use – this is a class project – your instructor prefers that you avoid the copyright issue entirely. In general, you are only allowed to use copyrighted material if you have a license to do so. For example, many of the sound effects from FreeSound are available for you to use under an Attribution License. That means you are free to use it so long as you cite the source in your documentation (e.g. your header comments). This is okay. A license where you have to pay is not okay.

If you are in doubt as to whether you have a license to use something, ask us on Ed Discussions.

Assignment Help

While the code in this assignment is only a little bit more complicated than Assignment 6. The challenge is that the directions are more open ended. We have tried to give you as much guidance in this document as we can. We suggest that you start this assignment early, and that you go to office hours page on the first sign of difficulty.

In addition, you should always check Ed Discussions for student questions as the assignment progresses. We may also periodically post announcements regarding this assignment on Ed and on the course website.


Organization and Scope

This assignment is even longer than Assignment 6. Fortunately, we have (technically) given you over three weeks for this assignment. While that time does include Thanksgiving Break, you do not have to work over break (and the micro-deadlines skip over the break). This assignment can be finished by the end of classes if you work a little bit every day, not including the break.

While there are no test cases this time, you should be able to figure out if everything is working simply by playing the game. There are no tricky “restore everything to how it was” like with Turtles. There are no nasty surprises lurking in the specifications. Just get the game working.

Assignment Source Code

To work on this assignment, you will need all of the following:

File Description
shield.zip The application package, with all the source code
samples.zip Several programs that give hints on this assignment

Only the first is a must download, as it contains the all of the source code necessary to complete the assignment. The second is a collection of demo code from the lecture on state-based programming. This sample code contains a lot of hints on how to approach some of the harder parts of this assignment, and we reference these samples throughout the instructions.

As with the imager application, this assignment is organized as a package with several files. To run the application, change the directory in your command shell to just outside of the folder shield and type

  python shield

In this case, Python will run the entire folder. What this really means is that it runs the script in __main__.py. This script imports each of the other modules in this folder to create a complex application. To work properly, the invaders folder should contain the following:

File Description
app.py The primary controller class for the application
wave.py A secondary controller for a single wave of bombs
models.py All model classes for the game (Silo, City, etc.)
consts.py All module with all of the constant (global variable) values
game2d A package with classes that can display graphics on the screen
Sounds A folder of sound effects approved for your use
Fonts A folder of True Type fonts approved for your use
Images A folder of images for the silos, cities, and backgroun
Data A folder with different waves you can play

For the basic game, you only need to worry about the first three files: app.py, wave.py, and models.py. The other files and folders can be left alone. However, when it is time to add a new feature, it helps to understand how all of these fit together.

app.py

This module contains the controller class MissileShield. This is the controller that launches the application, and is one of three modules that you must modify for this assignment. While it is the primary controller class, you will note that it has no script code. That is contained in the module __main__.py (which you should not modify).

wave.py

This module contains the secondary controller class Wave. This class manages a single wave of bombs. It works as a subcontroller, just like the example subcontroller.py in the provided sample code. It is another of the three modules that you must modify for this assignment,and the one that will require the most original code.

models.py

This module contains the model classes Silo, City, Bomb and Rocket. These classes are similar to those found in the pyro.py demo in the provided sample code. If you want to add other model classes (e.g. threats such as planes or drones), then you should add those here as well. This is the last of the three files you must modify for this assignment.

consts.py

This module is filled with constants (global variables that should not ever change). It is used by app.py, wave.py, and models.py to ensure that these modules agree on certain important values. It also contains code for adjusting your default wave. You should only modify this file if you are adding additional features to your program.

game2d

This is a package containing the classes you will use to design you game. These are classes that you will subclass, just like we demonstrated in lecture. In particular, the class Froggit is a subclass of GameApp from this package. As part of this assignment, you are expected to read the online documentation which describes how to use the base classes.

Under no circumstances should you ever modify this package!

Sounds

This is a folder of sound effects that you may wish to use as part of your new feature. You are also free to add more if you wish; just put them in this folder. All sounds must be WAV files. While we have gotten MP3 to work on Windows, Python support for MacOS is unreliable.

Fonts

This is a folder of True Type Fonts, should you get tired of the default Kivy font. You can put whatever font you want in this folder, provided it is a .ttf file. Other Font formats (such as .ttc, .otf, or .dfont) are not supported. Be very careful with fonts, however, as they are copyrighted in the same way images are. Do not assume that you can include any font that you find on your computer.

Images

This is a folder with image files for the frog and the obstacles. The GImage and GSprite classes allow you to include these in your game. You can put other images here if you wish. Once again, remember the copyright policy.

Data

This is a folder with JSON files that define a wave. You will turn these into dictionaries and use them to place the bombs in your game. These files will be used about midway through the assignment. But you should look at them briefly right away to familiarize yourself with these files.

Assignment Scope

As we explained in class, your game is a subclass of GameApp. The parent class does a lot of work for you. You just need to implement three main methods. They are as follows:

Method Description
start() Method to initialize the game state attributes
update(dt) Method to update the models for the next animation frame
draw() Method to draw all models to the screen

Your goal is to implement all of these methods according to their (provided) specification.

start()

This method should take the place of __init__. Because of how Kivy works, initialization code should go here and not in the initializer (which is called before the window is sized properly).

update(dt)

This method should move the position of everything for just one animation step, and resolve any collisions (potentially pausing the game). The speed at which this method is called is determined by the (immutable) attribute fps, which is set by the constructor. The parameter dt is time in seconds since the last call to update.

draw()

This method is called as soon as update is complete. Implementing this method should be as simple as calling the method draw, inherited from GObject, on each of the models.


These are the only three methods that you need to implement. But obviously you are not going to put all of your code in those three methods. The result would be an unreadable mess. An important part of this assignment is developing new (helper) methods whenever you need them so that each method is small and manageable. Your grade will depend partly on the design of your program. As one guideline, points will be deducted for methods that are more than 25 lines long (not including specifications or spacing).

You will also need to add methods and attributes to the class Wave in wave.py, as well as Silo, City, Bomb and Rocket in models.py. These classes are completely empty, though we have given you a lot of hints in the class specification. You should read all these specifications.

As you write the assignment, you may find that you need additional attributes. All new instance attributes should be hidden. You should list these new attributes and their invariants as single-line comments after the class specification (as we have done this semester). For example, each Silo has ammunition, and can only fire when that ammunition is not zero; you are going to need a getter for this attribute.

While documentation and encapsulation is essential for this assignment, you do not need to enforce any preconditions or invariants. However, you may find that debugging is a lot simpler if you do, as it will help you localize errors. But we will not take off points either way, as long as the game runs correctly.

Assignment Organization

This assignment follows the model-view-controller pattern discussed in class. The modules are clearly organized so that each holds models, the view, or a controller. The organization of these files is shown below. The arrows in this diagram mean “accesses”. So the MissileShield controller accesses the view and Wave subcontroller. The Wave controller accesses the view and the models.

This leads to an important separation of files. MissileShield is never permitted to access anything in models.py, and Wave is never permitted to access anything in app.py. This is an important rule that we will enforce while grading.

mvc
The Import Relationships

In addition to the three main modules, there is another module with no class or function definitions. It only has constants, which are global variables that do not change. This is imported by the models module and the various controllers. It is a way to help them share information.

When approaching this assignment, you should always be thinking about “what code goes where?” If you do not know what file to put things in, please ask on Ed Discussions (but do not post code). Here are some rough guidelines.

MissileShield

This controller does very little. All it does is keep track of the game state (e.g. whether or not the game is paused). Most of the time it just calls the methods in Wave, and lets Wave do all the work. However, if you need anything between waves, like a paused message or a high score, this goes here. This is similar to the classMainApp from the demo subcontroller.py

Wave

This class does all the hard work. In addition to the initializer (which is a proper __init__, not start), it needs its own update and draw methods. This is a subcontroller, and you should use the demo subcontroller.py (in the provided sample code) as a template.

The most complex method will be the update and you will certainly violate the 25-line rule if you do not break it up into helpers. For the basic game, this method will need to do the following:

  • Setup the silos and cities
  • Move the aim target according to player input
  • Move the bombs towards their cities
  • Move the rockets towards their targets
  • Detect collisions with bombs and/or rockets
  • Remove anything destroyed in an explosion

In our code, each one of these is a separate helper (and several of them are more than one). You should think about doing this in your code as well.

The Models

The models just keep track of data. Most of the time, models just have attributes, with getters and setters. Think Image from the previous assignment. However, sometimes models have additional methods that perform computation on the data, like swapPixel.

The models in this assignment are the game objects on screen: the frog and any terrain. You will notice that most of our model classes are subclasses of GImage. That is because they are represented by images. They inherit methods and attributes from this class that allow us to move them about the screen, and to draw them.

The reason why we need all these clases (instead of using GImage directly) is because they all have different behavior. New behavior means additional methods or attributes. In general, the purpose of these classes as follows.

  • Target: This class the aiming target that the player can move about the screen.
  • Silo: This class is a missile silo that has a small amount of ammunition
  • City: This class is a city you need to protect. It is one of your “lives”,
  • Bomb: This class is a bomb dropping from the sky; it targets a city or silo.
  • Rocket: This class is a rocket you fire back in self-defense.

As you can see each class is distinguished by its behavior, not its looks. And this behavior is what is going to require new attributes and methods.

If your added features include additional threats like planes or drones, you will probably need additional model classes. But if both planes and dones simply fly across the screen and drop a bomb, you only need one class for them because they have the same behavior. If your are in doubt about whether or not you need a new class, ask us on Ed Discussions.

Suggested Micro-Deadlines

You should start on this assignment soon as possible. If you wait until the weekend before this assignment is due, you will have a hard time completing it. If you work on a little bit of it every day or every other day, then you will enjoy it and get it done on time. We have also tried not to include your Thanksgiving Break in this assignment.

You should implement the application in stages, as described in these instructions. Do not try to get everything working all at once. Make sure that each stage is working before moving on to the next stage. Set up a schedule, but do not focus only on writing code. Leave time for learning things and asking questions.

We have provided you with a schedule of suggested milestones. This schedule ensures you will only work a little each day. However, to fit in the time alloted, this schedule does not leave any time for extra features. If you want to add features you will either need to work faster than the recommended schedule, or ask for an extension. But whatever the case, do not add any new features until you get the basic game working. If you add extensions too early, debugging may get very difficult.

Extension Policy

This assignment is technically due Monday, December 7, which is the last day of class. That is the last day we are allowed to make this due. However, we realize that ALL professors like to load you up with work the last week of class. Because of this fact, minor extensions are possible.

We are allowing no-questions-asked extensions up to Thursday, December 10. To get an extension, you must contact your lab instructor (do not e-mail the professor). Your instructor will assign you an extension in CMS. If you do not ask for an extension, you will be penalized for being late.


Overview of Missile Shield

The initial configuration of Missile Shield is shown in the picture below (minus the background art to make it easier to see objects). The bottom row consists of three silos: one at each end and one in the center of the screen. The silos have a fixed amount of ammunition which is represented by the numbers on them. Between the silos are three evenly spaced cities.


Initial Setup

Once the game begins, the bombs start dropping. These are represented in the picture above as white circles with a translucent tail. Each bomb travels in a straight line towards a silo or a city.

When the bomb reaches a silo and/or city, it destroys it. A destroyed city is removed from the game, while a silo remains but has its ammunition set to zero. This is shown below (though the removed city should be gone, not just translucent). Once all cities are destroyed, the game is over and the player loses.


Bomb Destruction

To defend themselves, the player fires back rockets. As shown below there is a blue aiming target (or reticule) on tje screen. The play launches a rocket from a silo towards this target. Rockets look similar to bombs, but move upwards and move faster; to distinguish them we make them a different color. Modern versions of Missile Command fire rockets in different ways, but the classic arcade game controlled the target with a trackball and had three fire buttons, one for each silo.


Rocket Fire

When the rocket reaches the target (or where the target was when it was fired), it explodes. The tail disappears and the circle grows until it reaches its maximum size. While it is growing, any bomb that is inside of the circle is destroyed. So in the picture below, the two rightmost bombs are destroyed, but the one on the left is not.


Rocket Explosion

Each wave has a limited number of bombs. When all bombs are destroyed (either from a rocket explosion or a detonation with a city/silo), the wave is over. As long as just one city remains, the player is alive. The player’s score is computed from the remaining rockets and cities on the screen. The video below shows the basic game, with no extra features.


Note that this game has a paused screen. Because the bombs are always falling, this gives us a way to take a break if we need to do something important outside of the game.

Game State

One of the challenges with making an application like this is keeping track of the game state. In the description above, we can identity several distinct phases of the game:

  • Before the game starts, and the bomb wave has not started
  • When the cities and silos are set up, but the bombs have not started falling
  • While the game is ongoing, and the bombs are falling.
  • While the game is paused
  • After the game is over

Keeping these phases straight is an important part of implementing the game. You need this information to implement update in MissileShield correctly. For example, whenever the game is ongoing, the method update should instruct the Wave object to move the bombs. However, if the game has just started, there is no Wave object yet, and the method update should create one.

For your convenience, we have provided you with constants for six states:

  • STATE_INACTIVE, before a a wave has started
  • STATE_LOADING, when it is time to load the wave file
  • STATE_ACTIVE, when the game is ongoing and the bombs are dropping
  • STATE_PAUSED, when the game is paused to display a message
  • STATE_CONTINUE, when a paused game is resumed
  • STATE_COMPLETE, when the game is over

All of these constants are available in consts.py. The current application state should be stored in a hidden attribute _state inside MissileShield. You are free to add more states when you add more features. However, your basic game should be able to handle these five states.

The rules for changing between these five states are outlined in the specification of method update in MissileShield. You should read that in its entirety. However, we will cover these rules in the instructions below as well.

Wave JSONs

We want to be able to control the difficult of each wave. That is hard to do if we randomly generate the bombs. So instead, each wave is defined by a JSON file. You should remember what a JSON string is from the very first assignment. A JSON file is just a file that stores a very large JSON string. These JSON files are a lightweight way to store information as nested dictionaries, which is the standard way of sending complex data across the Internet.

The tricky part about JSONs is coverting the string (or file) into the Python dictionary. Fortunately, we have provided a tool that makes this part easy. The GameApp class includes a method called load_json which your MissileShield class will inherit. Simply specify the name of the JSON file. As long as that file is stored in the JSON directory, this method will load this file and convert to a Python dictionary for you.

This means that working with wave files is really all about working with a complex nested dictionary. To understand how these dictionaries work, look at the file easy.json. This includes all of the features that you will need to implement the basic game. The top-level dictionary has five keys:

  • "version" : A float representing the wave version.

This version is only relevant if you define your own waves. It is discussed in the section on additional features.

  • "speed" : A float representing the bomb speed

This value represents how many pixels a bomb travels per second. Harder waves have higher speeds, as the bombs are moving faster.

  • "bombs" : A list of all the bombs in the wave.

This list cotains multiple dictionaries, where each dictionary describes a bomb. Each bomb is defined by the keys "x", "target", and "time". The latter is the most important. This is the time since the start of the wave when that bomb starts dropping. The bombs do not drop all at once, and a bomb should be offscreen before it is time for it to drop. The other two values define the line that the bomb should travel.

If you understand all of these elements, then you will have no problem completing this assignment.


The Basic Game

We have divided these instructions into two parts. This first part covers the basic things that you must implement just to get the game running. Afterwards, we talk about additional features you can put into your game. These extra features can earn you extra credit on this assignment.

You should focus most of your effort on the basic game. This is the bulk of your grade. If you do everything correct on the basic game, you can still earn a 100 on this assignment. The value of extra credit is typically limited to no more than 8 points. Furthermore, unless your features are incredibly innovative, we will not give you more than a 100, no matter how many things you have added.

Near the end of each task we have a section called Reviewing the Task where we summarize everything that we told you to do. Make sure you read this before writing any code.

1. Create a Welcome Screen

We start with a simple warm-up to get you used to defining state and drawing graphics elements. When the player starts the application, they should be greeted by a welcome screen. When you work on your add more features, you can embellish your welcome screen to be as fancy as you wish. But for now, we want the screen to consist of a background image (the file "background.png") with some text on top of it.

Because the welcome message is before any game has started, it belongs in the MissileShield class, not the Wave class. You are already seeing how we separate what goes where.

The text message will look something like the one above. It does not need to say “Press ‘S’ to Play”. It could say something else, as long as it is clear that the user should press a key on the keyboard to continue. However, we recommend that you be careful about allowing the user to press any key, as the user could press the one of the number keys and accidentally launch a rocket.

To create a text message, you need to create a GLabel and store in it an attribute. If you read the class invariant for MissileShield, you will see two attributes named _title and _text. The title attribute is the logo of the game. The text attribute is for any messages to display to the player. The text is typically smaller, like a footnote.

In addition to the text, we also want you to add a background image. This is the purpose of the attribute _background in the class invariant. To do this, you will create a GImage object. We suggest that you use the image BACKGROUND specified in consts.py, but you can use any other image you might wish.

Since the welcome message should appear as soon as you start the game, it should be created in the method start, the first important method of the class MissileShield. When creating your message, you will want to set things like the font size and position of the text. If you are unsure of how to do this, look at the class MainApp from the demo subcontroller.py in the provided sample code.

As you can see from the documentation for GLabel and GObject, graphics objects have a lot of attributes to specify things such as position, size, color, font style, and so on. You should experiment with these attributes to get the welcome screen that you want.

There are a few things to understand when working with a label. The first thing to understand is the positioning. In Kivy, the screen origin (0,0) is at the bottom-left corner, and not the center like it was for the Turtle assignment. If you want to find the center of the window (our version centers these on the screen), the MissileShield object has attributes width and height that store the size of the window. In addition, for the label ibjects, the attributes x and y store the center of the object. So you can center something horizontally by assigning x to width/2.

When placing labels, you do not always want to center them. Sometimes you would like the label to be flush againt the edge of the window. For that reason we have attributes like left, right, top, and bottom. These are alternate attributes for x and y. They move the graphics object in much the same way, but give you a little more control over the positioning.

One you understand how to position the label, it is time to think about your font choice and style. If you want to look exactly like the picture above, we have some constants to help you in const.py. The font is THEME_FONT, which is a reference to Magnetar. The title has size THEME_LARGE while the message has THEME_MEDIUM. However, you are not constrained to these choices. You may chose a different font or font size if you wish, so long as it fits on the screen.

Working with an image for the background is very similar. An image object obeys the same positioning rules as a label. However, instead of a font choice, you select a source, which is the image file to display. In const.py we have BACKGROUND which is a reference to a good background image to use. Images are resizable, so you should make sure to set the width and height to match the size of the window. This is not guaranteed if you don’t, especially on retina displays.

Drawing the Welcome Message

Simply adding this code to start is not enough. If you were to run the application right now, all you would see is a blank white window. You have to tell Python what to draw. To do this, simply add the lines

    self._background.draw(self.view)
    self._title.draw(self.view)
    self._text.draw(self.view)

to the method draw in MissileShield. The (non-hidden) attribute view is a reference to the window (much like the Window object in Assignment 4). Hence this method call instructs Python to the background and then the text. Drawing is back to front, so drawing the image first ensures it is always in the background. Now run the application and check if you see your welcome message appears.

Initializing Game State

The other thing that you have to do in the beginning is initialize the game state. The attribute _state (included in the class specification) should start out as STATE_INACTIVE. That way we know that the game is not ongoing, and the program should (not yet) be attempting to animate anything on the screen. In addition, the other attributes listed (particularly _wave) should be None, since we have not done anything yet.

The _state attribute is an important part of many of the invariants in this game. In particular, we want your new attribute for the welcome message to have the following invariant:

  • If the state is STATE_INACTIVE, then there is a welcome message with title and text.
  • If the state is not STATE_INACTIVE, the _title attribute is None.
  • If the state is STATE_ACTIVE, the _text attribute is None.
  • The _background attribute is never None, as an image is always displayed.

Does your start() method satisfy this invariant?

Dismissing the Welcome Screen

The welcome screen should not show up forever. The player should be able to dismiss the welcome screen (and start a new game) when he or she presses a key. To respond to keyboard events, you will need the attribute input, which is an instance of GInput. This class has several methods for identifying what keys are currently pressed.

When using the attribute input, remember the issues that we discussed in class. The method update(dt) is called every 16 milliseconds. Checking if the key is down will return a lot of matches. You want to detect a key press which is the first time the key is held down. Remember the method (is_key_pressed) to do this.

When you detect a key press, then you should change the state STATE_INACTIVE to STATE_LOADING. This will load a wave file and start a new game. You are not ready to actually write the code to start the game, but switching states is an important first activity.

Invariants must be satisfied at the end of every method, so you need to assign None to the welcome message as well. This will require a simple change to method draw() to keep it from crashing (you cannot draw None). Once you have done that, run the application. Does the message disappear when you press a key?

Reviewing the Task

We have covered a lot in these instructions. It helps to have some a reminder of what you should doing. To finish this part, you are adding code to each of the start, update, and draw methods of Froggit. In the method start, you should

  1. Create an attribute for the background and assign it a GImage
  2. Create an attribute for the title and assign it a GLabel
  3. Create an attribute for the message and assign it a GLabel
  4. Create an atttribute for the state and assign it to STATE_INACTIVE

In the method update you should

  1. Check if the start key was pressed
  2. Change the state to STATE_LOADING if the key was pressed
  3. Ensure the application invariants are satisfied

Finally, in the method draw you should

  1. Draw the background (always)
  2. Draw the title if it is not None
  3. Draw the message if it is not None

Documenting your New Attributes

When working on the steps above, you may have needed to add new attributes beyond the ones that we have provided. Whenever you a new attribute, you must add it and its corresponding invariant as a comment after the class specification (these comments are the class invariant). Add it just after the comment stating ADD MORE ATTRIBUTES, to make it easier for the graders (and you) to find them. We will deduct style points for instance attributes that are not listed in the class invariant.

Pacing Yourself

This first part of the assignment looks relatively straightforward, but it gets you used to having to deal with controller state. Try to finish this part by Thursday, November 19, which is a day after starting the assignment. You will spend most of your time reading the online documentation, but this will give you a solid understanding of how this application works.

2. Initialize the Wave

The state STATE_LOADING is going to last just one animation frame. During that time you are going to load the wave file and create a Wave object. So for this activity you are going to write code in two different classes: MissileShield and Wave.

Loading a JSON file is easier than you think. There is a method (technically it is a class method) in GameApp called load_json, and MissileShield inherits this method. Simply call this method with the argument DEFAULT_WAVE. The method will return a dictionary and you are good to go. So from this point on, you will treat the wave information like a dictionary.

By default, the starting wave is easy.json. You can go into consts.py to change this if you wish. Alternatively, you can test other waves by typing

  python shield wavename

So you can load the medium.json wave simply by typing

  python shield medium.json

Creating a Wave Object

Once you have loaded the JSON file, you want to create a Wave object and assign it to the attribute _wave in MissileShield. We have started the definition of the Wave class for you in wave.py. However, it does not do much, because we have not defined the initializer.

Without an initializer, the constructor will not take any arguments. However, we want the Wave constructor to take a single argument: the JSON dictionary containing all of the information about the wave. You will want to save this information, so your initializer should store this in an attribute (we recommend using the attribute _data). Make sure that you document this attribute in your class specification.

After you have created the Wave object, it is also time to change the state in MissileShield to STATE_ACTIVE. As we said, STATE_LOADING only lasts on frame. You load the file and immediately switch, regardless of what keys the player presses.

Creating the Aim Target

As soon as the wave is created, we need to set up our defenses. So you need to create a Target object and position it in the middle of the screen. Note that this class is in models.py, but it does not have any code. That is because it does not need any code. It inherits everything from GImage, even the initializer.

However, we do recommend that you add a short-initializer to this class.
The image aiming target never changes. Its image source is TARGET_IMAGE and its size is given by TARGET_WIDTH and TARGET_HEIGHT. The only thing that changes is its position, So you can make a simple initializer whose only parameters (other than self) are x and y. This initializer is one line, calling the super() initializer with the missing values.

As the aim target is going to last the entire wave, it also needs its own attribute and should be created in the initializer. Remember to document this attribute in the class invariant.

Creating the Silos

The aiming target is not going to do anything without the missile silos. So we need to place three Silo objects: one on the left side, one on the right side, and one in the center. Vertically, they should all be positioned at the bottom of the screen.

As with Target, the Silo class is in models.py and has no code. Once again, free to make a custom initializer for this class. The image source is SILO_IMAGE and its size is SILO_WIDTH and SILO_HEIGHT.

As with the target, the Wave object is going to need attributes to store these silos. While you could create three attributes – one of each silo – that is going to make the code complicated very quickly. Instead we recommend the that _silos attribute be a list of all the silos, so you only need one attribute.

Creating the Cities

Finally, you want to have something to protect. That is the point of the cities. You need to create six City objects. Placing these is a little more complicated. You want to break up the window width into nine equal “slots”. The first, fifth, and last slot were used for the silos. The remaining slots are for the cities. The x attribute of each city should be centered in one of these slots. The bottom of the city should be CITY_OFFSET off the ground.

Once again, the City class is in models.py. Feel free to create a custom initializer for this class. The image source is CITY_IMAGE and its size is CITY_WIDTH and CITY_HEIGHT. In addition, you want to create an attribute _cities in Wave that is a list of the city objects.

Drawing the Wave

You have now created a lot of GImage objects in the Wave class. But once again, creating all these objects is not enough to draw them to the screen. You need to draw them. However, drawing all these objects are a bit more complicated than drawing the welcome message. For example, the target is a (hidden) attribute in Wave. While the MissileShield code

 
  self._wave._target.draw(self.view)

works (and you should try it out), it is not allowed. That is because the attribute _target is hidden inside of the class Wave, and MissileShield is not permitted to access anything hidden in another class. We will take off style points if a class of one module ever accesses the hidden attributes of an object of a class in a different module.

This is the purpose of adding a draw method to class Wave. The draw method in MissileShield should call the draw method in Wave, and this in turn should call the draw method for the target (defined in GImage).

However, only MissileShield has access to the attribute view, which is necessary for drawing. The class Wave cannot directly access any attributes in MissileShield. If a method in Wave needs an attribute from MissileShield, then MissileShield must provide that attribute as an argument in the method call. This means that the draw method in Wave needs to have view as a parameter, and the code in MissileShield should look like this.

  self._wave.draw(self.view)

Now the only access of something hidden is _wave, which is okay since it is inside of MissileShield (MissileShield can access its own hidden attributes). Notice this is very similar to how we draw GObject objects.

When you are done, you should be able to see a lot of things on the screen: the background, the silos, the cities and the aim target. In particular, when you load easy.json, it should look something like this.

water
The Start of a Wave

Reviewing the Task

In this task, you are writing code in four different methods. You are adding code to the start and draw methods in Shield. You are also adding an initializer and a draw method to Wave. You may or may not be adding initializers to three other classes (Target, Silo, and City). That is your choice.

Let’s start with the methods in Wave, as you need them first. In __init__ you should

  1. Get the JSON dictionary from MissileShield as a parameter
  2. Save this dictionary to an attribute
  3. Create an attribute _target for the aiming reticule
  4. Create an attribute _silos for the three silos
  5. Create an attribute _cities for the six cities

In the draw method for Wave you should just draw all of these objects to the screen (the class MissileShield already handles the background).

Now that your have Wave working, let’s move to MissileShield. In the start method for MissileShield, add an attribute for the wave. It will start out as None.

In the update method for MissileShield you should

  1. Check if the state is STATE_LOADING (if not, skip the steps below)
  2. Load the DEFAULT_WAVE as a dictionary using the method load_json
  3. Create a Wave object, passing the dictionary as an argument
  4. Change the state to STATE_ACTIVE

Finally, in the draw method for MissleShield, you should draw the Wave object if it is not None.

Pacing Yourself

There are a lot of classes working together now, but the code is still pretty straight-forward. You are not doing much more than writing initializers with a few lines of code in them. The challenging part is understanding how everything fits together. But this is a lot, so we are budgeting two days to figure this all out. Try to complete this part by Saturday, November 21.

3. Move the Target

To understand simple animation, we are going to start with the easiest thing to move: the target reticule. In the original game, the target was moved by a trackball. In this version, we are going to use the keyboard to control it, as that allows us to control it a lot easier than trying to work the mouse.

Animating the Target

By default, we will assume that the player uses the arrow keys to move the target. If you prefer to WASD controls or some other controls, that is okay. But those must be implemented in addition to arrow-key control, not in place of.

To see how to control the target, you should look at the arrow.py demo from the provided sample code. This example shows how to check if the arrow keys are pressed, and how to use that to animate a shape. Note that this is actually easier than dismissing the welcome message. We do not care if a key press is the first one. The target will continue to move so long as we hold down a key.

Technically, animation takes place in the update method of MissileShield. But once again, _target is a hidden attribute of Wave. So just like we added a draw method to Wave, we want to add an update method to Wave as well. This is where you will move the target. Remember that this method must be called within the update method of MissileShield, or nothing will happen. Again, see the subcontroller.py demo from the sample code to understand what we are asking for.

To check the keyboard, the method update in Wave will need to access the input attribute Invaders, which is an instance of GInput. Again, since Wave is not allowed to access any of the attributes of Invaders, that means you need to pass input as an argument in this method call.

To move the target, just change its x and y values. The target will have a speed (more on this in a second). You move the target as follows:

  • If the up arrow is held down, add the speed to y
  • If the down arrow is held down, subtract the speed from y
  • If the left arrow is held down, subtract the speed from x
  • If the right arrow is held down, add the speed to x

So what is this speed? In this game, speed is measured in seconds. However, all our code is processed in animation frames, not seconds. So to compute the speed, we need to know how many seconds have passed each animation frame. That is the purpose of the dt parameter in the update method in MissileShield. The speed of the target is

  speed = dt*AIM_SPEED_STEP

However, once again, we need this value in Wave, not just MissileShield. So both input and dt need to be parameters in the method update of Wave.

Implement this code and try it out before going any further.

Debugging Your Code

This is generally the first place the students encounter real difficulty. It is possible to do everything perfectly up until now only for your target not to move. If your target refuses to move, add a watch statement to the draw method of Wave. Print out the id (the folder name) of the target. Run the game and look for this print statement. What you see will (hopefully) identify your bug.

The print statement never appears: In this case, you have forgot to call the update method for Wave from MissileShield. Make sure MissileShield has (something like) this line of code in its update:

    self._wave.update(self.input,dt)

The target id keeps changing: In this case, you are accidentally reseting either the Target object or the Wave object each frame. If you only create the Target object in the initializer of Wave, it is most likely the latter. Go back and read initialize the wave to see how to stop this.

The target id is constant: If this is true and the target still will not move, we have no idea what your problem is. It is something unique. Please see a consultant immediately. They will not look at your code, but they will help you debug it better. In our experience, when students claim the target id is constant but the target is not moving, there is actually a problem with their debugging statements.

Adjusting the Speed

Once you have gotten the target moving, you will notice that it does not move particularly quickly. It is going to be hard to move this across the screen fast enough to defend all your cities.

To simulate the trackball of the old arcade machine, we are going to give the target some acceleration. As long as you hold the keys down, the target will get faster and faster. But once you let go of the keys, the speed drops down to zero.

To implement this, the target needs a speed attribute. If you added an initializer to the Target class, this will be easy to add to the class. This speed should start out at zero. As long as any arrow key is held down, you should add AIM_SPEED_STEP to this speed, with a maximum value of AIM_SPEED_LIMIT (so once it reaches AMI_SPEED_LIMIT) it cannot get any faster. But if there is a frame where no arrow keys are held down, the speed should drop back to 0.

As the speed can change, this means that this attribute needs getters and setters in Target. In addition, while you do not need to enforce the invariants, you do need to say what they are in your class invariant for that class.

Moving the target is the same as it was before. However, instead of adding or subtracting AIM_SPEED_STEP, you use the current speed. Try this out and see the difference.

Restricting Movement

You should ensure that the target stays completely on the screen even if the player continues to hold down a key. If you do not do this, the target is going to be completely lost once it goes off screen. Our code for this extra feature is 3 lines long; it uses the functions min and max.

When we say that the target must stay on screen, we mean that the entire target must remain on screen. You cannot have half the target off and half of it on screen. This is important because the x and y attributes are the center of the target.

In addition to staying on screen, we never want the target to go below the missile silos. The bottom of the target should always be above the top of the silos.

Reviewing the Task

This task requires you to put code in three different classes: MissileShield, Wave and Target.

  1. In the Target class, add an attribute for the speed with a getter and setter.
  2. In the Wave class, add an update that checks the input and moves the target.
  3. In the MissileShield class, call the update of Wave, passing input and dt as arguments.

Make sure that your target moves properly. Try to bounce it against the walls. If your target is not moving at all, refer to our instructions for debugging your code

Pacing Yourself

We highly recommend that you complete this by Sunday, November 22, before you leave for Thanksgiving. This is the first place were students can get really stuck, and you can take advantage of consulting hours before you go.

This activity is actually pretty straightforward, provide you understand the arrows.py demo in the provided sample code. Most people can complete this part of the assignment in two hours or less. So if you find yourself struggling with this part of the assignment, get help immediately.

4. Drop the Bombs

Okay, now it is time to start the game. We want to start dropping bombs on the player. This is the purpose of the JSON file that you loaded. You will use this to create the bombs in the initializer of Wave, and then move them in the update method.

A bomb will fall in a straight line from the top of the screen to the top of a target. This line is defined by the "x" and "target" values for each bomb in the JSON. The bomb starts at (x,GAME_WIDTH) putting it at the top of the screen. It then travels to (obj.x,obj.top) – the center top – of the object (Silo or City) targetted. The "target" value is always a number 0 to 8 indexing the targets from left to right on the screen. So 0, 4, and 8 refer to silos and everything else refers to a city.

Creating the Bombs

The Bomb class in models.py and you will definitely want to modify its initializer. A Bomb object should store its starting position and target position in addition to its (inherited) current position. You should set these attributes in the initializer. The bomb is a cicle with radius BOMB_RADIUS. As Bomb is a subclass of GEllipse, this just means that you set the width and height to be twice the radius. In addition, fillcolor should be BOMB_COLOR.

In addition, each Bomb object has a starting time. This is the "time" value in the JSON. This is the time the bomb will drop, and it is measured in seconds from the start of the wave. As each bomb has a different starting time you will want to make an attribute for this as well.

Once you have the initializer, you will want to create the bombs. Just like the City objects where put in a list in Wave, you will want a list attribute to store the Bomb objects. You should do this in the initializer of Wave.

However, at this point, your initializer is probably getting a little long. Remember the 25-line rule; no method is allowed to be more than 25-lines of code, not including the header or docstring. So you probably want to split this initializer into some helpers now. You can have one helper to place the silo and cities and another to create the bombs.

Placing the Bombs

As the start time suggests, the bombs are not all going to be moving at once. Many bombs will be waiting their turn offscreen. In particular, until it is time to drop a bomb, you should not draw or move an undropped bomb.

This means we need someway to detected whether or not a bomb is dropped. There are a few ways to do this. One way is to add a new atribute to Bomb called active or dropped. This attribute starts as False. When it is time to drop the bomb this gets set to true. Only bombs with a True value for this attribute are dropped or moved.

Another way is to keep two lists in Wave. When you create the Bomb objects in the initializer of Wave, put them in a list called pending. Have another list of Bomb objects called inflight. When a bomb is dropped, move it from pending to inflight. Only bombs in inflight are drawn or moved.

There is no right answer here. Do whichever one you are most comfortable with.

Regardless of your approach, you do need code to mark a bomb as dropped (either by setting the attribute or moving it to a new list). So how do you know when to drop the bottom? The drop time is measured from the start of the wave. So in the Wave initializer, you will need a new attribute to track the time. It starts at 0 when the Wave object is created and stores the number of seconds that have passed.

How do you know the number of seconds that have passed? That is the purpose of the dt attribute. You were already using it to move the target. You can use it to count the passage of time as well.

Moving the Bombs

If a bomb is active/dropped, you should move it. To move a bomb you should compute the vector from the current position to the target location (the top center of the city or silo). If you do not remember how vectors work, please refer to our short tutorial. Normalize this vector to get the unit vector. That is the direction the bomb is travelling.

You then multiply this vector by the bomb speed to get the velocity vector. But what is the speed? If you look at Missile Command games, you will notice that the bombs get faster and faster each wave. That is why the speed is in the JSON file. It is the second value after the "version". This is the number of pixels to move per second. You should multiply it by the dt to get the distance to tracel for that frame.

This means that the total movement is given by the vector

    movement = unit_vector * dt * speed

Add this vector to the current bomb position to get the new bomb position. That is it. Once a bomb reaches the target, stop moving.

Drawing the Bombs

There is a lot of code setting up the bombs and moving them. But you cannot really debug this code if you cannot see anything. So that means you need to draw the bombs as well.

Fortunately, a Bomb is a subclass of a GEllipse. It has a draw method that it inherits from that class. So you just need to add code to the draw method of Wave that draws all active bombs. Again, you should only draw bombs that have already been dropped.

Once you do this, you can now test your code. If you run

    python shield immediate.json

that starts a wave where all the bombs drop at the same time. They all go in a straight vertical line from the top of the screen to their target. Because silos are taller, silo bombs will hit before city bombs, but everything should hit at roughly the same time.

Once that is working, try

    python shield staggered.json

This will drop exactly the same bombs, but staggered at 2 second intervals. If this works, then you can be confident the start time code is working correctly.

Drawing the Tail

Right now the bombs are an simple circle. But in the games, they are line from their start position to their current position. This tail helps the player plot their trajectories.

To support these tails, we are going to need to add some new code. A line is represented by a GPath object. The primary attributes for GPath are points and linewidth. The linewidth is the width of the line. Make it larger than 1 (the default) for a thicker line. The attribute points is an even-length list of numbers defining the line segment. So if you want the line segment from (0,10) to (20,30), the points attribute would be [0,10,20,30].

For each active Bomb object you are going to create a GPath object for the tail. In this case you should make the line width equal to BOMB_RADIUS. The line segment will start at the initial bomb position and go to the current bomb position. To give it a translucent color, use the constant BOMB_TAIL.

Where to put this GPath object? Put it in the Bomb object as an additional atribute. But that means that we have to override the draw method in Bomb to draw two things: the circle (ellipse) and the tail. We have seen how to do this in class. We want to take the original draw method and add something to it (the tail). That is the purpose of super().

This means that Bomb will have a new draw method that calls super().draw(view) to draw the original ellipse. It then has a second draw call to the draw the tail. You want the ellipse on top, which means the call to super() should be last.

Reviewing the Task

There is a lot going on here, but it is now restricted to two classes. In the class Bomb you need to add an initializer with the following attributes

  • An attribute for the start location
  • An attribute for the target location
  • An attribute for the start time
  • An attribute for the tail line
  • An attribute marking the object as dropped (optional)

You also need to override the draw method in Bomb to

  • Draw the original ellipse via super()
  • Draw the tail via its attribute

In the initializer for class Wave you need to create the Bomb objects an add them to a list. Then in the update method you need to

  • Check which bombs have dropped
  • Compute the movement vector for each active bomb
  • Add that vector to get the new bomb position

Finally, you have to draw all the active bombs in the draw method of Wave. Once you have done that this task is complete.

Pacing Yourself

This is a longer activity, but completing it is very satisfying. Once you are able to complete this activity, you should have the confidence that you can complete this entire assignment. The individual tasks do not get harder than this. But given the number of things you need to figure out for this task, we are budgeting three days for this task.

As a result, we recommend that you complete this by Monday, November 30, which is the day you come back from Thanksgiving Break. We are not asking you to spend Thanksgiving Break on this. Instead, we asking you to spend the Monday and Tuesday before Thanksgiving (as class is still in session then) and the Monday you get back. This is more than enough time to work on this part. In fact, if you finish everything but drawing the tail before break, you can enjoy your break guilt-free.

If you are in town on Tuesday, we highly recommend that you come to lab hours on that day if you are struggling with this part of the assignment. We will not be holding lab that week, but the Tuesday lab will be available as open office hours for anyone that wants help.

5. Detonate the Bombs

At this point the bombs will reach their targets and stop. It is time to do some damage. When a bomb reaches its target, the target is destroyed. Any City object will be removed and any Silo object will lose its ammunition. Of course, we have not added any ammunition yet, so we will need to do that first.

Loading up the Silos

The purpose of the silos is to hold ammunition. So you will need to add an attribute for that in the Silo class. If you did not previously add an initializer to the Silo class, you will need to do that now. The ammunition is an integer indicating how many rockets it has remaining. Each Silo object starts with AMMO_COUNT rockets.

We need some way to track the ammunition. The way to do that is to add a GLabel attribute to the Silo object indicating the number of rockets remaining. You should override the draw method in Silo to draw this label on top of the silo image. You do this the same way that you drew the tail in the Bomb object.

When you are done with this, start up a new game. This time you should see the ammo numbers on top of the silos, as shown below.

water
A Wave with Loaded Silos

Blowing Up a Silo

When a bomb reaches its target, you need to test whether the target is a Silo or a City object. If it is a Silo, you should set the ammunition to zero. This means that the Silo object needs a getter and setter for the ammunition attribute.

In addition, when the Silo object is hit, you need to remove the Bomb. Att the very least, it should no longer be drawn on the screen. But we recommend that you go further and remove it from the list in Wave just to be safe.

Blowing Up a City

If the target of a bomb is a city, that city is destroyed when the bomb reaches it. What does that mean? There are many different ways to implement this. One way is to remove the city from the list of City objects. Another way to do this is to add an attribute to the City class marking whether on not the city is alive. Dead cities should not be drawn. Choose the approach you are most comfortable with.

As with Silo detonation, once a bomb blows up a city, you should remove that bomb from Wave

Reviewing the Task

This task is fairly straight-forward. The biggest change is adding the ammunition attribute and graphics to the class Silo. Other than that, you just have to modify update in Wave to do the following:

  • Check if a bomb reached its target.
  • Remove the bomb if it reached its target.
  • If the target is a Silo, set the ammunition to zero.
  • If the target is a City, remove it from the game.

Again, remember the 25-line rule. You probably want to pull all this out as its own helper method (or two).

To test your code once again use the files immediate.json and staggered.json. These drop a bomb for each silo and city and so they should destroy everything on the screen. We also recommend easy.json for more interesting bomb paths to make sure that you vector addition is correct.

Finally, we recommend that you also test the wave file doubletap.json. This will hit each city and silo twice. Obviously a dead city cannot be destroyed, so in that case you should remove the bomb and do nothing else.

Pacing Yourself

This is a comparably chill part of the assignment, and is a good thing to come back to after the break. Try to complete this by Tuesday, December 1. which is the day after you come back from the holiday.

6. Pause the Game

Watching these cities get destroyed can get stressfull. So it is time to introduce a pause option to give us some time to think about what to do.

The game should pause whenever the players presses the p key. If the game is paused, it should resume when the player presses the r key. Pausing is a different state. When the game is paused, it should be in the state STATE_PAUSED.

Pausing the Game

Pausing the game is easy. Simply do not call update in Wave. Again, you can see exactly this idea if you examine subcontroller.py in the sample code. Your code in MissleShield should update the Wave if the state is STATE_ACTIVE and not if it is STATE_PAUSED. As this takes place in MissileShield, that class is also where you should write the code to detect the p key.

There is one more thing to do when you pause the game. We want you to display a message that the game is paused, just like we have done below.

game paused
Game Paused

Notice that you are displaying a message to the player. You can do this with _text or _title attribute in MissileShield, provided that you draw it last. There is no need to add a label to Wave for this, especially since MissileShield is in charge of pausing.

In the example above we made a few stylistic choices that you might want to adopt, but you are not required to do so. We have used a more normal font (BASIC_FONT) instead of the THEME_FONT from the welcome message. In addition, we set the background of the GLabel to a solid color, covering up the bombs underneath. We did this to make the label more readable, which is all that matters. You can do whatever you want with your paused message so long as it is still readable.

Resuming the Game

The player should be able to start playing again by pressing the r key. When you resume, you should switch to the state GAME_CONTINUE. This state is similar to STATE_LOADING. It is a one-frame state where you delete the text message (set it to None) and switch the state back to STATE_ACTIVE. The only difference with STATE_LOADING is that you do not make a new wave.

Reviewing the Task

Again, this is a straight-forward task. Most of the code this time is in MissileShield. You just need to write code for a new state. But ultimately, this is no harder than the initial welcome message. When you are done, start up the wave of your choice. Rapidly pause and unpause the game a few times to make sure your code is working correctly.

Pacing Yourself

Because this is such a simple task, you should be able to finish it quickly. Try to complete this part by Wednesday, December 2. In fact, we think you can complete this task and the next one in a single day.

7. Lose the Game

Even with pausing, eventually the bombs will still destroy all your cities and silos. When that happens you are just left with silence. It is time to let the player know that they have lost so that they can grieve and move on.

Fortunately, this is very similar to pausing the game. When the game is lost, the game should pause, and a message should be displayed telling the player that they lost, like the one below:

game paused
Game Over

The primary difference this time is the state. Instead of switching to STATE_PAUSED, this time you should switch to STATE_COMPLETE, marking the end of the game.

Detecting the End

Your update method in Wave should be constantly checking for the game’s end. At the very end of update, it should count the number of cities left alive. If that number is more than zero, the player can keep going – even if their silos are out of ammunition. But if the number of cities reaches zero, the game ends immediately.

To test this, we recommend using the wave doubletap.json. This bombs every city twice. It has one wave of bombs at 1 second and other at the 10 second mark. The game should end after the first bombing wave reaches its target.

Cleaning Up the Bombs

When the player loses, we do not want anything on the screen other than the (potentially empty) silos. Any bombs or rockets in the air should just disappear. That means you probably want a helper method in Wave for deleting the objects. We don’t want to delete the entire Wave object because we still want the silos. But everything else should be gone.

Starting a New Game

If the player loses, the might want to try again. To enable this, we allow the player to restart the game by pressing r. This the same way we resume a game when it is paused.

However, we cannot start a new game by switching to STATE_ACTIVE. The wave is complete; the cities are gone. In this case, we have to create a new Wave object. So instead of switching to STATE_ACTIVE, the code should switch to STATE_LOADING instead. That will load a new wave and start it, using the code you have already written.

Reviewing the Task

This task is very similar to pausing that game. The only differences are that

  • This is the result of an event (cities lost), not a key press
  • The state switches to STATE_COMPLETE instead of STATE_PAUSED
  • Resuming the game switches to STATE_LOADING instead of STATE_ACTIVE

Test this game on a few quick waves. Use doubletap.json to make sure that the wave ends immediately on the death of the last city. Also make sure that you can restart the game.

Pacing Yourself

Because this part of the project is so similar to pausing the game, try to finish this part by Wednesday, December 2. This will give you enough time to finish the last tricky part.

8. Fire the Rockets

It is time to allow the player to fight back and defend their cities. That is where the Rocket objects come in. Rockets are similar to bombs, except that they are created by the player, not the JSON file. In fact, a lot of the code you wrote for the Bomb class is going to carry over to the Rocket class, making this task not so hard. But there are enough differences that we need a separate class here.

Detecting a Launch

The player has three silos. When they launch a rocket, they have to specify which silo the rocket came from. For this you will use the number keys: 1 (left silo), 2 (center silo) and 3 (right silo). Remember that the method is_key_pressed represents a key as a string, so you would use

    input.is_key_pressed('1')

to detect this.

There is one other requirement. In order for a missle launch, the chosen silo must have available ammunition. If there is no ammunition, nothing happens. In the base game, this can be a little unsatisfying, as the player might be confused why nothing is happening (until they see the ammunition count).

This is one of the main reasons to have sound in your game. A sound effect for a launch failure quickly tells the player something is wrong. However, sound is not required for the base game. It is simply an option for the additional features.

Launching a Rocket

If the missile launch is successful, drop the ammunition count of that silo by one and create a Rocket object. Rockets are very similar to bombs in that they have a start and target location that defines their trajectory. In their case, the start is the top center of the silo that fired the rocket (similar to how the target of a bomb is the top center). The target of a rocket, on the other hand, is the current location of the Target object. So this rocket is going to draw a line from the tip of the silo to the aiming reticule.

Note that when we say the current location of the Target object, we mean when the rocket is launched. If the aim target moves, you should not update the rocket. It should keep going to it originally assigned target.

Just like bombs, rockets have a tail. So add an attribute for GPath object and override the draw method just like you did in Bomb. To help us keep bombs and rockets separate, a rocket should be colored ROCKET_COLOR with ROCKET_TAIL for its tail color.

Finally, these rocket objects are going to need somewhere to live. Just like Wave has a list of Bomb objects, it is going to need a list of Rocket objects.

Moving a Rocket

Rockets move exactly like bombs. You compute the unit vector pointing to the target location and multiply that by the speed and the dt. The primary difference here is that rocket speed is not set by the JSON file. Instead it is defined by the constant ROCKET_SPEED.

When the rocket reaches its target it should stop (for now). Do not delete the rocket. Just let it stay there.

Reviewing the Task

While there is a fair bit of code for this step, it is all familiar code. You can copy and paste of lot of it from the Bomb class. And if you can figure out how to write the shared code as helpers, even better (though this is not required).

In the class Rocket you need to add an initializer with the following attributes

  • An attribute for the start location
  • An attribute for the target location
  • An attribute for the tail line

You also need to override the draw method just like you did with Bomb.

In the initializer for class Wave you need to do the following in the update method.

  • Check if a rocket was successfully fired
  • Create a rocket and add it to the list
  • Compute the movement vectors for each rocket in the list
  • Move each rocket forward via its movement vector.

Pacing Yourself

While there is a lot of code in this step, it is not a lot of new code. We are still budgeting two days for this task, but many of you should be able to finish even faster than that. Try to complete this part by Friday, December 4.

9. Explode the Rockets

Rockets do not stop in midair. They explode. And this is where the code in Bomb and Rocket start to differ.

A rocket explosion is not instantaneous. It takes a while. For that reason, the Rocket class needs an additional attribute indicating whether or not the rocket has exploded. This value starts out as false, and only switches to true when the rocket reaches its target.

If a rocket is exploding, two things happens. The first is that the tail disappears. You can set the attribute to None if you want, but all that matters is that you stop drawing it. The other thing that happens is that the circle portion of the rocket starts to grow.

Animating the Explosion

While the rocket was moving, the update method in Wave was regularly changing the position. When the rocket is exploding, the position remains fixed, but the radius (e.g. the width and the height) change.

The value ROCKET_STEP_RADIUS is the amount the rocket radius grows per second. So you should add 2*ROCKET_STEP_RADIUS*dt to the rocket radius at each call to update. You should do this until you reach ROCKET_MAX_RADIUS. The rocket should never get larger than ROCKET_MAX_RADIUS.

To make it easier to see overlapping explosions, an exploding rocket should change its color to ROCKET_TAIL. This gives is a translucent color that allows us to see overlapping explosions.

Removing the Rocket

When the rocket reaches ROCKET_MAX_RADIUS, the explosion is complete. It should sit at this size one animation frame and then be deleted the next animation frame. Deleting the rockets is simple. Just look at the pyro.py demo in the provided sample code.

To make sure the rocket is at full size for one frame, it helps to pay attention to the order in which you have written your code. To keep to the 25-line rule, hopefully you have made each task its own helper, which makes it easy to reorder your code as necessary. If you write the code to delete a rocket before the code to expand its size, that guarantees the rocket will last one more animation frame before it is deleted. That is because it was not at maximum size when you were deleting rockets.

Reviewing the Task

Most of the code in this step will take place in update of Wave, or an associated helper. This code should

  • Detect if a rocket is exploding
  • Drop the tail of any exploding rocket
  • Make the exploding rocket translucent
  • Expand the radius of the rocket ROCKET_STEP_RADIUS per second
  • Delete the rocket when it reaches ROCKET_MAX_RADIUS

Not all of the code above needs to be in Wave. Some of it, such as changing the rocket color or dropping the tail, can take place in a method in Rocket. As always, how you design your code is up to you.

The key thing to test when you run your code is the rocket deletion. Fire off a long rocket (i.e. a long distance to its target) followed by a short rocket. The short rocket should get deleted first even though it was fired second.

Pacing Yourself

At this point in the project, you have learned so much that this task is not particularly difficult. We believe you can easily complete it in day. Try to finish this part by Saturday, December 5.

10. Eliminate the Bombs

While the rocket explosions are pretty, they do not really do anything. It is time to protect the cities. If a bomb is contained inside of the explosion blast, it is needs to be deleted. By contained, we mean the bomb circle, not the tail.

Testing containment is easy. The Rocket class inherits the method contains from GObject. This method tests if a point is inside of a shape. The method argument can either be a Point2 object or a two-element tuple of numbers. So all you have to do is test that the Bomb object x and y attributes are contained inside the current rocket ellipse. If that happens, delete the bomb.

Testing Your Code

While the amount of code that you need to write for this part of the project is not that large, it is now possible to win the game. So it is time to start testing with the waves provided. Start with easy.json and see if you can destroy all the bombs before they hit your cities and silos. If you are having difficulty there is no shame in changing the "speed" value in the JSON file. Lower values make the bombs slower, making them easier to hit.

Test several waves before continuing. Make sure that you have a feel for the game.

Pacing Yourself

While the code is not that complicated, we want to make sure that you have enough time to test waves. Playing the game is the only way to discover bugs from earlier steps that you might have missed. For that reason, we have budgeted a full day for this task. Try to finish this part by Sunday, December 6.

11. Win the Game

While it is now possible to win the game, the game just sits there when the bombs are destroyed. The player does not get any payoff for their hardwork. So just like you created a game over screen, it is you now need to create a congratulations screen.

Like many of the original arcade games, Missle Command is a game about getting the best score. So when the player wins, you want to display their score, as shown below.

game paused
Final Score

Detecting the End

The game is over when there are no more bombs on the screen. However, to keep the game from ending abruptly, the game should not stop if there are also any rockets still on the screen (exploding or otherwise). Only once all of the bombs and all of the rockets are gone does the game end. Note this means we could keep the game going for a while by shooting off more rockets.

Computing the Score

Once all rockets and bombs are gone, it is time to compute the score. The game should award SCORE_AMMO for each remaining rocket in a silo, and SCORE_CITY for each surviving city. Total this number up and display it in the congratulations message.

Restarting the Game

When the player wins the game, the game should switch its state to STATE_COMPLETE, just like we did when the player lost the game. This will allow the player to restart the game without writing any additional code.

Pacing Yourself

This (and the next task) are the very end of the assignment. They are simple enough that you should be able to finish them on Monday, December 7, the day that the assignment is due. That means that if you wish to work on additional features, you will need to complete this task earlier, or ask for an extension.

12. Support New Waves

If you are going to work on additional features, you will want to make some new wave files. And even if you don’t, it would be cool to see some new waves with just the basic game features. What do you think is an easy wave? What is a hard wave? With that said, we are not requiring you to make new waves for your game. But we do want you to add some code to make it possible.

The problem is that the your wave loading code in MissileShield is not particularly robust. Is uses the json module built into Python. But the functions in that module module crash if there any any problems with the JSON file. Missing a comma? The game crashes. Added a comma in the wrong spot? The game crashes. Used single quotes instead of double quotes for your strings? The game crashes.

We want you to add some error handling to your code. That means putting a try-except in function you use to load the wave. Your code should capture the error into a variable e as shown in class. It then should use the Kivy logger to display the error as follows:

    Logger.info(type(e).__name__+': '+str(e))

Note that Logger is a module imported at the top of app.py. The info function works like print except that it integrates it into the normal Kivy messages. That print statement will show the type of error that happened and the associated error message. This tool is very similar to the debugging tool that we showed in class.

In addition, when a wave fails to load, we want to you to change the _text attribute so that it tells the player that a wave failed to load, as shown below.

corrupted wave
A Malformed Wave

It is likely that you will need multiple lines to show this message if you intended to display the name of the file. You do not need more than one GLabel object to do this. You can get more than one line in your label by putting a '\n' character in your string.

This is a very short task. When you have done all this, try your game on malformed.json. You should see the image above and the Terminal should display the error mesage.

[INFO   ] [json.decoder.JSONDecodeError] Expecting ',' delimiter: line 23 column 3 (char 300)

When you see this, you are done with the basic game.


Additional Features

Our suggested timeline gives you just enough time to work on this assignment. But if you are able to finish early, then you have the opportunity to extend the game and try to make it more fun. While this part if not required, this is an opportunity for extra credit. We will award up to 8 points for extra credit, according to how interesting your features are.

When you add new features, you might find yourself reorganizing a lot of the code above. You may add new methods or change any of the methods you have written. You may add new classes. For example, you might want to add a class for a drone that switches back and forth between targets. You can even completely rewrite existing classes like Bomb to support explosion animations.

You are allowed to change anything you want so long as you update the specifications to reflect the changes. There are only four things that you are not allowed to change.

  • The target reticule must remain in bounds
  • The win (destroy all bombs) and lose (lose all cities) conditions must remain the same.
  • The player must lose as soon as all cities are destroyed
    (Though you can take time to animate this destruction before ending the game)
  • The game must continue as long as there are rockets in the air.
  • Restarting and unpausing the game must use the same key.
  • No game elements (planes, drones, etc.) can be introduced in the provided waves.

The last condition is critical. Anything that the player needs to fight should be specified in a JSON file. One of the nice features of JSON files is that we can add new keys to them without breaking our existing code. The old features are still there and still work. And the new features work if we have the code to support them.

That means that for many (but not all) of the extra credit features you will need to create your own wave files to show them off. For style purposes, we recommend that you change the version number if you start adding elements to a JSON file. This is a way of indicating that it is changed from the original format.

We highly recommend that you back up your solution before working on any additional features. Many times we have seen students completely ruin their perfectly good code adding the new features. Do not do that.

Once again, addition features are simply for extra credit. You can earn full points on this assignment with just the basic game. The purpose of these new features to allow you to earn back any points that you might miss for implementing a feature incorrectly. However, you cannot get back any points lost for writing bad specifications or for violating the 25-line rule, no matter how good your extra features are. And again, your features must be truly exceptional to earn more than 100. You cannot exceed 100 just for implementing our suggestions below.

Possible Features

Here are some possible ways to extend the game, though you should not be constrained by Here are some possible ways to extend the game, though you should not be constrained by any of them. Make the game you want to make. We will reward originality more than we will reward quantity. While this is a fairly simple game, the design space is wide open with possibilities.

Sound

Sound is one of the easiest features to add to the game. We have provided several audio files with the source code. You will want to look at them, but you are not restricted to only those sounds. Remember that it is a violation of the Academic Integrity Policy to use unlicensed copyrighted material.

To load an audio file, you simply create a Sound object as follows:

    launchSound = Sound('launch.wav')

Once it is loaded, you can play it whenever you want (such as when a rocket is fired) by calling launchSound.play(). Read the online specification to see how to use Sound objects. You cannot replay a sound until the current version of the sound stops. So if you want to play the same sound multiple times simultaneously (such as if you have overlapping launches), you will either need to stop the current sound or create multiple Sound objects.

Important: Real-time sound is unfortunately one of Python’s greatest weaknesses. When you play a sound, that is a request for the sound to be played, but it does not guarantee to play it right away. This is particularly true when you play a sound for the first time, as there is a delay to load the sound resources. This means it can be very tricky to get sound and animation to align in Python. While the basic 1 point version of this extra credit is easy, doing better than that is very hard.

Animated Score

One of the hallmarks of Missile Command is the animated score at the end. It flashes up each rocket and each city on the screen as it totals up the score. We have even provided smaller images for the rockets and cities to allow you to do this. If you watch the video where we included our additional features we do just that.

Note that this will obviously require a new state. You will need a state between STATE_ACTIVE and STATE_COMPLETE where you total up the score. You should add that to consts.py.

Once again, sound goes a long way in this animation. The beat as each rocket and city are counted can be really satisfying. However, this is a place where getting the sound right is really hard. Aligning multiple short sounds to a beat in Python is nearly impossible. In our video above, we did not play an individual sound for each beat. Instead we recorded the sound for a maximum score and then cut the sound short as needed.

Multiple Waves

Missile Command is not designed to be limited to a single wave. Ideally, the player can continue until they run out of cities. Again, we did that in our video above. To support multiple waves, you have to do a few things.

First of all you need a way to specific multiple waves. That will definitely require a custom wave file. We will not tell you how to design this file. That is part of the challenge.

In addition, you need a way to specify the surviving cities for each wave. So now a Wave object is not just defined by the wave data. It is defined by the wave data and the surviving city list.

It is customary in Missile Command to give the player a new city whenever they reach a new score threshold (e.g. a few thousand points or so). You are welcome to do this, but it is not required. If you do, you need to display a message informing the player each time they get a new city.

Bonus Enemies

The standard Missile Command has threats beyond bombs. It has planes that fly over and launch bombs of their own. It has satellites that can hover and and launch multiple bombs. It has drones that dive bomb erratically, making it hard to tell where they are going. And even the normal bombs, sometimes they can splinter into multiple bombs.

You are welcome to add any of these that you want. You can even think of new challenges. But any challenge that you add must be shown off in a custom wave file. These challenges should not appear in any of the provided waves.

Animation

To keep this game simple, the animation in this game is very rudimentary. To be fair, this is a game from the 1980s, when graphics were not that much to write home about. Graphic sprites (an optional topic covered in Lab 23) were not introduced until the mid to late 80s.

That means there is a lot of modernization you could do for this game. You could add proper sprites for the rockets. You could add cool explosions. You could even put animated people in the city windows. Do whatever you want to do.

However, as you modernize the graphics, make sure not to change the core gameplay. Rockets should still explode slowly and bombs should be destroyed when they are in the blast radius of this explosion.

Your Imagination

What else have you always wanted a game like this to do? Do you want to have weapons other than rockets? Maybe an EMP super weapon? Or maybe a drone that you fly with a mouse at the same time you launch your missiles? With that said, do not go too wild with power-ups or collectibles. We much prefer a few innovations that greatly improve the play as opposed to a screen filled with gizmos.

Again, you can make any modifications to the game you want, but the core gameplay must be there. If we load the game on any of the wave files that we have provided, it should play as normal with nothing more than cosmetic differences. New features like this are only allowed in new wave files.


Finishing Touches

Before submitting anything, test your program to see that it works. Play for a while and make sure that as many parts of it as you can check are working. Cycle between multiple wave files.

When you are done, reread the specifications of all your methods and functions (including those we stubbed in for you), and be sure that your specifications are clear and that your functions follow their specifications. If you implemented extensions, add a README file that explains your extensions very clearly. You should also add a README if you decide to use non-standard controls (anything other than the arrow keys or the number keys to fire).

As part of this assignment, we expect you to follow our style guidelines:

  • You have indented with spaces, not tabs (Pulsar handles this automatically).
  • Classes are separated from each other by two blank lines
  • Methods are separated from each other by a single blank line
  • Class contents are ordered as follows: getters/setters, initializer, non-hidden methods, hidden methods
  • Lines are short enough that horizontal scrolling is not necessary (about 80 chars)
  • The specifications for all of the methods and classes are complete
  • Specifications are immediately after the method header and indented
  • No method is more than 25 lines long, not including the specification

We are serious about the last one. This is a potential 10 point deduction.

Turning it In

You are potentially modifying a lot of files in this assignment. At a bare minimum, your are modifying app.py, wave.py, and models.py. You might be modifying consts.py. You might have extra art and sound files.

To simplify the submission process, we are not asking you upload each individual file. Instead, put all your files in a zip file called shield.zip and submit this instead. We need to be able to play your game, and if anything is missing, we cannot play it.

If you did add any extensions, then your submission must include a README file documenting all of the extensions you added. You should also tell us what wave files we should run in order to experience them. We cannot give you credit for extensions if we do not know about this. If there is no README file, we will assume the game has no extensions.

Completing the Survey

One last time, we need you to do a survey. As always, the survey will ask about things such as how long you spent on the assignment and your impression of the difficulty. This is the return of an assignment that we had abandoned because it was too hard. We have tried really hard to make it feasible this time. We are interested in your opinion.

Please try to complete the survey within a day of turning in this assignment. Remember that participation in surveys comprises 1% of your final grade.