1. Richard Jones
  2. pygame-tutorial

Commits

Richard Jones  committed f2dd0de

renaming of steps

  • Participants
  • Parent commits fff32e4
  • Branches default

Comments (0)

Files changed (29)

File 02-handle-events.py

-import pygame
-
-pygame.init()
-screen = pygame.display.set_mode((640, 480))
-
-running = True
-while running:
-    for event in pygame.event.get():
-        if event.type == pygame.QUIT:
-            running = False
-        if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
-            running = False
-

File 02-main-loop.py

View file
+import pygame
+
+pygame.init()
+screen = pygame.display.set_mode((640, 480))
+
+running = True
+while running:
+    for event in pygame.event.get():
+        if event.type == pygame.QUIT:
+            running = False
+        if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
+            running = False
+

File 025-refactoring.py

-import pygame
-
-class Game(object):
-    def main(self, screen):
-        while 1:
-            for event in pygame.event.get():
-                if event.type == pygame.QUIT:
-                    return
-                if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
-                    return
-
-if __name__ == '__main__':
-    pygame.init()
-    screen = pygame.display.set_mode((640, 480))
-    Game().main(screen)
-

File 03-drawing.py

-import pygame
-
-class Game(object):
-    def main(self, screen):
-        clock = pygame.time.Clock()
-
-        image = pygame.image.load('player.png')
-
-        while 1:
-            clock.tick(30)
-
-            for event in pygame.event.get():
-                if event.type == pygame.QUIT:
-                    return
-                if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
-                    return
-
-            screen.fill((200, 200, 200))
-            screen.blit(image, (320, 240))
-            pygame.display.flip()
-
-if __name__ == '__main__':
-    pygame.init()
-    screen = pygame.display.set_mode((640, 480))
-    Game().main(screen)
-

File 03-structure.py

View file
+import pygame
+
+class Game(object):
+    def main(self, screen):
+        while 1:
+            for event in pygame.event.get():
+                if event.type == pygame.QUIT:
+                    return
+                if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
+                    return
+
+if __name__ == '__main__':
+    pygame.init()
+    screen = pygame.display.set_mode((640, 480))
+    Game().main(screen)
+

File 04-drawing.py

View file
+import pygame
+
+class Game(object):
+    def main(self, screen):
+        clock = pygame.time.Clock()
+
+        image = pygame.image.load('player.png')
+
+        while 1:
+            clock.tick(30)
+
+            for event in pygame.event.get():
+                if event.type == pygame.QUIT:
+                    return
+                if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
+                    return
+
+            screen.fill((200, 200, 200))
+            screen.blit(image, (320, 240))
+            pygame.display.flip()
+
+if __name__ == '__main__':
+    pygame.init()
+    screen = pygame.display.set_mode((640, 480))
+    Game().main(screen)
+

File 04-move.py

-import pygame
-
-class Game(object):
-    def main(self, screen):
-        clock = pygame.time.Clock()
-
-        image = pygame.image.load('player.png')
-        image_x = 320
-        image_y = 240
-
-        while 1:
-            clock.tick(30)
-
-            for event in pygame.event.get():
-                if event.type == pygame.QUIT:
-                    return
-                if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
-                    return
-
-            key = pygame.key.get_pressed()
-            if key[pygame.K_LEFT]:
-                image_x -= 10
-            if key[pygame.K_RIGHT]:
-                image_x += 10
-            if key[pygame.K_UP]:
-                image_y -= 10
-            if key[pygame.K_DOWN]:
-                image_y += 10
-
-            screen.fill((200, 200, 200))
-            screen.blit(image, (image_x, image_y))
-            pygame.display.flip()
-
-if __name__ == '__main__':
-    pygame.init()
-    screen = pygame.display.set_mode((640, 480))
-    Game().main(screen)
-

File 05-animation.py

View file
+import pygame
+
+class Game(object):
+    def main(self, screen):
+        clock = pygame.time.Clock()
+
+        image = pygame.image.load('player.png')
+        image_x = 320
+        image_y = 240
+
+        while 1:
+            clock.tick(30)
+
+            for event in pygame.event.get():
+                if event.type == pygame.QUIT:
+                    return
+                if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
+                    return
+
+            key = pygame.key.get_pressed()
+            if key[pygame.K_LEFT]:
+                image_x -= 10
+            if key[pygame.K_RIGHT]:
+                image_x += 10
+            if key[pygame.K_UP]:
+                image_y -= 10
+            if key[pygame.K_DOWN]:
+                image_y += 10
+
+            screen.fill((200, 200, 200))
+            screen.blit(image, (image_x, image_y))
+            pygame.display.flip()
+
+if __name__ == '__main__':
+    pygame.init()
+    screen = pygame.display.set_mode((640, 480))
+    Game().main(screen)
+

File 05-sprite.py

-import pygame
-
-class Player(pygame.sprite.Sprite):
-    def __init__(self, *groups):
-        super(Player, self).__init__(*groups)
-        self.image = pygame.image.load('player.png')
-        self.rect = pygame.rect.Rect((320, 240), self.image.get_size())
-
-    def update(self):
-        key = pygame.key.get_pressed()
-        if key[pygame.K_LEFT]:
-            self.rect.x -= 10
-        if key[pygame.K_RIGHT]:
-            self.rect.x += 10
-        if key[pygame.K_UP]:
-            self.rect.y -= 10
-        if key[pygame.K_DOWN]:
-            self.rect.y += 10
-
-class Game(object):
-    def main(self, screen):
-        clock = pygame.time.Clock()
-
-        sprites = pygame.sprite.Group()
-        player = Player(sprites)
-
-        while 1:
-            clock.tick(30)
-
-            for event in pygame.event.get():
-                if event.type == pygame.QUIT:
-                    return
-                if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
-                    return
-
-            sprites.update()
-            screen.fill((200, 200, 200))
-            sprites.draw(screen)
-            pygame.display.flip()
-
-if __name__ == '__main__':
-    pygame.init()
-    screen = pygame.display.set_mode((640, 480))
-    Game().main(screen)
-

File 06-smooth.py

-import pygame
-
-class Player(pygame.sprite.Sprite):
-    def __init__(self, *groups):
-        super(Player, self).__init__(*groups)
-        self.image = pygame.image.load('player.png')
-        self.rect = pygame.rect.Rect((320, 240), self.image.get_size())
-
-    def update(self, dt):
-        key = pygame.key.get_pressed()
-        if key[pygame.K_LEFT]:
-            self.rect.x -= 300 * dt
-        if key[pygame.K_RIGHT]:
-            self.rect.x += 300 * dt
-        if key[pygame.K_UP]:
-            self.rect.y -= 300 * dt
-        if key[pygame.K_DOWN]:
-            self.rect.y += 300 * dt
-
-class Game(object):
-    def main(self, screen):
-        clock = pygame.time.Clock()
-
-        sprites = pygame.sprite.Group()
-        player = Player(sprites)
-
-        while 1:
-            dt = clock.tick(30)
-
-            for event in pygame.event.get():
-                if event.type == pygame.QUIT:
-                    return
-                if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
-                    return
-
-            sprites.update(dt / 1000.)
-            screen.fill((200, 200, 200))
-            sprites.draw(screen)
-            pygame.display.flip()
-
-if __name__ == '__main__':
-    pygame.init()
-    screen = pygame.display.set_mode((640, 480))
-    Game().main(screen)
-

File 06-sprite.py

