Smalltalk Programming
Lesson 14

Your shooter game will not be cool if it did not shoot. Also, you certainly do not want to code the enemies before you have a way to shoot them. This means that you will start coding the changes needed to shoot first.

1. Remember in the design phase that it was determined that the ship does the shooting. But before you add the code for the ship to shoot, you will want to create an object that can be shot from the ship.

2. Create a Shot class using the code below and then save your changes.

EllipseMorph subclass: #Shot
    
instanceVariableNames: ''
    
classVariableNames: ''
    
poolDictionaries: ''
    
category: 'ShooterGame'

3. What type of Morph is being used for your shot? What will this type of Morph look like?

4. Type in the code below in your Shot class to initialize the shot instance. Save the changes.

initialize

    
super initialize.
    
self color: Color red.
    
self extent: 16 @ 16

5. Look at each line of code. Can you figure out what each line of code is doing?

6. Now you can add the ability for your ship to actually shoot. Because it will be your ship that is shooting, make the code change below in your Ship class. Type in the code below and then save the changes.

shoot

    
| shot |
    
shot := Shot new.
    
shot position: self topCenter - shot bottomCenter.
    
owner addMorph: shot

7. Look at each line of code. Can you figure out what each line of code is doing?

8. Now that you have added the code to shoot, try shooting from your ship.

9. You may or may not have actually tried to shoot using your ship. This brings up an interesting question – what keyboard key(s) should be used for shooting? If you did try to shoot, what key(s) did you try to use?

10. A big part of programming is to consider how a person (or user) will want use your program. It is important that your program works in a way that the user needs or wants it to. After all, they will be using the program, so it should be made for what is best for them.

11. Popular keyboard keys for shooting are the space key and the “f” key. Make the following code changes to Ship>>keystroke: so that these two new keystrokes will be used to create (or instantiate) a shot.

keystroke: keyString

    
keyString = '<left>' ifTrue: [self moveLeft].
    
keyString = '<right>' ifTrue: [self moveRight].
    
keyString = '<up>' ifTrue: [self moveUp].
    
keyString = '<down>' ifTrue: [self moveDown].
    
keyString = 'f' ifTrue: [self shoot].
    
keyString = ' ' ifTrue: [self shoot]

12. Test your new code. What do you notice? What else needs to be done?

13. Save and Quit your Smalltalk image.

Download the PDF version.