Skip to content

Commit 72155f9

Browse files
committed
Finish README.md, add saucer pic, add template spaceinvaders.py
1 parent 6cd553d commit 72155f9

File tree

3 files changed

+172
-62
lines changed

3 files changed

+172
-62
lines changed

Day2/README.md

Lines changed: 155 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,10 @@
1-
##Installation
1+
#Installation
22

33
If you have Python and pygame already installed on your computer, you should be good to go! Otherwise, the easiest way to get started is to go to http://helloworldbookblog.com/tools/ and download the installer for your operating system. This will include everything you need. We will be using Python version 2.X.
44

55
If there are installation issues, http://repl.it/ can be used for the first week. It cannot be used for the second week though, because graphics and pygame are required.
66

7-
## Review of Python Classes
7+
# Review of Python Classes
88

99
A class can be thought of as a blueprint that you can use to create many copies of something.
1010

@@ -18,7 +18,6 @@ Classes begin with the `class` keyword, followed by the class name. Classes can
1818
bob = Person()
1919
bob.name = "Bob"
2020

21-
2221
### Example
2322

2423
The following is a class called Book
@@ -35,48 +34,178 @@ As a warm up, type the class into Python and do the following:
3534

3635
3. Create two books by different authors. Get each of them to print out their title and author.
3736