View file
+import pygame
+
+class Player(pygame.sprite.Sprite):
+    def __init__(self, *groups):
+        super(Player, self).__init__(*groups)
+        self.image = pygame.image.load('player.png')
+        self.rect = pygame.rect.Rect((320, 240), self.image.get_size())
+
+    def update(self):
+        key = pygame.key.get_pressed()
+        if key[pygame.K_LEFT]:
+            self.rect.x -= 10
+        if key[pygame.K_RIGHT]:
+            self.rect.x += 10
+        if key[pygame.K_UP]:
+            self.rect.y -= 10
+        if key[pygame.K_DOWN]:
+            self.rect.y += 10
+
+class Game(object):
+    def main(self, screen):
+        clock = pygame.time.Clock()
+
+        sprites = pygame.sprite.Group()
+        player = Player(sprites)
+
+        while 1:
+            clock.tick(30)
+
+            for event in pygame.event.get():
+                if event.type == pygame.QUIT:
+                    return
+                if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
+                    return
+
+            sprites.update()
+            screen.fill((200, 200, 200))
+            sprites.draw(screen)
+            pygame.display.flip()
+
+if __name__ == '__main__':
+    pygame.init()
+    screen = pygame.display.set_mode((640, 480))
+    Game().main(screen)
+

File 07-background.py

-import pygame
-
-class Player(pygame.sprite.Sprite):
-    def __init__(self, *groups):
-        super(Player, self).__init__(*groups)
-        self.image = pygame.image.load('player.png')
-        self.rect = pygame.rect.Rect((320, 240), self.image.get_size())
-
-    def update(self, dt):
-        key = pygame.key.get_pressed()
-        if key[pygame.K_LEFT]:
-            self.rect.x -= 300 * dt
-        if key[pygame.K_RIGHT]:
-            self.rect.x += 300 * dt
-        if key[pygame.K_UP]:
-            self.rect.y -= 300 * dt
-        if key[pygame.K_DOWN]:
-            self.rect.y += 300 * dt
-
-class Background(pygame.sprite.Sprite):
-    def __init__(self, *groups):
-        super(Background, self).__init__(*groups)
-        self.image = pygame.image.load('background.png')
-        self.rect = pygame.rect.Rect((0, 0), self.image.get_size())
-
-class Game(object):
-    def main(self, screen):
-        clock = pygame.time.Clock()
-
-        sprites = pygame.sprite.OrderedUpdates()
-        background = Background()
-        sprites.add(background)
-        player = Player()
-        sprites.add(player)
-
-        while 1:
-            dt = clock.tick(30)
-
-            for event in pygame.event.get():
-                if event.type == pygame.QUIT:
-                    return
-                if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
-                    return
-
-            sprites.update(dt / 1000.)
-            sprites.draw(screen)
-            pygame.display.flip()
-
-if __name__ == '__main__':
-    pygame.init()
-    screen = pygame.display.set_mode((640, 480))
-    Game().main(screen)
-

File 07-smooth.py

View file
+import pygame
+
+class Player(pygame.sprite.Sprite):
+    def __init__(self, *groups):
+        super(Player, self).__init__(*groups)
+        self.image = pygame.image.load('player.png')
+        self.rect = pygame.rect.Rect((320, 240), self.image.get_size())
+
+    def update(self, dt):
+        key = pygame.key.get_pressed()
+        if key[pygame.K_LEFT]:
+            self.rect.x -= 300 * dt
+        if key[pygame.K_RIGHT]:
+            self.rect.x += 300 * dt
+        if key[pygame.K_UP]:
+            self.rect.y -= 300 * dt
+        if key[pygame.K_DOWN]:
+            self.rect.y += 300 * dt
+
+class Game(object):
+    def main(self, screen):
+        clock = pygame.time.Clock()
+
+        sprites = pygame.sprite.Group()
+        player = Player(sprites)
+
+        while 1:
+            dt = clock.tick(30)
+
+            for event in pygame.event.get():
+                if event.type == pygame.QUIT:
+                    return
+                if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
+                    return
+
+            sprites.update(dt / 1000.)
+            screen.fill((200, 200, 200))
+            sprites.draw(screen)
+            pygame.display.flip()
+
+if __name__ == '__main__':
+    pygame.init()
+    screen = pygame.display.set_mode((640, 480))
+    Game().main(screen)
+

File 075-refactoring.py

-import pygame
-
-class Sprite(pygame.sprite.Sprite):
-    def __init__(self, image, location):
-        super(Sprite, self).__init__()
-        self.image = pygame.image.load(image)
-        self.rect = pygame.rect.Rect(location, self.image.get_size())
-
-class Player(Sprite):
-    def update(self, dt):
-        key = pygame.key.get_pressed()
-        if key[pygame.K_LEFT]:
-            self.rect.x -= 300 * dt
-        if key[pygame.K_RIGHT]:
-            self.rect.x += 300 * dt
-        if key[pygame.K_UP]:
-            self.rect.y -= 300 * dt
-        if key[pygame.K_DOWN]:
-            self.rect.y += 300 * dt
-        self.dirty = 1
-
-class Game(object):
-    def main(self, screen):
-        clock = pygame.time.Clock()
-
-        sprites = pygame.sprite.OrderedUpdates()
-        background = Sprite('background.png', (0, 0))
-        sprites.add(background)
-        player = Player('player.png', (320, 240))
-        sprites.add(player)
-
-        while 1:
-            dt = clock.tick(30)
-
-            for event in pygame.event.get():
-                if event.type == pygame.QUIT:
-                    return
-                if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
-                    return
-
-            sprites.update(dt / 1000.)
-            sprites.draw(screen)
-            pygame.display.flip()
-
-if __name__ == '__main__':
-    pygame.init()
-    screen = pygame.display.set_mode((640, 480))
-    Game().main(screen)
-

File 08-background.py

View file
+import pygame
+
+class Player(pygame.sprite.Sprite):
+    def __init__(self, *groups):
+        super(Player, self).__init__(*groups)
+        self.image = pygame.image.load('player.png')
+        self.rect = pygame.rect.Rect((320, 240), self.image.get_size())
+
+    def update(self, dt):
+        key = pygame.key.get_pressed()
+        if key[pygame.K_LEFT]:
+            self.rect.x -= 300 * dt
+        if key[pygame.K_RIGHT]:
+            self.rect.x += 300 * dt
+        if key[pygame.K_UP]:
+            self.rect.y -= 300 * dt
+        if key[pygame.K_DOWN]:
+            self.rect.y += 300 * dt
+
+class Background(pygame.sprite.Sprite):
+    def __init__(self, *groups):
+        super(Background, self).__init__(*groups)
+        self.image = pygame.image.load('background.png')
+        self.rect = pygame.rect.Rect((0, 0), self.image.get_size())
+
+class Game(object):
+    def main(self, screen):
+        clock = pygame.time.Clock()
+
+        sprites = pygame.sprite.OrderedUpdates()
+        background = Background()
+        sprites.add(background)
+        player = Player()
+        sprites.add(player)
+
+        while 1:
+            dt = clock.tick(30)
+
+            for event in pygame.event.get():
+                if event.type == pygame.QUIT:
+                    return
+                if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
+                    return
+
+            sprites.update(dt / 1000.)
+            sprites.draw(screen)
+            pygame.display.flip()
+
+if __name__ == '__main__':
+    pygame.init()
+    screen = pygame.display.set_mode((640, 480))
+    Game().main(screen)
+

File 08-walls.py

