Web   ·   Wiki   ·   Activities   ·   Blog   ·   Lists   ·   Chat   ·   Meeting   ·   Bugs   ·   Git   ·   Translate   ·   Archive   ·   People   ·   Donate
summaryrefslogtreecommitdiffstats
path: root/SpaceWar.py
blob: cfb488cea2c76c0c650ce775291f72afc3471ae9 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
#! /usr/bin/env python
# -*- coding: utf-8 -*-
#
# SpaceWar
# Copyright (C) 2007
# Copyright (C) 2013, Alan Aguiar
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
# Contact information:
# Alan Aguiar <alanjas@gmail.com>

import gtk
import itertools
import pygame
import random

class SpaceWar():
    """Top-level application class."""
    
    def __init__(self):
        self.count = 0
        self.level = 1

    def load_all(self):
        # Dun dun duuuuuuuun
        pygame.display.init()
        
        # Initialize the screen surface
        self.screen = pygame.display.get_surface()
        if not(self.screen):
            info = pygame.display.Info()
            size = (info.current_w, info.current_h)
            self.screen = pygame.display.set_mode(size, pygame.FULLSCREEN)
        self.rect = self.screen.get_rect()

        # Core objects
        self.clock = pygame.time.Clock()
        self.running = True
        
        # images
        self.ship_img = pygame.image.load('img/Space/ship1.png').convert_alpha()
        self.shot_img = pygame.image.load('img/Space/bullet4.png').convert_alpha()
        self.enemy_img = pygame.image.load('img/OldSchool/skully.png').convert_alpha()

        pygame.mixer.init()
        self.shot_sound = pygame.mixer.Sound('sounds/shot.wav')

        # Game objects
        self.ship = Ship(self)
        self.ship.rect.midbottom = self.rect.midbottom
        self.shots = pygame.sprite.Group()
        self.enemies = pygame.sprite.Group()
        # Add enemies
        self.add_enemies(self.level)

    def add_enemies(self, level):
        for l in range(level):
            enemy = Enemy(self)
            x = random.randint(0, self.rect[2])
            y = random.randint(20, self.rect[3] - 100)
            enemy.rect.center = x, y
            enemy.direction = random.choice((-1 , 1))
            self.enemies.add(enemy)

    def run(self):
        self.load_all()
        while self.running:
            # Timing phase
            delta = self.clock.tick(30)
            while gtk.events_pending():
                gtk.main_iteration()
            # Event phase
            for evt in pygame.event.get():
                if evt.type == pygame.QUIT:
                    self.running = False
                elif evt.type == pygame.KEYDOWN:
                    if evt.key == pygame.K_ESCAPE:
                        self.running = False
                    if evt.key == pygame.K_LEFT:
                        self.ship.direction = -1
                    elif evt.key == pygame.K_RIGHT:
                        self.ship.direction = 1
                    elif evt.key == pygame.K_SPACE:
                        new_shot = Shot(self)
                        new_shot.rect.midbottom = self.ship.rect.midtop
                        self.shots.add(new_shot)
                elif evt.type == pygame.KEYUP:
                    if evt.key == pygame.K_LEFT and self.ship.direction == -1:
                        self.ship.direction = 0
                    elif evt.key == pygame.K_RIGHT and self.ship.direction == 1:
                        self.ship.direction = 0
            
            # Update phase
            self.ship.update(delta)
            self.shots.update(delta)
            self.enemies.update(delta)
            # Look for shot-enemy collisions
            pygame.sprite.groupcollide(self.enemies, self.shots, True, True)

            if len(self.enemies) == 0:
                self.count = self.count + 1

            if self.count > 10:
                self.count = 0
                self.level = self.level + 1
                self.add_enemies(self.level)
            
            # Display phase
            self.screen.fill((0,0,0))
            for spr in self.enemies:
                self.screen.blit(spr.image, spr.rect, spr.source_rect)
            self.shots.draw(self.screen)
            self.screen.blit(self.ship.image, self.ship.rect)
            pygame.display.flip()
            

class Ship(pygame.sprite.Sprite):
    """The player-controlled ship."""

    def __init__(self, parent):
        super(Ship, self).__init__()
        self.parent = parent
        self.image = parent.ship_img
        self.rect = self.image.get_rect()
        self.direction = 0
        self.speed = 0.1

    def update(self, delta):
        self.rect.move_ip(delta*self.direction*self.speed, 0)
        self.rect.clamp_ip(self.parent.rect)


class Shot(pygame.sprite.Sprite):
    """A single shot fired by the player."""

    def __init__(self, parent):
        super(Shot, self).__init__()
        self.parent = parent
        self.image = parent.shot_img
        self.rect = self.image.get_rect()
        self.speed = 0.2
        
        # Load and play the shot sound
        self.sound = parent.shot_sound
        self.sound.play()

    def update(self, delta):
        self.rect.move_ip(0, -1*delta*self.speed)
        if not self.rect.colliderect(self.parent.rect):
            self.kill()


class Enemy(pygame.sprite.Sprite):
    """An enemy ship."""
    
    def __init__(self, parent):
        super(Enemy, self).__init__()
        self.parent = parent
        self.image = parent.enemy_img
        self.rect = self.image.get_rect()
        self.direction = 1
        self.speed = 0.05
        
        # Setup the animation frames
        self.n_frames = 2
        self.rect.width /= self.n_frames # Make self.rect to be the size of one frame
        self.source_rects = itertools.cycle([self.rect.move(x*self.rect.width, 0) for x in xrange(self.n_frames)])
        self.source_rect = self.source_rects.next() # Load the position of the first frame
        
        # Setup the animation timing
        self.time_per_frame = 200 # ms per frame in the animation
        self.time_left = self.time_per_frame

    def update(self, delta):
        self.time_left -= delta
        if self.time_left <= 0:
            self.time_left += self.time_per_frame
            self.source_rect = self.source_rects.next()
        
        self.rect.move_ip(delta*self.direction*self.speed, 0)
        if self.direction == 1 and self.rect.right >= self.parent.rect.right:
            self.direction *= -1
            self.rect.right = self.parent.rect.right
        elif self.direction == -1 and self.rect.left <= self.parent.rect.left:
            self.direction *= -1
            self.rect.left = self.parent.rect.left

def main():
    s = SpaceWar()
    s.run()

if __name__ == '__main__':
    main()