37+
# Project - Space Invaders!
38+
39+
We're going to use classes to make an arcade classic: Space Invaders!
40+
41+
## Running the code
42+
43+
Open up `spaceinvaders.py` using IDLE. Hit F5 or go to Run, Run Module to run the program.
44+
45+
You should see your green spaceship. You can move this spaceship by pressing and holding the left and right keys. You can shoot by pressing space. So far, there's not a lot to shoot. This isn't much fun, is it?
46+
47+
Over the course of this class, we'll implement aliens that you can shoot, and who will also shoot back at you!
48+
49+
## Code walkthrough
50+
51+
At the top of the code, we have two functions (not part of any class) that are used for detecting whether rectangles intersect. This is library code borrowed from the book Invent with Python.
52+
53+
We then define a screen size, initialize pygame, and create the screen that we're going to be using to implement the game
54+
55+
pygame.init()
56+
57+
SCREEN_WIDTH = 640
58+
SCREEN_HEIGHT = 480
59+
60+
screen = pygame.display.set_mode([SCREEN_WIDTH,SCREEN_HEIGHT])
61+
62+
This is followed by some arrays: `player_missiles` and `alien_missiles`. These arrays contain the missiles that the player and the aliens shoot at each other. At the moment, they're empty.
63+
64+
After that come our classes. The first class is our Spaceship. This class has three properties: an X position on the screen, a Y position, and a picture. In this case, we're going to load up `spaceship.png` from the directory that this file is in.
65+
66+
class Spaceship:
67+
xpos = 0
68+
ypos = 0
69+
picture = pygame.image.load('spaceship.png')
70+
71+
We then have a constructor that requires defining the x and y positions of the spaceship
72+
73+
def __init__(self, x, y):
74+
self.xpos = x
75+
self.ypos = y
76+
77+
We also have 5 methods:
78+
79+
1. `moveRight` - Moves the ship 5 pixels to the right
80+
2. `moveLeft` - Moves the ship 5 pixels to the left
81+
3. `shoot` - Creates a missile object with a position near the ship and adds it to the global player missile array
82+
4. `get_rect` - Gets the bounding rectangle for the player. This is used to calculate if the player got hit
83+
5. `draw` - Blits the player's picture at the right position on the screen
84+
85+
We also have classes for Aliens and Missiles. Notice that they are all very, very similar to one another. Hmm...
86+
87+
After the classes, we have an event loop that does the following things
88+
1. Detects key presses from the player and makes the player's ship do things
89+
2. Moves the player's misiles around and draws them
90+
3. Moves the aliens' missiles around and draws them (TO DO!)
91+
4. Moves the aliens around and draws them
92+
5. Detects whether all the aliens are gone, or if one has reached the bottom (TO DO!)
93+
94+
## Finishing up the basic game
95+
96+
At the moment, we need to make this a game! We'll need to add aliens, give them the ability to shoot, and add win/lose conditions for the player.
97+
98+
### Making aliens
99+
100+
We'll need to make some aliens to make the game interesting. In order to do this, we'll need to put some aliens in the alien array.
101+
102+
aliens = []
103+
# Make a grid of aliens
104+
# Your code here!
105+
106+
Make a 8 by 4 grid of aliens. Remember that the constructor for the Alien class requires an x and y position! (x = horizontal position, y = vertical)
107+
108+
Hint: Use for loops - one for the horizontal and one for the vertical direction
109+
110+
### Completing the Alien class
111+
112+
So, we've made a couple aliens, but if we run the program, we can't see them! Where are they?
113+
114+
This is because we don't have any code for the aliens' `draw` method. Let's complete the draw method!
115+
116+
Next up is the `shoot` method. It wouldn't be fun if the aliens couldn't shoot, right?
117+
118+
Finally, we'll need to tell the aliens when to shoot. Keep in mind that there are many of them, and the event loop is very fast. In this part of the code:
119+
120+
for alien in aliens:
121+
alien.draw()
122+
# Aliens shoot randomly
123+
# Your code here!
124+
125+
You need to tell when the aliens when to shoot. (Hint: use random.randint !)
126+
127+
### Detecting collisions between Aliens and player missiles
128+
129+
Now we're getting somewhere - we can shoot the aliens and they can shoot us. However, something is wrong - the missiles fly right by and do nothing!
130+
131+
We'll need to figure out when missiles collide with aliens. In this part of the code:
132+
133+
# Move, detect collisions, and draw the player's missiles
134+
for missile in player_missiles:
135+
missile.move()
136+
# Determine if the missile hit an alien. If so, the missile is spent
137+
# Your code here!
138+
139+
Figure out when the missile has hit any of the aliens.
140+
141+
Hint #1: Loop over the list of aliens and use `doRectsOverlap`. What are the `get_rect()` methods for?
142+
143+
Hint #2: When an alien is hit, remove it from the list of aliens and make the missile "spent"
144+
145+
### Winning and Losing conditions
146+
147+
In Space Invaders, the player wins when the player has shot all the aliens. The player loses when they either get shot by an alien, or if an alien reaches the bottom of the screen.
148+
149+
Let's implement these conditions. First, let's check to see if the player has gotten shot (the spaceship overlaps with an alien's missile) by adding a check to this section of code. The player should immediately lose (and the game is over) whenever the spaceship is hit.
150+
151+
for missile in alien_missiles:
152+
missile.move()
153+
# Detects collisions between the player and the alien missile
154+
# The player loses if they touch an alien missile
155+
# Your code here!
156+
157+
Hint: Take a look at the example for when a player missile hits an alien
158+
159+
Hint: The game is over when `running` is set to `False`
160+
161+
162+
Finally, we need to see if there are any aliens left, or if an alien reaches the bottom of the screen. The player wins if there are no more aliens, but loses if any of the aliens reach the bottom!
38163

164+
Hint: Loop through the aliens to see if any of them have a `ypos` greater than a certain amount...
39165

40-
1. Give each student a favorite color property. Then write a method that will have the student tell us his favorite color.
41166

42-
2. Write a class method that will have each Student say his name and age and favorite color.
167+
## Projects!
43168

44-
3. Create a few more students: `jane` and `betty`. Give them ages, names, and favorite colors.
169+
We now have a complete, but extremely basic game of space invaders. The rest of this class is to make this game _awesome_.
45170

46-
4. Bonus: Give each student a best friend property (hint: use classes!). Write a method to return his/her best friend's name
171+
### 1. Make the alien change pictures every frame
47172

48-
## Constructors
173+
In space invaders, the aliens look different every single frame. There's another picture in here called `alien2.png`. Use it and change the appearance of all the aliens every single frame.
49174

50-
In the last section, we were creating students without names and ages. We then gave names and ages to the students later. It doesn't make any sense to make Students with names and ages, so let's do the folowwing:
175+
(Hint: Change the alien's picture every time its move method is called)
51176

52-
def __init__(self, name, age):
53-
self.name = name
54-
self.age = age
177+
### 2. Keep score
55178

56-
Try to run your program again, and then use the same console command as before:
179+
It's much more fun when we can keep the player's score. Whenever the player shoots an alien, give the player 25 points. Then, make a point display to show the player. Here's some of the boilerplate code for adding text to the screen:
57180

58-
bobby = Student()
181+
myfont = pygame.font.SysFont("Arial", 15)
182+
score_label = myfont.render(str(score1), 1, pygame.color.THECOLORS['white'])
183+
screen.blit(score1_labe, (5, 10))
59184

60-
What happens?
185+
### 3. Give the player multiple lives
61186

62-
You get an error. Since we have an constructor now, you can no longer create a Student without providing enough information to fill in the constructor arguments. Try this:
187+
The player shouldn't automatically die whenever they get shot - they should have 3 lives. The player only loses when they lose all 3 of their lives. Make a display for letting the player know how many lives they have left next to the score display.
63188

64-
bobby = Student("bobby", 10)
189+
### 4. Make a flying saucer zip across the top of the screen
65190

66-
It should work.
191+
Remember how there was a saucer that sometimes appears at the top of the screen in space invaders? Let's implement that!
67192

68-
The constructors in Python have the name `__init__`, and have an extra argument you do not need to provide when you instantiate an object - in this case: `self`.
193+
Make a new class called Saucer, use the `saucer.png` image provided in this repo, and every now and then, move a saucer from the right to the left across the very top of the screen.
69194

70-
## Lab - Deck of Cards
195+
Whenever the player shoots the saucer, give the player 100 points.
71196

72-
You will be implementing a deck of cards. Open up the file `DeckCards.py` in this directory inside IDLE.
197+
### Other ideas
73198

74-
1. Complete the card class. Each card has a suit (hearts, diamonds, spades, clubs) and a value (A, J, K, Q, 2-10)
199+
- Give the aliens an explosion animation whenever they get shot
200+
- Make a YOU WIN and a YOU LOSE screen in the pygame window
201+
- The aliens' movement isn't too great - they stay in formation even after most of them are gone. Can you make smaller formations of aliens more challenging to shoot?
202+
- Give the player some shields (they can take some hits) to hide behind
203+
- Make different kinds of aliens - there's only 1 kind right now
75204

76-
2. Complete the deck class. Each deck will have 52 cards - 13 Hearts, 13 Spades, 13 Clubs, 13 Diamonds, each suit with cards A, J, K, Q, 2 to 10.
205+
## Further reading
77206

78-
3. Complete the `dealCards` and `remainingCards` methods. See the code for details.
207+
Remember at the beginning of the class we noted how similar the player, alien, and missile classes were? Doesn't the code look very similar too? This is where `inheritence` comes into play. In Object Oriented Programming, inheritence is a way of saying that "this class is a kind of this other class". For example, an Orange is a Fruit, or a Dog is an Animal.
79208

80-
4. Now write a program that uses the Deck class to deal random cards.
209+
Recommended reading is here: https://docs.python.org/2/tutorial/classes.html .
81210

82-
5. Try to implement some simple card games using your Card and Deck classes.
211+
Special challenge is to re-write the Player, Alien, and Missiles classes to all inherit from a common class, so we don't have to reimplement `draw` for any of them.

Day2/saucer.png

4.82 KB
Loading

Day2/spaceinvaders.py

Lines changed: 17 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -63,8 +63,7 @@ class Alien:
6363
xpos = 0
6464
ypos = 0
6565
xspeed = 2
66-
picture1 = pygame.image.load('alien1.png')
67-
picture2 = pygame.image.load('alien2.png')
66+
picture = pygame.image.load('alien1.png')
6867

6968
def __init__(self, x, y):
7069
self.xpos = x
@@ -73,19 +72,17 @@ def __init__(self, x, y):
7372
def move(self, x, y):
7473
self.xpos += x
7574
self.ypos += y
76-
self.picture3 = self.picture1
77-
self.picture1 = self.picture2
78-
self.picture2 = self.picture3
7975

8076
def shoot(self):
81-
missile = Missile(self.xpos + 16, self.ypos + 32, 10)
82-
alien_missiles.append(missile)
77+
# Your code here!
78+
pass
8379

8480
def get_rect(self):
8581
return pygame.Rect(self.xpos, self.ypos, 32, 32)
8682

8783
def draw(self):
88-
screen.blit(self.picture1, (self.xpos, self.ypos))
84+
# Your code here!
85+
pass
8986

9087

9188
class Missile:
@@ -116,9 +113,8 @@ def isSpent(self):
116113
# Create all the objects and variables!
117114
spaceship = Spaceship(200, 440)
118115
aliens = []
119-
for x in range(1,8):
120-
for y in range(1,4):
121-
aliens.append(Alien(x * 50 + 10, y * 50 + 10))
116+
# Make a grid of aliens
117+
# Your code here!
122118

123119
running = True
124120
ticks = 0
@@ -149,27 +145,21 @@ def isSpent(self):
149145
# Move, detect collisions, and draw the player's missiles
150146
for missile in player_missiles:
151147
missile.move()
152-
for alien in aliens:
153-
if doRectsOverlap(alien.get_rect(), missile.get_rect()):
154-
aliens.remove(alien)
155-
missile.spent = True
148+
149+
# Determine if the missile hit an alien. If so, the missile is spent
150+
# Your code here!
156151

157152
if missile.isSpent():
158153
player_missiles.remove(missile)
159154
missile.draw()
160155

161-
# Move, detect collisions, and draw the player's missiles
156+
157+
# Move, detect collisions, and draw the aliens' missiles
162158
for missile in alien_missiles:
163159
missile.move()
164-
165-
if doRectsOverlap(spaceship.get_rect(), missile.get_rect()):
166-
print "YOU LOSE"
167-
running = False
168-
missile.spent = True
169-
170-
if missile.isSpent():
171-
alien_missiles.remove(missile)
172-
missile.draw()
160+
# Detects collisions between the player and the alien missile
161+
# The player loses if they touch an alien missile
162+
# Your code here!
173163

174164
# Move all the aliens
175165
# The more aliens there are, the slower they move
@@ -189,20 +179,11 @@ def isSpent(self):
189179
for alien in aliens:
190180
alien.draw()
191181
# Aliens shoot randomly
192-
# 0.05 percent change per frame that an alien shoots
193-
if (random.randint(1,1000) < 5):
194-
alien.shoot()
182+
# Your code here!
195183

196184
# If there are no more aliens, the player wins
197-
if len(aliens) == 0:
198-
print "YOU WIN!"
199-
running = False
200-
201185
# If any alien reaches the bottom of the screen, the player loses
202-
for alien in aliens:
203-
if alien.ypos > SCREEN_HEIGHT - 64:
204-
print "YOU LOSE"
205-
running = False
186+
# Your code here!
206187

207188
# Draw the spaceship
208189
spaceship.draw()

0 commit comments

Comments
 (0)