-import pygame
-
-class Sprite(pygame.sprite.Sprite):
-    def __init__(self, image, location):
-        super(Sprite, self).__init__()
-        self.image = pygame.image.load(image)
-        self.rect = pygame.rect.Rect(location, self.image.get_size())
-
-class Player(Sprite):
-    def update(self, dt, game):
-        last = self.rect.copy()
-
-        key = pygame.key.get_pressed()
-        if key[pygame.K_LEFT]:
-            self.rect.x -= 300 * dt
-        if key[pygame.K_RIGHT]:
-            self.rect.x += 300 * dt
-        if key[pygame.K_UP]:
-            self.rect.y -= 300 * dt
-        if key[pygame.K_DOWN]:
-            self.rect.y += 300 * dt
-
-        new = self.rect
-        for cell in pygame.sprite.spritecollide(self, game.walls, False):
-            cell = cell.rect
-            if last.right <= cell.left and new.right > cell.left:
-                new.right = cell.left
-            if last.left >= cell.right and new.left < cell.right:
-                new.left = cell.right
-            if last.bottom <= cell.top and new.bottom > cell.top:
-                new.bottom = cell.top
-            if last.top >= cell.bottom and new.top < cell.bottom:
-                new.top = cell.bottom
-
-class Game(object):
-    def main(self, screen):
-        clock = pygame.time.Clock()
-
-        sprites = pygame.sprite.OrderedUpdates()
-        background = Sprite('background.png', (0, 0))
-        sprites.add(background)
-        player = Player('player.png', (320, 240))
-        sprites.add(player)
-        self.walls = pygame.sprite.Group()
-        for x in range(0, 640, 32):
-            for y in range(0, 480, 32):
-                if x in (0, 640-32) or y in (0, 480-32):
-                    self.walls.add(Sprite('block.png', (x, y)))
-        sprites.add(self.walls)
-
-        while 1:
-            dt = clock.tick(30)
-
-            for event in pygame.event.get():
-                if event.type == pygame.QUIT:
-                    return
-                if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
-                    return
-
-            sprites.update(dt / 1000., self)
-            sprites.draw(screen)
-            pygame.display.flip()
-
-if __name__ == '__main__':
-    pygame.init()
-    screen = pygame.display.set_mode((640, 480))
-    Game().main(screen)
-

File 09-gravity.py

-import pygame
-
-class Sprite(pygame.sprite.Sprite):
-    def __init__(self, image, location):
-        super(Sprite, self).__init__()
-        self.image = pygame.image.load(image)
-        self.rect = pygame.rect.Rect(location, self.image.get_size())
-
-class Player(Sprite):
-    resting = False
-    dy = 0
-    def update(self, dt, game):
-        last = self.rect.copy()
-
-        key = pygame.key.get_pressed()
-        if key[pygame.K_LEFT]:
-            self.rect.x -= 300 * dt
-        if key[pygame.K_RIGHT]:
-            self.rect.x += 300 * dt
-
-        if self.resting and key[pygame.K_SPACE]:
-            self.dy = -500
-        self.dy = min(400, self.dy + 40)
-
-        self.rect.y += self.dy * dt
-
-        new = self.rect
-        self.resting = False
-        for cell in pygame.sprite.spritecollide(self, game.walls, False):
-            cell = cell.rect
-            if last.right <= cell.left and new.right > cell.left:
-                new.right = cell.left
-            if last.left >= cell.right and new.left < cell.right:
-                new.left = cell.right
-            if last.bottom <= cell.top and new.bottom > cell.top:
-                self.resting = True
-                new.bottom = cell.top
-                self.dy = 0
-            if last.top >= cell.bottom and new.top < cell.bottom:
-                new.top = cell.bottom
-                self.dy = 0
-
-class Game(object):
-    def main(self, screen):
-        clock = pygame.time.Clock()
-
-        sprites = pygame.sprite.OrderedUpdates()
-        background = Sprite('background.png', (0, 0))
-        sprites.add(background)
-        player = Player('player.png', (320, 240))
-        sprites.add(player)
-        self.walls = pygame.sprite.Group()
-        for x in range(0, 640, 32):
-            for y in range(0, 480, 32):
-                if x in (0, 640-32) or y in (0, 480-32):
-                    self.walls.add(Sprite('block.png', (x, y)))
-        sprites.add(self.walls)
-
-        while 1:
-            dt = clock.tick(30)
-
-            for event in pygame.event.get():
-                if event.type == pygame.QUIT:
-                    return
-                if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
-                    return
-
-            sprites.update(dt / 1000., self)
-            sprites.draw(screen)
-            pygame.display.flip()
-
-if __name__ == '__main__':
-    pygame.init()
-    screen = pygame.display.set_mode((640, 480))
-    Game().main(screen)
-

File 09-refactoring.py

View file
+import pygame
+
+class Sprite(pygame.sprite.Sprite):
+    def __init__(self, image, location):
+        super(Sprite, self).__init__()
+        self.image = pygame.image.load(image)
+        self.rect = pygame.rect.Rect(location, self.image.get_size())
+
+class Player(Sprite):
+    def update(self, dt):
+        key = pygame.key.get_pressed()
+        if key[pygame.K_LEFT]:
+            self.rect.x -= 300 * dt
+        if key[pygame.K_RIGHT]:
+            self.rect.x += 300 * dt
+        if key[pygame.K_UP]:
+            self.rect.y -= 300 * dt
+        if key[pygame.K_DOWN]:
+            self.rect.y += 300 * dt
+        self.dirty = 1
+
+class Game(object):
+    def main(self, screen):
+        clock = pygame.time.Clock()
+
+        sprites = pygame.sprite.OrderedUpdates()
+        background = Sprite('background.png', (0, 0))
+        sprites.add(background)
+        player = Player('player.png', (320, 240))
+        sprites.add(player)
+
+        while 1:
+            dt = clock.tick(30)
+
+            for event in pygame.event.get():
+                if event.type == pygame.QUIT:
+                    return
+                if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
+                    return
+
+            sprites.update(dt / 1000.)
+            sprites.draw(screen)
+            pygame.display.flip()
+
+if __name__ == '__main__':
+    pygame.init()
+    screen = pygame.display.set_mode((640, 480))
+    Game().main(screen)
+

File 10-tilemap.py

-import pygame
-import tmx
-
-class Sprite(pygame.sprite.Sprite):
-    def __init__(self, image, location):
-        super(Sprite, self).__init__()
-        self.image = pygame.image.load(image)
-        self.rect = pygame.rect.Rect(location, self.image.get_size())
-
-class Player(Sprite):
-    resting = False
-    dy = 0
-    def update(self, dt, game):
-        last = self.rect.copy()
-
-        key = pygame.key.get_pressed()
-        if key[pygame.K_LEFT]:
-            self.rect.x -= 300 * dt
-        if key[pygame.K_RIGHT]:
-            self.rect.x += 300 * dt
-
-        if self.resting and key[pygame.K_SPACE]:
-            self.dy = -500
-        self.dy = min(400, self.dy + 40)
-
-        self.rect.y += self.dy * dt
-
-        new = self.rect
-        self.resting = False
-        for cell in game.tilemap.layers_by_name['triggers'].collide(new, 'blockers'):
-            blockers = cell.tile.properties['blockers']
-            if 'l' in blockers and last.right <= cell.left and new.right > cell.left:
-                new.right = cell.left
-            if 'r' in blockers and last.left >= cell.right and new.left < cell.right:
-                new.left = cell.right
-            if 't' in blockers and last.bottom <= cell.top and new.bottom > cell.top:
-                self.resting = True
-                new.bottom = cell.top
-                self.dy = 0
-            if 'b' in blockers and last.top >= cell.bottom and new.top < cell.bottom:
-                new.top = cell.bottom
-                self.dy = 0
-
-        game.tilemap.set_focus(new.x, new.y)
-
-class Game(object):
-    def main(self, screen):
-        clock = pygame.time.Clock()
-
-        self.tilemap = tmx.load('map.tmx', screen.get_size())
-
-        sprites = tmx.SpriteLayer()
-        start_cell = self.tilemap.layers_by_name['triggers'].find(player='')[0]
-        player = Player('player.png', (start_cell.px, start_cell.py))
-        sprites.add(player)
-        self.tilemap.layers.append(sprites)
-
-        background = pygame.image.load('background.png')
-
-        while 1:
-            dt = clock.tick(30)
-
-            for event in pygame.event.get():
-                if event.type == pygame.QUIT:
-                    return
-                if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
-                    return
-
-            self.tilemap.update(dt / 1000., self)
-            screen.blit(background, (0,0))
-            self.tilemap.draw(screen)
-            pygame.display.flip()
-
-if __name__ == '__main__':
-    pygame.init()
-    screen = pygame.display.set_mode((640, 480))
-    Game().main(screen)
-

File 10-walls.py

View file
+import pygame
+
+class Sprite(pygame.sprite.Sprite):
+    def __init__(self, image, location):
+        super(Sprite, self).__init__()
+        self.image = pygame.image.load(image)
+        self.rect = pygame.rect.Rect(location, self.image.get_size())
+
+class Player(Sprite):
+    def update(self, dt, game):
+        last = self.rect.copy()
+
+        key = pygame.key.get_pressed()
+        if key[pygame.K_LEFT]:
+            self.rect.x -= 300 * dt
+        if key[pygame.K_RIGHT]:
+            self.rect.x += 300 * dt
+        if key[pygame.K_UP]:
+            self.rect.y -= 300 * dt
+        if key[pygame.K_DOWN]:
+            self.rect.y += 300 * dt
+
+        new = self.rect
+        for cell in pygame.sprite.spritecollide(self, game.walls, False):
+            cell = cell.rect
+            if last.right <= cell.left and new.right > cell.left:
+                new.right = cell.left
+            if last.left >= cell.right and new.left < cell.right:
+                new.left = cell.right
+            if last.bottom <= cell.top and new.bottom > cell.top:
+                new.bottom = cell.top
+            if last.top >= cell.bottom and new.top < cell.bottom:
+                new.top = cell.bottom
+
+class Game(object):
+    def main(self, screen):
+        clock = pygame.time.Clock()
+
+        sprites = pygame.sprite.OrderedUpdates()
+        background = Sprite('background.png', (0, 0))
+        sprites.add(background)
+        player = Player('player.png', (320, 240))
+        sprites.add(player)
+        self.walls = pygame.sprite.Group()
+        for x in range(0, 640, 32):
+            for y in range(0, 480, 32):
+                if x in (0, 640-32) or y in (0, 480-32):
+                    self.walls.add(Sprite('block.png', (x, y)))
+        sprites.add(self.walls)
+
+        while 1:
+            dt = clock.tick(30)
+
+            for event in pygame.event.get():
+                if event.type == pygame.QUIT:
+                    return
+                if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
+                    return
+
+            sprites.update(dt / 1000., self)
+            sprites.draw(screen)
+            pygame.display.flip()
+
+if __name__ == '__main__':
+    pygame.init()
+    screen = pygame.display.set_mode((640, 480))
+    Game().main(screen)
+

File 11-enemies.py

-import pygame
-import tmx
-
-class Sprite(pygame.sprite.Sprite):
-    def __init__(self, image, location):
-        super(Sprite, self).__init__()
-        self.image = pygame.image.load(image)
-        self.rect = pygame.rect.Rect(location, self.image.get_size())
-
-class Enemy(Sprite):
-    direction = 1
-    def update(self, dt, game):
-        self.rect.x += self.direction * 100 * dt
-        for cell in game.tilemap.layers_by_name['triggers'].collide(self.rect, 'reverse'):
-            if self.direction > 0:
-                self.rect.right = cell.left
-            else:
-                self.rect.left = cell.right
-            self.direction *= -1
-            break
-        if self.rect.colliderect(game.player.rect):
-            game.player.is_dead = True
-
-class Player(Sprite):
-    resting = False
-    dy = 0
-    is_dead = False
-    def update(self, dt, game):
-        last = self.rect.copy()
-
-        key = pygame.key.get_pressed()
-        if key[pygame.K_LEFT]:
-            self.rect.x -= 300 * dt
-        if key[pygame.K_RIGHT]:
-            self.rect.x += 300 * dt
-
-        if self.resting and key[pygame.K_SPACE]:
-            self.dy = -500
-        self.dy = min(400, self.dy + 40)
-
-        self.rect.y += self.dy * dt
-
-        new = self.rect
-        self.resting = False
-        for cell in game.tilemap.layers_by_name['triggers'].collide(new, 'blockers'):
-            blockers = cell.tile.properties['blockers']
-            if 'l' in blockers and last.right <= cell.left and new.right > cell.left:
-                new.right = cell.left
-            if 'r' in blockers and last.left >= cell.right and new.left < cell.right:
-                new.left = cell.right
-            if 't' in blockers and last.bottom <= cell.top and new.bottom > cell.top:
-                self.resting = True
-                new.bottom = cell.top
-                self.dy = 0
-            if 'b' in blockers and last.top >= cell.bottom and new.top < cell.bottom:
-                new.top = cell.bottom
-                self.dy = 0
-
-        game.tilemap.set_focus(new.x, new.y)
-
-class Game(object):
-    def main(self, screen):
-        clock = pygame.time.Clock()
-
-        self.tilemap = tmx.load('map.tmx', screen.get_size())
-
-        sprites = tmx.SpriteLayer()
-        start_cell = self.tilemap.layers_by_name['triggers'].find(player='')[0]
-        self.player = Player('player.png', (start_cell.px, start_cell.py))
-        sprites.add(self.player)
-        self.tilemap.layers.append(sprites)
-
-        enemies = tmx.SpriteLayer()
-        for enemy in self.tilemap.layers_by_name['triggers'].find(enemy=''):
-            enemies.add(Enemy('enemy.png', (enemy.px, enemy.py)))
-        self.tilemap.layers.append(enemies)
-
-        background = pygame.image.load('background.png')
-
-        while 1:
-            dt = clock.tick(30)
-
-            for event in pygame.event.get():
-                if event.type == pygame.QUIT:
-                    return
-                if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
-                    return
-
-            self.tilemap.update(dt / 1000., self)
-            screen.blit(background, (0,0))
-            self.tilemap.draw(screen)
-            pygame.display.flip()
-
-            if self.player.is_dead:
-                print 'YOU DIED'
-                return
-
-if __name__ == '__main__':
-    pygame.init()
-    screen = pygame.display.set_mode((640, 480))
-    Game().main(screen)
-

File 11-gravity.py

View file
+import pygame
+
+class Sprite(pygame.sprite.Sprite):
+    def __init__(self, image, location):
+        super(Sprite, self).__init__()
+        self.image = pygame.image.load(image)
+        self.rect = pygame.rect.Rect(location, self.image.get_size())
+
+class Player(Sprite):
+    resting = False
+    dy = 0
+    def update(self, dt, game):
+        last = self.rect.copy()
+
+        key = pygame.key.get_pressed()
+        if key[pygame.K_LEFT]:
+            self.rect.x -= 300 * dt
+        if key[pygame.K_RIGHT]:
+            self.rect.x += 300 * dt
+
+        if self.resting and key[pygame.K_SPACE]:
+            self.dy = -500
+        self.dy = min(400, self.dy + 40)
+
+        self.rect.y += self.dy * dt
+
+        new = self.rect
+        self.resting = False
+        for cell in pygame.sprite.spritecollide(self, game.walls, False):
+            cell = cell.rect
+            if last.right <= cell.left and new.right > cell.left:
+                new.right = cell.left
+            if last.left >= cell.right and new.left < cell.right:
+                new.left = cell.right
+            if last.bottom <= cell.top and new.bottom > cell.top:
+                self.resting = True
+                new.bottom = cell.top
+                self.dy = 0
+            if last.top >= cell.bottom and new.top < cell.bottom:
+                new.top = cell.bottom
+                self.dy = 0
+
+class Game(object):
+    def main(self, screen):
+        clock = pygame.time.Clock()
+
+        sprites = pygame.sprite.OrderedUpdates()
+        background = Sprite('background.png', (0, 0))
+        sprites.add(background)
+        player = Player('player.png', (320, 240))
+        sprites.add(player)
+        self.walls = pygame.sprite.Group()
+        for x in range(0, 640, 32):
+            for y in range(0, 480, 32):
+                if x in (0, 640-32) or y in (0, 480-32):
+                    self.walls.add(Sprite('block.png', (x, y)))
+        sprites.add(self.walls)
+
+        while 1:
+            dt = clock.tick(30)
+
+            for event in pygame.event.get():
+                if event.type == pygame.QUIT:
+                    return
+                if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
+                    return
+
+            sprites.update(dt / 1000., self)
+            sprites.draw(screen)
+            pygame.display.flip()
+
+if __name__ == '__main__':
+    pygame.init()
+    screen = pygame.display.set_mode((640, 480))
+    Game().main(screen)
+

File 12-shooting.py

-import pygame
-import tmx
-
-class Sprite(pygame.sprite.Sprite):
-    def __init__(self, image, location):
-        super(Sprite, self).__init__()
-        self.image = pygame.image.load(image)
-        self.rect = pygame.rect.Rect(location, self.image.get_size())
-
-class Enemy(Sprite):
-    direction = 1
-    def update(self, dt, game):
-        self.rect.x += self.direction * 100 * dt
-        for cell in game.tilemap.layers_by_name['triggers'].collide(self.rect, 'reverse'):
-            if self.direction > 0:
-                self.rect.right = cell.left
-            else:
-                self.rect.left = cell.right
-            self.direction *= -1
-            break
-        if self.rect.colliderect(game.player.rect):
-            game.player.is_dead = True
-
-class Bullet(pygame.sprite.Sprite):
-    image = pygame.image.load('bullet.png')
-    def __init__(self, location, direction):
-        super(Bullet, self).__init__()
-        self.rect = pygame.rect.Rect(location, self.image.get_size())
-        self.direction = direction
-        self.lifespan = 1
-
-    def update(self, dt, game):
-        self.lifespan -= dt
-        if self.lifespan < 0:
-            self.kill()
-            return
-        self.rect.x += self.direction * 400 * dt
-
-        if pygame.sprite.spritecollide(self, game.enemies, True):
-            self.kill()
-
-class Player(Sprite):
-    resting = False
-    dy = 0
-    is_dead = False
-    gun_cooldown = 0
-    direction = 1
-
-    def __init__(self, location):
-        super(Player, self).__init__('player-right.png', location)
-        self.right_image = self.image
-        self.left_image = pygame.image.load('player-left.png')
-
-    def update(self, dt, game):
-        last = self.rect.copy()
-
-        key = pygame.key.get_pressed()
-        if key[pygame.K_LEFT]:
-            self.rect.x -= 300 * dt
-            self.image = self.left_image
-            self.direction = -1
-        if key[pygame.K_RIGHT]:
-            self.rect.x += 300 * dt
-            self.image = self.right_image
-            self.direction = 1
-
-        if key[pygame.K_LSHIFT] and not self.gun_cooldown:
-            if self.direction > 0:
-                game.sprites.add(Bullet(self.rect.midright, 1))
-            else:
-                game.sprites.add(Bullet(self.rect.midleft, -1))
-            self.gun_cooldown = 1
-
-        self.gun_cooldown = max(0, self.gun_cooldown - dt)
-
-        if self.resting and key[pygame.K_SPACE]:
-            self.dy = -500
-        self.dy = min(400, self.dy + 40)
-
-        self.rect.y += self.dy * dt
-
-        new = self.rect
-        self.resting = False
-        for cell in game.tilemap.layers_by_name['triggers'].collide(new, 'blockers'):
-            blockers = cell.tile.properties['blockers']
-            if 'l' in blockers and last.right <= cell.left and new.right > cell.left:
-                new.right = cell.left
-            if 'r' in blockers and last.left >= cell.right and new.left < cell.right:
-                new.left = cell.right
-            if 't' in blockers and last.bottom <= cell.top and new.bottom > cell.top:
-                self.resting = True
-                new.bottom = cell.top
-                self.dy = 0
-            if 'b' in blockers and last.top >= cell.bottom and new.top < cell.bottom:
-                new.top = cell.bottom
-                self.dy = 0
-
-        game.tilemap.set_focus(new.x, new.y)
-
-class Game(object):
-    def main(self, screen):
-        clock = pygame.time.Clock()
-
-        self.tilemap = tmx.load('map.tmx', screen.get_size())
-
-        self.sprites = tmx.SpriteLayer()
-        start_cell = self.tilemap.layers_by_name['triggers'].find(player='')[0]
-        self.player = Player((start_cell.px, start_cell.py))
-        self.sprites.add(self.player)
-        self.tilemap.layers.append(self.sprites)
-
-        self.enemies = tmx.SpriteLayer()
-        for enemy in self.tilemap.layers_by_name['triggers'].find(enemy=''):
-            self.enemies.add(Enemy('enemy.png', (enemy.px, enemy.py)))
-        self.tilemap.layers.append(self.enemies)
-
-        background = pygame.image.load('background.png')
-
-        running = True
-        while running:
-            dt = clock.tick(30)
-
-            for event in pygame.event.get():
-                if event.type == pygame.QUIT:
-                    running = False
-                if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
-                    running = False
-
-            self.tilemap.update(dt / 1000., self)
-            screen.blit(background, (0,0))
-            self.tilemap.set_focus(self.player.rect.x, self.player.rect.y)
-            self.tilemap.draw(screen)
-            pygame.display.flip()
-
-            if self.player.is_dead:
-                print 'YOU DIED'
-                running = False
-
-if __name__ == '__main__':
-    pygame.init()
-    screen = pygame.display.set_mode((640, 480))
-    Game().main(screen)
-

File 12-tilemap.py

View file
+import pygame
+import tmx
+
+class Sprite(pygame.sprite.Sprite):
+    def __init__(self, image, location):
+        super(Sprite, self).__init__()
+        self.image = pygame.image.load(image)
+        self.rect = pygame.rect.Rect(location, self.image.get_size())
+
+class Player(Sprite):
+    resting = False
+    dy = 0
+    def update(self, dt, game):
+        last = self.rect.copy()
+
+        key = pygame.key.get_pressed()
+        if key[pygame.K_LEFT]:
+            self.rect.x -= 300 * dt
+        if key[pygame.K_RIGHT]:
+            self.rect.x += 300 * dt
+
+        if self.resting and key[pygame.K_SPACE]:
+            self.dy = -500
+        self.dy = min(400, self.dy + 40)
+
+        self.rect.y += self.dy * dt
+
+        new = self.rect
+        self.resting = False
+        for cell in game.tilemap.layers_by_name['triggers'].collide(new, 'blockers'):
+            blockers = cell.tile.properties['blockers']
+            if 'l' in blockers and last.right <= cell.left and new.right > cell.left:
+                new.right = cell.left
+            if 'r' in blockers and last.left >= cell.right and new.left < cell.right:
+                new.left = cell.right
+            if 't' in blockers and last.bottom <= cell.top and new.bottom > cell.top:
+                self.resting = True
+                new.bottom = cell.top
+                self.dy = 0
+            if 'b' in blockers and last.top >= cell.bottom and new.top < cell.bottom:
+                new.top = cell.bottom
+                self.dy = 0
+
+        game.tilemap.set_focus(new.x, new.y)
+
+class Game(object):
+    def main(self, screen):
+        clock = pygame.time.Clock()
+
+        self.tilemap = tmx.load('map.tmx', screen.get_size())
+
+        sprites = tmx.SpriteLayer()
+        start_cell = self.tilemap.layers_by_name['triggers'].find(player='')[0]
+        player = Player('player.png', (start_cell.px, start_cell.py))
+        sprites.add(player)
+        self.tilemap.layers.append(sprites)
+
+        background = pygame.image.load('background.png')
+
+        while 1:
+            dt = clock.tick(30)
+
+            for event in pygame.event.get():
+                if event.type == pygame.QUIT:
+                    return
+                if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
+                    return
+
+            self.tilemap.update(dt / 1000., self)
+            screen.blit(background, (0,0))
+            self.tilemap.draw(screen)
+            pygame.display.flip()
+
+if __name__ == '__main__':
+    pygame.init()
+    screen = pygame.display.set_mode((640, 480))
+    Game().main(screen)
+

File 13-enemies.py

View file
+import pygame
+import tmx
+
+class Sprite(pygame.sprite.Sprite):
+    def __init__(self, image, location):
+        super(Sprite, self).__init__()
+        self.image = pygame.image.load(image)
+        self.rect = pygame.rect.Rect(location, self.image.get_size())
+
+class Enemy(Sprite):
+    direction = 1
+    def update(self, dt, game):
+        self.rect.x += self.direction * 100 * dt
+        for cell in game.tilemap.layers_by_name['triggers'].collide(self.rect, 'reverse'):
+            if self.direction > 0:
+                self.rect.right = cell.left
+            else:
+                self.rect.left = cell.right
+            self.direction *= -1
+            break
+        if self.rect.colliderect(game.player.rect):
+            game.player.is_dead = True
+
+class Player(Sprite):
+    resting = False
+    dy = 0
+    is_dead = False
+    def update(self, dt, game):
+        last = self.rect.copy()
+
+        key = pygame.key.get_pressed()
+        if key[pygame.K_LEFT]:
+            self.rect.x -= 300 * dt
+        if key[pygame.K_RIGHT]:
+            self.rect.x += 300 * dt
+
+        if self.resting and key[pygame.K_SPACE]:
+            self.dy = -500
+        self.dy = min(400, self.dy + 40)
+
+        self.rect.y += self.dy * dt
+
+        new = self.rect
+        self.resting = False
+        for cell in game.tilemap.layers_by_name['triggers'].collide(new, 'blockers'):
+            blockers = cell.tile.properties['blockers']
+            if 'l' in blockers and last.right <= cell.left and new.right > cell.left:
+                new.right = cell.left
+            if 'r' in blockers and last.left >= cell.right and new.left < cell.right:
+                new.left = cell.right
+            if 't' in blockers and last.bottom <= cell.top and new.bottom > cell.top:
+                self.resting = True
+                new.bottom = cell.top
+                self.dy = 0
+            if 'b' in blockers and last.top >= cell.bottom and new.top < cell.bottom:
+                new.top = cell.bottom
+                self.dy = 0
+
+        game.tilemap.set_focus(new.x, new.y)
+
+class Game(object):
+    def main(self, screen):
+        clock = pygame.time.Clock()
+
+        self.tilemap = tmx.load('map.tmx', screen.get_size())
+
+        sprites = tmx.SpriteLayer()
+        start_cell = self.tilemap.layers_by_name['triggers'].find(player='')[0]
+        self.player = Player('player.png', (start_cell.px, start_cell.py))
+        sprites.add(self.player)
+        self.tilemap.layers.append(sprites)
+
+        enemies = tmx.SpriteLayer()
+        for enemy in self.tilemap.layers_by_name['triggers'].find(enemy=''):
+            enemies.add(Enemy('enemy.png', (enemy.px, enemy.py)))
+        self.tilemap.layers.append(enemies)
+
+        background = pygame.image.load('background.png')
+
+        while 1:
+            dt = clock.tick(30)
+
+            for event in pygame.event.get():
+                if event.type == pygame.QUIT:
+                    return
+                if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
+                    return
+
+            self.tilemap.update(dt / 1000., self)
+            screen.blit(background, (0,0))
+            self.tilemap.draw(screen)
+            pygame.display.flip()
+
+            if self.player.is_dead:
+                print 'YOU DIED'
+                return
+
+if __name__ == '__main__':
+    pygame.init()
+    screen = pygame.display.set_mode((640, 480))
+    Game().main(screen)
+

File 13-sound.py

-import pygame
-import tmx
-
-class Sprite(pygame.sprite.Sprite):
-    def __init__(self, image, location):
-        super(Sprite, self).__init__()
-        self.image = pygame.image.load(image)
-        self.rect = pygame.rect.Rect(location, self.image.get_size())
-
-class Enemy(Sprite):
-    direction = 1
-    def update(self, dt, game):
-        self.rect.x += self.direction * 100 * dt
-        for cell in game.tilemap.layers_by_name['triggers'].collide(self.rect, 'reverse'):
-            if self.direction > 0:
-                self.rect.right = cell.left
-            else:
-                self.rect.left = cell.right
-            self.direction *= -1
-            break
-        if self.rect.colliderect(game.player.rect):
-            game.player.is_dead = True
-
-class Bullet(pygame.sprite.Sprite):
-    image = pygame.image.load('bullet.png')
-    def __init__(self, location, direction):
-        super(Bullet, self).__init__()
-        self.rect = pygame.rect.Rect(location, self.image.get_size())
-        self.direction = direction
-        self.lifespan = 1
-
-    def update(self, dt, game):
-        self.lifespan -= dt
-        if self.lifespan < 0:
-            self.kill()
-            return
-        self.rect.x += self.direction * 400 * dt
-
-        if pygame.sprite.spritecollide(self, game.enemies, True):
-            game.explosion.play()
-            self.kill()
-
-class Player(Sprite):
-    resting = False
-    dy = 0
-    is_dead = False
-    gun_cooldown = 0
-    direction = 1
-
-    def __init__(self, location):
-        super(Player, self).__init__('player-right.png', location)
-        self.right_image = self.image
-        self.left_image = pygame.image.load('player-left.png')
-
-    def update(self, dt, game):
-        last = self.rect.copy()
-
-        key = pygame.key.get_pressed()
-        if key[pygame.K_LEFT]:
-            self.rect.x -= 300 * dt
-            self.image = self.left_image
-            self.direction = -1
-        if key[pygame.K_RIGHT]:
-            self.rect.x += 300 * dt
-            self.image = self.right_image
-            self.direction = 1
-
-        if key[pygame.K_LSHIFT] and not self.gun_cooldown:
-            if self.direction > 0:
-                game.sprites.add(Bullet(self.rect.midright, 1))
-            else:
-                game.sprites.add(Bullet(self.rect.midleft, -1))
-            self.gun_cooldown = 1
-            game.shoot.play()
-
-        self.gun_cooldown = max(0, self.gun_cooldown - dt)
-
-        if self.resting and key[pygame.K_SPACE]:
-            game.jump.play()
-            self.dy = -500
-        self.dy = min(400, self.dy + 40)
-
-        self.rect.y += self.dy * dt
-
-        new = self.rect
-        self.resting = False
-        for cell in game.tilemap.layers_by_name['triggers'].collide(new, 'blockers'):
-            blockers = cell.tile.properties['blockers']
-            if 'l' in blockers and last.right <= cell.left and new.right > cell.left:
-                new.right = cell.left
-            if 'r' in blockers and last.left >= cell.right and new.left < cell.right:
-                new.left = cell.right
-            if 't' in blockers and last.bottom <= cell.top and new.bottom > cell.top:
-                self.resting = True
-                new.bottom = cell.top
-                self.dy = 0
-            if 'b' in blockers and last.top >= cell.bottom and new.top < cell.bottom:
-                new.top = cell.bottom
-                self.dy = 0
-
-        game.tilemap.set_focus(new.x, new.y)
-
-class Game(object):
-    def main(self, screen):
-        clock = pygame.time.Clock()
-
-        self.tilemap = tmx.load('map.tmx', screen.get_size())
-
-        self.sprites = tmx.SpriteLayer()
-        start_cell = self.tilemap.layers_by_name['triggers'].find(player='')[0]
-        self.player = Player((start_cell.px, start_cell.py))
-        self.sprites.add(self.player)
-        self.tilemap.layers.append(self.sprites)
-
-        self.enemies = tmx.SpriteLayer()
-        for enemy in self.tilemap.layers_by_name['triggers'].find(enemy=''):
-            self.enemies.add(Enemy('enemy.png', (enemy.px, enemy.py)))
-        self.tilemap.layers.append(self.enemies)
-
-        background = pygame.image.load('background.png')
-
-        self.jump = pygame.mixer.Sound('jump.wav')
-        self.shoot = pygame.mixer.Sound('shoot.wav')
-        self.explosion = pygame.mixer.Sound('explosion.wav')
-
-        while 1:
-            dt = clock.tick(30)
-
-            for event in pygame.event.get():
-                if event.type == pygame.QUIT:
-                    return
-                if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
-                    return
-
-            self.tilemap.update(dt / 1000., self)
-            screen.blit(background, (0,0))
-            self.tilemap.draw(screen)
-            pygame.display.flip()
-
-            if self.player.is_dead:
-                print 'YOU DIED'
-                return
-
-if __name__ == '__main__':
-    pygame.init()
-    screen = pygame.display.set_mode((640, 480))
-    Game().main(screen)
-

File 14-shooting.py

View file
+import pygame
+import tmx
+
+class Sprite(pygame.sprite.Sprite):
+    def __init__(self, image, location):
+        super(Sprite, self).__init__()
+        self.image = pygame.image.load(image)
+        self.rect = pygame.rect.Rect(location, self.image.get_size())
+
+class Enemy(Sprite):
+    direction = 1
+    def update(self, dt, game):
+        self.rect.x += self.direction * 100 * dt
+        for cell in game.tilemap.layers_by_name['triggers'].collide(self.rect, 'reverse'):
+            if self.direction > 0:
+                self.rect.right = cell.left
+            else:
+                self.rect.left = cell.right
+            self.direction *= -1
+            break
+        if self.rect.colliderect(game.player.rect):
+            game.player.is_dead = True
+
+class Bullet(pygame.sprite.Sprite):
+    image = pygame.image.load('bullet.png')
+    def __init__(self, location, direction):
+        super(Bullet, self).__init__()
+        self.rect = pygame.rect.Rect(location, self.image.get_size())
+        self.direction = direction
+        self.lifespan = 1
+
+    def update(self, dt, game):
+        self.lifespan -= dt
+        if self.lifespan < 0:
+            self.kill()
+            return
+        self.rect.x += self.direction * 400 * dt
+
+        if pygame.sprite.spritecollide(self, game.enemies, True):
+            self.kill()
+
+class Player(Sprite):
+    resting = False
+    dy = 0
+    is_dead = False
+    gun_cooldown = 0
+    direction = 1
+
+    def __init__(self, location):
+        super(Player, self).__init__('player-right.png', location)
+        self.right_image = self.image
+        self.left_image = pygame.image.load('player-left.png')
+
+    def update(self, dt, game):
+        last = self.rect.copy()
+
+        key = pygame.key.get_pressed()
+        if key[pygame.K_LEFT]:
+            self.rect.x -= 300 * dt
+            self.image = self.left_image
+            self.direction = -1
+        if key[pygame.K_RIGHT]:
+            self.rect.x += 300 * dt
+            self.image = self.right_image
+            self.direction = 1
+
+        if key[pygame.K_LSHIFT] and not self.gun_cooldown:
+            if self.direction > 0:
+                game.sprites.add(Bullet(self.rect.midright, 1))
+            else:
+                game.sprites.add(Bullet(self.rect.midleft, -1))
+            self.gun_cooldown = 1
+
+        self.gun_cooldown = max(0, self.gun_cooldown - dt)
+
+        if self.resting and key[pygame.K_SPACE]:
+            self.dy = -500
+        self.dy = min(400, self.dy + 40)
+
+        self.rect.y += self.dy * dt
+
+        new = self.rect
+        self.resting = False
+        for cell in game.tilemap.layers_by_name['triggers'].collide(new, 'blockers'):
+            blockers = cell.tile.properties['blockers']
+            if 'l' in blockers and last.right <= cell.left and new.right > cell.left:
+                new.right = cell.left
+            if 'r' in blockers and last.left >= cell.right and new.left < cell.right:
+                new.left = cell.right
+            if 't' in blockers and last.bottom <= cell.top and new.bottom > cell.top:
+                self.resting = True
+                new.bottom = cell.top
+                self.dy = 0
+            if 'b' in blockers and last.top >= cell.bottom and new.top < cell.bottom:
+                new.top = cell.bottom
+                self.dy = 0
+
+        game.tilemap.set_focus(new.x, new.y)
+
+class Game(object):
+    def main(self, screen):
+        clock = pygame.time.Clock()
+
+        self.tilemap = tmx.load('map.tmx', screen.get_size())
+
+        self.sprites = tmx.SpriteLayer()
+        start_cell = self.tilemap.layers_by_name['triggers'].find(player='')[0]
+        self.player = Player((start_cell.px, start_cell.py))
+        self.sprites.add(self.player)
+        self.tilemap.layers.append(self.sprites)
+
+        self.enemies = tmx.SpriteLayer()
+        for enemy in self.tilemap.layers_by_name['triggers'].find(enemy=''):
+            self.enemies.add(Enemy('enemy.png', (enemy.px, enemy.py)))
+        self.tilemap.layers.append(self.enemies)
+
+        background = pygame.image.load('background.png')
+
+        running = True
+        while running:
+            dt = clock.tick(30)
+
+            for event in pygame.event.get():
+                if event.type == pygame.QUIT:
+                    running = False
+                if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
+                    running = False
+
+            self.tilemap.update(dt / 1000., self)
+            screen.blit(background, (0,0))
+            self.tilemap.set_focus(self.player.rect.x, self.player.rect.y)
+            self.tilemap.draw(screen)
+            pygame.display.flip()
+
+            if self.player.is_dead:
+                print 'YOU DIED'
+                running = False
+
+if __name__ == '__main__':
+    pygame.init()
+    screen = pygame.display.set_mode((640, 480))
+    Game().main(screen)
+

File 15-sound.py

View file
+import pygame
+import tmx
+
+class Sprite(pygame.sprite.Sprite):
+    def __init__(self, image, location):
+        super(Sprite, self).__init__()
+        self.image = pygame.image.load(image)
+        self.rect = pygame.rect.Rect(location, self.image.get_size())
+
+class Enemy(Sprite):
+    direction = 1
+    def update(self, dt, game):
+        self.rect.x += self.direction * 100 * dt
+        for cell in game.tilemap.layers_by_name['triggers'].collide(self.rect, 'reverse'):
+            if self.direction > 0:
+                self.rect.right = cell.left
+            else:
+                self.rect.left = cell.right
+            self.direction *= -1
+            break
+        if self.rect.colliderect(game.player.rect):
+            game.player.is_dead = True
+
+class Bullet(pygame.sprite.Sprite):
+    image = pygame.image.load('bullet.png')
+    def __init__(self, location, direction):
+        super(Bullet, self).__init__()
+        self.rect = pygame.rect.Rect(location, self.image.get_size())
+        self.direction = direction
+        self.lifespan = 1
+
+    def update(self, dt, game):
+        self.lifespan -= dt
+        if self.lifespan < 0:
+            self.kill()
+            return
+        self.rect.x += self.direction * 400 * dt
+
+        if pygame.sprite.spritecollide(self, game.enemies, True):
+            game.explosion.play()
+            self.kill()
+
+class Player(Sprite):
+    resting = False
+    dy = 0
+    is_dead = False
+    gun_cooldown = 0
+    direction = 1
+
+    def __init__(self, location):
+        super(Player, self).__init__('player-right.png', location)
+        self.right_image = self.image
+        self.left_image = pygame.image.load('player-left.png')
+
+    def update(self, dt, game):
+        last = self.rect.copy()
+
+        key = pygame.key.get_pressed()
+        if key[pygame.K_LEFT]:
+            self.rect.x -= 300 * dt
+            self.image = self.left_image
+            self.direction = -1
+        if key[pygame.K_RIGHT]:
+            self.rect.x += 300 * dt
+            self.image = self.right_image
+            self.direction = 1
+
+        if key[pygame.K_LSHIFT] and not self.gun_cooldown:
+            if self.direction > 0:
+                game.sprites.add(Bullet(self.rect.midright, 1))
+            else:
+                game.sprites.add(Bullet(self.rect.midleft, -1))
+            self.gun_cooldown = 1
+            game.shoot.play()
+
+        self.gun_cooldown = max(0, self.gun_cooldown - dt)
+
+        if self.resting and key[pygame.K_SPACE]:
+            game.jump.play()
+            self.dy = -500
+        self.dy = min(400, self.dy + 40)
+
+        self.rect.y += self.dy * dt
+
+        new = self.rect
+        self.resting = False
+        for cell in game.tilemap.layers_by_name['triggers'].collide(new, 'blockers'):
+            blockers = cell.tile.properties['blockers']
+            if 'l' in blockers and last.right <= cell.left and new.right > cell.left:
+                new.right = cell.left
+            if 'r' in blockers and last.left >= cell.right and new.left < cell.right:
+                new.left = cell.right
+            if 't' in blockers and last.bottom <= cell.top and new.bottom > cell.top:
+                self.resting = True
+                new.bottom = cell.top
+                self.dy = 0
+            if 'b' in blockers and last.top >= cell.bottom and new.top < cell.bottom:
+                new.top = cell.bottom
+                self.dy = 0
+
+        game.tilemap.set_focus(new.x, new.y)
+
+class Game(object):
+    def main(self, screen):
+        clock = pygame.time.Clock()
+
+        self.tilemap = tmx.load('map.tmx', screen.get_size())
+
+        self.sprites = tmx.SpriteLayer()
+        start_cell = self.tilemap.layers_by_name['triggers'].find(player='')[0]
+        self.player = Player((start_cell.px, start_cell.py))
+        self.sprites.add(self.player)
+        self.tilemap.layers.append(self.sprites)
+
+        self.enemies = tmx.SpriteLayer()
+        for enemy in self.tilemap.layers_by_name['triggers'].find(enemy=''):
+            self.enemies.add(Enemy('enemy.png', (enemy.px, enemy.py)))
+        self.tilemap.layers.append(self.enemies)
+
+        background = pygame.image.load('background.png')
+
+        self.jump = pygame.mixer.Sound('jump.wav')
+        self.shoot = pygame.mixer.Sound('shoot.wav')
+        self.explosion = pygame.mixer.Sound('explosion.wav')
+
+        while 1:
+            dt = clock.tick(30)
+
+            for event in pygame.event.get():
+                if event.type == pygame.QUIT:
+                    return
+                if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
+                    return
+
+            self.tilemap.update(dt / 1000., self)
+            screen.blit(background, (0,0))
+            self.tilemap.draw(screen)
+            pygame.display.flip()
+
+            if self.player.is_dead:
+                print 'YOU DIED'
+                return
+
+if __name__ == '__main__':
+    pygame.init()
+    screen = pygame.display.set_mode((640, 480))
+    Game().main(screen)
+

File overview.txt

View file
 
   Explain the two different event types (QUIT and KEYDOWN.)
 
-03-drawing.py
+03-structure.py
+  Here we introduce some structure to the code.
+
+04-drawing.py
   The final step to getting something basic going is being able to draw
   images to the screen. Once you've achieved this there's a stack of games
   that you're able to write (adventure games, tetris, ...)
 
   We've also limited the redrawing of the screen to 30 frames per second.
 
-04-move.py
+05-animation.py
   A lot of games have animation though. Here we hold the rendered position
   of the image in a couple of variables. We modify the variables in
   response to key presses and the image moves.
 
   Explain why we use pygame.key.get_pressed()
 
-05-sprite.py
+06-sprite.py
   Images and their location on screen are common partners; a "sprite" is
   often used to combine the two.
 
 
   Note the sprite-specific event handling is now part of the sprite itself.
 
-06-smooth.py
+07-smooth.py
   Here we handle the differences between computer capabilities by
   incorporating the amount of time passed into the movement calculations.
 
-07-background.py
+08-background.py
   Instead of the plain background we add a nice coloured one.
 
-  We've introduced the concept of dirty segments - explain.
-
-075-refactoring.py
+09-refactoring.py
   Refactoring out the common code.
 
-08-walls.py
+10-walls.py
   Adding some walls and some basic collision detection.
 
   Basic rectangular collisions. Note we check transitions so we can conform
 
   Note how we can't slide along the walls.
 
-09-gravity.py
+11-gravity.py
   Introduce gravity and jumping.
 
   Note that jumping should only be possible when resting (or once while
   Later when we have platforms try not zeroing the velocity and walk off
   the end of a platform.
 
-10-tilemap.py
+12-tilemap.py
   Introduce a real tile map loaded from the common TMX format. Using a
   library, because we're not crazy. There's a bunch of TMX libraries. And
   TMX tools.
   Discuss blocker sides and how they solve the wall collision problem of
   before.
 
-11-enemies.py
+13-enemies.py
   Enemies are added using more triggers, including some to make them turn
   around.
 
 
   The player can die so handle that.
 
-12-shooting.py
+14-shooting.py
   Player shooting. We need to know which direction the player is facing.
 
   Note possibility of sprite animation.
 
   More refactoring!
 
-13-sound.py
+15-sound.py
   Load sounds and .play() sounds when appropriate. Easy! Try not to
   overload the mixer though!
 
+