Exemplo n.º 1
0
    def __init__(self, name, width, height):
        super().__init__(name, width, height)

        self.ship = Ship()  # None  # TODO: should create a Ship object here
        # TODO: should create asteroids
        self.asteroids = []
        # TODO: should create stars
        self.stars = []
        self.bullets = []
Exemplo n.º 2
0
 def __init__(self, name, width, height):
     super().__init__( name, width, height )
     self.ship = Ship()  # Creates a ship
     self.asteroids=[]   # A list of all asteroids
     for i in range(4):                  # Change for different amount of Asteroids
         self.asteroids.append(Asteroid(random.randrange(0, 1280, 5),random.randrange(0, 720, 5)))
     self.stars=[]       # A list of all background stars
     for i in range(50):                # Change for different amount of background Stars
         self.stars.append(Star())
     self.bullets = []   # A list of all bullets
Exemplo n.º 3
0
 def __init__(self, name, width, height):
     super().__init__(name, width, height)
     # TODO: should create a Ship object here
     self.ship = Ship()  # None
     # TODO: should create asteroids
     self.asteroids = []
     for i in range(8):  # Change for different amount of Asteroids
         self.asteroids.append(Asteroid())
     self.stars = []
     for i in range(250):  # Change for different amount of background Stars
         self.stars.append(Star())
     # TODO: should create bullets
     self.bullets = []
Exemplo n.º 4
0
    def __ship_destroyed(ship: objects.Ship, mp: MapBuilder):
        """
        :param ship: Ship - a ship that has destroyed
        :param mp: MapBuilder - a map that the ship is placed
        :return: None
        """
        for i in range(ship.get_type()):
            x = ship.get_x_at(i)
            y = ship.get_y_at(i)

            mp.get_button(x, y).config(text="X", bg=Color.DESTROYED_SHIP)

            # Automatically hitting adjacent points
            if x < 10 and mp.get_button(x + 1,
                                        y).cget("bg") == Color.MAP_COLOR:
                mp.get_button(x + 1, y).config(bg=Color.BROKEN_POINT,
                                               text="*",
                                               state=DISABLED)
            if x > 1 and mp.get_button(x - 1, y).cget("bg") == Color.MAP_COLOR:
                mp.get_button(x - 1, y).config(bg=Color.BROKEN_POINT,
                                               text="*",
                                               state=DISABLED)
            if y < 10 and mp.get_button(x,
                                        y + 1).cget("bg") == Color.MAP_COLOR:
                mp.get_button(x, y + 1).config(bg=Color.BROKEN_POINT,
                                               text="*",
                                               state=DISABLED)
            if y > 1 and mp.get_button(x, y - 1).cget("bg") == Color.MAP_COLOR:
                mp.get_button(x, y - 1).config(bg=Color.BROKEN_POINT,
                                               text="*",
                                               state=DISABLED)
            if x < 10 and y < 10 and mp.get_button(
                    x + 1, y + 1).cget("bg") == Color.MAP_COLOR:
                mp.get_button(x + 1, y + 1).config(bg=Color.BROKEN_POINT,
                                                   text="*",
                                                   state=DISABLED)
            if x > 1 and y > 1 and mp.get_button(
                    x - 1, y - 1).cget("bg") == Color.MAP_COLOR:
                mp.get_button(x - 1, y - 1).config(bg=Color.BROKEN_POINT,
                                                   text="*",
                                                   state=DISABLED)
            if x > 1 and y < 10 and mp.get_button(
                    x - 1, y + 1).cget("bg") == Color.MAP_COLOR:
                mp.get_button(x - 1, y + 1).config(bg=Color.BROKEN_POINT,
                                                   text="*",
                                                   state=DISABLED)
            if x < 10 and y > 1 and mp.get_button(
                    x + 1, y - 1).cget("bg") == Color.MAP_COLOR:
                mp.get_button(x + 1, y - 1).config(bg=Color.BROKEN_POINT,
                                                   text="*",
                                                   state=DISABLED)
Exemplo n.º 5
0
 def __init__(self, name, width, height):
     super().__init__(name, width, height)
     self.width = width
     self.height = height
     self.ship = Ship()  # Creates a ship
     self.asteroids = []  # A list of all asteroids
     for i in range(5):  # Change for different amount of Asteroids
         self.asteroids.append(
             Asteroid(random.randrange(0, width, 5),
                      random.randrange(0, height, 5)))
     self.stars = []  # A list of all background stars
     for i in range(25):  # Change for different amount of background Stars
         self.stars.append(Star())
     self.bullets = []  # A list of all bullets
     self.score = 0  # Possible score variable
Exemplo n.º 6
0
 def start_game(self):
     self.step = 0
     self.score = 0
     self.ship = Ship(Vect(400, 400), Vect(0, 0), 0)
     self.soundtrack.play(-1)
     self.is_started = True
     self.is_over = False
Exemplo n.º 7
0
def get_params():
    width = 500
    height = 400

    DISPLAYSURF = pygame.display.set_mode((width, height))
    DISPLAYSURF.fill((255, 255, 255))

    score = 0
    lives = 1

    return {
        'FPS': 30,
        'width': width,
        'height': height,
        'DISPLAYSURF': DISPLAYSURF,
        'fps_clock': pygame.time.Clock(),
        'score': score,
        'lives': lives,
        'bullets': [],
        'rocks': [],
        'bullet_group': pygame.sprite.Group(),
        'rock_group': pygame.sprite.Group(),
        'ship': Ship((width / 2, height - 50), 0.5),
        'rock_generator': RockGenerator(width, height),
        'game_info': GameInfo(score, lives),
        'audio': AudioEffects()
    }
Exemplo n.º 8
0
def main():
    """Set up main loop for game"""
    pygame.init()
    clock = pygame.time.Clock()
    settings = Settings()
    screen = settings.screen
    ship = Ship(screen)
    aliens = create_aliens(screen)
    projectiles = pygame.sprite.Group()
    barriers = pygame.sprite.Group(Barrier(screen, 1), Barrier(screen, 2),
                                   Barrier(screen, 3), Barrier(screen, 4))
    score = Score()

    while True:
        check_events(screen, ship, projectiles)
        update_objects(ship, projectiles, barriers, aliens, score)
        update_screen(settings, ship, barriers, projectiles, aliens, score)
        clock.tick(60)
Exemplo n.º 9
0
def restart_game(text, color):
    global ship_enemies, ship, bullets
    font = pygame.font.SysFont('comicsans', 100)
    text = font.render(text, True, (255, 255, 255))
    window.blit(text, (screen_width/2-text.get_width()/2, screen_height/2))
    font = pygame.font.SysFont('comicsans', 50)
    text = font.render('Naciśnij dowolny klawisz, aby rozpocząć nową grę...', True, color)
    window.blit(text, (screen_width/2-text.get_width()/2, screen_height/2+100))
    pygame.display.update()
    pause = True
    while pause:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pause = False
                pygame.quit()
            if event.type == pygame.KEYDOWN:
                pause = False
                bullets = []
                ship_enemies = [[Ship(x*100+100, i*60, 64, 64, 15, enemy_image) for x in range(8)] for i in range(4)]
                ship.x = screen_width/2-ship.width/2
Exemplo n.º 10
0
 def __init__(self, ship=None):
     if ship is None:
         self.ship = Ship()
     else:
         # Rebuild object if ship is set
         self.ship = ship
Exemplo n.º 11
0
class Asteroids( Game ):
    """
    Asteroids extends the base class Game to provide logic for the specifics of the game
    """
    def __init__(self, name, width, height):
        super().__init__( name, width, height )
        self.ship = Ship()  # Creates a ship
        self.asteroids=[]   # A list of all asteroids
        for i in range(4):                  # Change for different amount of Asteroids
            self.asteroids.append(Asteroid(random.randrange(0, 1280, 5),random.randrange(0, 720, 5)))
        self.stars=[]       # A list of all background stars
        for i in range(50):                # Change for different amount of background Stars
            self.stars.append(Star())
        self.bullets = []   # A list of all bullets

    def handle_input(self):
        super().handle_input()
        keys_pressed = pygame.key.get_pressed()
        if keys_pressed[K_LEFT] and self.ship:
            self.ship.rotate(-1)
        if keys_pressed[K_RIGHT] and self.ship:
            self.ship.rotate(1)
        if keys_pressed[K_UP] and self.ship:
            self.ship.accelerate(0.05)
        if keys_pressed[K_DOWN] and self.ship:
            self.ship.accelerate(0) #TODO: Set to (0) to stop the ship instantly with down-key AKA EASYMODE.
        if keys_pressed[K_SPACE] and self.ship:
            if len(self.bullets) == 0:
                self.bullets.append(Bullet(self.ship.position, self.ship.rotation, self.frame))
            else:
                if self.bullets[len(self.bullets)-1].ttl > 50:
                    self.bullets.append(Bullet(self.ship.position, self.ship.rotation, self.frame))

            # Försöker få delay i bullet interval
            if len(self.bullets) >= 10:
                del self.bullets[0]
                self.bullets.append(Bullet(self.ship.position, self.ship.rotation, self.frame))



    def update_simulation(self):
        """
        update_simulation() causes all objects in the game to update themselves
        """
        super().update_simulation()

        if self.ship:
            self.ship.update( self.width, self.height )
        for asteroid in self.asteroids:
            asteroid.update( self.width, self.height )
        for star in self.stars:
            star.update( self.width, self.height )
        for bullet in self.bullets:
            bullet.update( self.width, self.height)
            if bullet.ttl + 100 < self.frame:
                self.bullets.pop(self.bullets.index(bullet))

        self.handle_collisions()

    def render_objects(self):
        """
        render_objects() causes all objects in the game to draw themselves onto the screen
        """
        super().render_objects()
        # Render the ship:
        if self.ship:
            self.ship.draw( self.screen )
        # Render all the stars, if any:
        for star in self.stars:
            star.draw( self.screen )
        # Render all the asteroids, if any:
        for asteroid in self.asteroids:
            asteroid.draw( self.screen )
        # Render all the bullet, if any:
        for bullet in self.bullets:
            bullet.draw( self.screen )


    def handle_collisions(self):
        if self.ship:
            for asteroid in self.asteroids:
                if asteroid.collide(self.ship):
                    self.running = False
                for bullet in self.bullets:
                    if asteroid.contains(bullet.position):
                        self.bullets.pop(self.bullets.index(bullet))
                        self.asteroids.pop(self.asteroids.index(asteroid))
                        if asteroid.health >= 2:
                            self.asteroids.append(Debris(asteroid.position))
                            self.asteroids.append(Debris(asteroid.position))
                            self.asteroids.append(Debris(asteroid.position))
                            self.asteroids.append(Debris(asteroid.position))
                        break
Exemplo n.º 12
0
class Asteroids(Game):

    def __init__(self, name, width, height):
        super().__init__( name, width, height )
        self.ship = Ship()  # Creates a ship
        self.asteroids=[]   # A list of all asteroids
        for i in range(5):                  # Change for different amount of Asteroids
            self.asteroids.append(Asteroid(random.randrange(0, width, 5),random.randrange(0, height, 5)))
        self.stars=[]       # A list of all background stars
        for i in range(25):                # Change for different amount of background Stars
            self.stars.append(Star())
        self.bullets = []   # A list of all bullets
        self.score = 0 # Possible score variable

    def handle_input(self):
        super().handle_input()
        pygame.key.set_repeat()
        keys_pressed = pygame.key.get_pressed()
        if keys_pressed[K_LEFT] and self.ship:
            self.ship.rotate(-1)
        if keys_pressed[K_RIGHT] and self.ship:
            self.ship.rotate(1)
        if keys_pressed[K_UP] and self.ship:
            self.ship.accelerate(0.05)
        if keys_pressed[K_DOWN] and self.ship:
            self.ship.accelerate(0) #TODO: Set to (0) to stop the ship instantly with down-key AKA EASYMODE.
        if keys_pressed[K_SPACE] and self.ship:
            if len(self.bullets) >= 15:
                del self.bullets[0]
                self.bullets.append(Bullet(self.ship.position, self.ship.rotation, self.frame))
            else:
                self.bullets.append(Bullet(self.ship.position, self.ship.rotation, self.frame))
    """         if len(self.bullets) == 0:
                self.bullets.append(Bullet(self.ship.position, self.ship.rotation, self.frame))
            else:
                if self.bullets[len(self.bullets)-1].ttl > 50:
                    self.bullets.append(Bullet(self.ship.position, self.ship.rotation, self.frame))

            # Försöker få delay i bullet interval
             """



    def update_simulation(self):
        """
        update_simulation() causes all objects in the game to update themselves
        """
        super().update_simulation()

        if self.ship:
            self.ship.update( self.width, self.height )
        for asteroid in self.asteroids:
            asteroid.update( self.width, self.height )
        for star in self.stars:
            star.update( self.width, self.height )
        for bullet in self.bullets:
            bullet.update( self.width, self.height )
            if bullet.ttl + 30 < self.frame:
                self.bullets.pop(self.bullets.index(bullet))
        self.handle_collisions()

    def render_objects(self):
        """
        render_objects() causes all objects in the game to draw themselves onto the screen
        """
        super().render_objects()
        # Render the ship:
        if self.ship:
            self.ship.draw( self.screen )
        # Render all the stars, if any:
        for star in self.stars:
            star.draw( self.screen )
        # Render all the asteroids, if any:
        for asteroid in self.asteroids:
            asteroid.draw( self.screen )
        # Render all the bullet, if any:
        for bullet in self.bullets:
            bullet.draw( self.screen )


    def handle_collisions(self):
        if self.ship:
            for asteroid in self.asteroids:
                if asteroid.collide(self.ship):
                    self.death_screen()
                for bullet in self.bullets:
                    if asteroid.contains(bullet.position):
                        self.score += 10
                        self.bullets.pop(self.bullets.index(bullet))
                        self.asteroids.pop(self.asteroids.index(asteroid))
                        if asteroid.health >= 2:
                            self.asteroids.append(Debris(asteroid.position))
                            self.asteroids.append(Debris(asteroid.position))
                            self.asteroids.append(Debris(asteroid.position))
                            self.asteroids.append(Debris(asteroid.position))

    def death_screen(self):
        game = Asteroids("Asteroids", 640, 480)
        label = self.myfont.render("Bitch Please!", 1, (8, 8, 8))
        label2 = self.myfont.render("You Died!", 1, (255, 255, 255))
        score = self.smallfont.render("Score:" + str(self.score), 1, (255, 255, 255))
        self.screen.blit(label, (self.width * 0.30, self.height * 0.35))
        self.screen.blit(label2, (self.width * 0.35, self.height * 0.40))
        self.screen.blit(score, (self.width * 0.4, self.height * 0.5))
        pygame.display.update()
        pygame.time.wait(2000)
        pygame.time.wait(500)
        game.runGame()
Exemplo n.º 13
0
import pygame
from objects import Ship, Bullet
import random

pygame.init()

run = True
clock = pygame.time.Clock()
screen_width, screen_height = (1000, 600)
window = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption('Space Invaders')
background_image = pygame.image.load('background.png')
ship_image = pygame.transform.scale(pygame.image.load('ship.png'), (64, 64))
enemy_image = pygame.transform.scale(pygame.image.load('enemy.png'), (64, 48))
ship = Ship(screen_width/2-32, screen_height-64, 64, 64, 5, ship_image)
bullet_image_up = pygame.image.load('bullet.png')
bullet_image_down = pygame.transform.rotate(bullet_image_up, 180)
bullets = []
pygame.time.set_timer(pygame.USEREVENT+1, random.randrange(1000, 2000))
ship_enemies = None
bullet_time = 0
enemy_move_time = 0
enemy_direction = 1
enemies_go_down = False


def redraw_window():
    window.blit(background_image, (0, 0))
    
def restart_game(text, color):
    global ship_enemies, ship, bullets
Exemplo n.º 14
0
class Asteroids(Game):
    """
    Asteroids extends the base class Game to provide logic for the specifics of the game
    """
    def __init__(self, name, width, height):
        super().__init__(name, width, height)
        # TODO: should create a Ship object here
        self.ship = Ship()  # None
        # TODO: should create asteroids
        self.asteroids = []
        for i in range(8):  # Change for different amount of Asteroids
            self.asteroids.append(Asteroid())
        self.stars = []
        for i in range(250):  # Change for different amount of background Stars
            self.stars.append(Star())
        # TODO: should create bullets
        self.bullets = []

    def handle_input(self):
        super().handle_input()
        keys_pressed = pygame.key.get_pressed()
        if keys_pressed[K_LEFT] and self.ship:
            self.ship.rotate(-0.5)
        if keys_pressed[K_RIGHT] and self.ship:
            self.ship.rotate(0.5)
        if keys_pressed[K_UP] and self.ship:
            self.ship.accelerate(0.005)
        if keys_pressed[K_DOWN] and self.ship:
            self.ship.accelerate(
                0
            )  #TODO: Set to (0) to stop the ship instantly with down-key AKA EASYMODE.
            pass
        if keys_pressed[K_SPACE] and self.ship:
            if len(self.bullets) < 10:
                self.bullets.append(
                    Bullet(self.ship.position, self.ship.rotation))
            elif len(self.bullets) >= 10:
                del self.bullets[0]
                self.bullets.append(
                    Bullet(self.ship.position, self.ship.rotation))
                # TODO: should create a bullet when the user fires

    def update_simulation(self):
        """
        update_simulation() causes all objects in the game to update themselves
        """
        super().update_simulation()

        if self.ship:
            self.ship.update(self.width, self.height)
        for asteroid in self.asteroids:
            asteroid.update(self.width, self.height)
        for star in self.stars:
            star.update(self.width, self.height)
        for bullets in self.bullets:
            bullets.update(self.width, self.height)
        # TODO: should probably work out how to remove a bullet when it gets old
        self.handle_collisions()

    def render_objects(self):
        """
        render_objects() causes all objects in the game to draw themselves onto the screen
        """
        super().render_objects()
        # Render the ship:
        if self.ship:
            self.ship.draw(self.screen)
        # Render all the stars, if any:
        for star in self.stars:
            star.draw(self.screen)
        # Render all the asteroids, if any:
        for asteroid in self.asteroids:
            asteroid.draw(self.screen)
        # Render all the bullet, if any:
        for bullet in self.bullets:
            bullet.draw(self.screen)

    def handle_collisions(self):
        if self.ship:
            for asteroid in self.asteroids:
                if asteroid.collide(self.ship):
                    self.running = False
                for bullet in self.bullets:
                    if asteroid.contains(bullet.position):
                        self.bullets.pop(self.bullets.index(bullet))
                        self.asteroids.pop(self.asteroids.index(asteroid))
Exemplo n.º 15
0
class Asteroids(Game):
    def __init__(self, name, width, height):
        super().__init__(name, width, height)
        self.width = width
        self.height = height
        self.ship = Ship()  # Creates a ship
        self.asteroids = []  # A list of all asteroids
        for i in range(5):  # Change for different amount of Asteroids
            self.asteroids.append(
                Asteroid(random.randrange(0, width, 5),
                         random.randrange(0, height, 5)))
        self.stars = []  # A list of all background stars
        for i in range(25):  # Change for different amount of background Stars
            self.stars.append(Star())
        self.bullets = []  # A list of all bullets
        self.score = 0  # Possible score variable

    def handle_input(self):
        super().handle_input()
        pygame.key.set_repeat(0, 100)
        keys_pressed = pygame.key.get_pressed()
        if keys_pressed[K_LEFT] and self.ship:
            self.ship.rotate(-3)
        if keys_pressed[K_RIGHT] and self.ship:
            self.ship.rotate(3)
        if keys_pressed[K_UP] and self.ship:
            self.ship.accelerate(0.05)
        if keys_pressed[K_DOWN] and self.ship:
            self.ship.accelerate(
                0
            )  #TODO: Set to (0) to stop the ship instantly with down-key AKA EASYMODE.
        if keys_pressed[K_SPACE] and self.ship:
            if time.time(
            ) - self.ship.shot_timer > self.ship.shot_delay:  #Limits the rate of fire. Cannot fire more often than shot_delay value
                self.ship.shot_timer = time.time(
                )  #if it shoots, saves last fired timestamp
                self.ship.spawnProtection = False  #removes Spawn protection if bullet is fired
                if len(
                        self.bullets
                ) >= 15:  #Does not allow more than 15 bullets in total. deletes the oldest if more than 15.
                    del self.bullets[0]
                    self.bullets.append(
                        Bullet(self.ship.position.copy(), self.ship.rotation,
                               self.ship.shot_timer)
                    )  #Spawns a bullet with ships location. rotation and timestamp when fired.
                else:
                    self.bullets.append(
                        Bullet(self.ship.position.copy(), self.ship.rotation,
                               self.ship.shot_timer))
        if keys_pressed[K_f] and self.ship:
            self.asteroids.append(
                Asteroid(
                    random.randrange(0, self.width, 5),
                    random.randrange(0, self.height,
                                     5)))  #Command for spawning more asteroids
        if keys_pressed[K_t] and self.ship:
            if time.time(
            ) - self.ship.jump_timer > self.ship.jump_delay:  #Checks if jumpdrive is on cooldown
                self.ship.jump_timer = time.time()  #Saves timestamp for jump
                self.ship.jumpDrive()  #Jumps the ship

    def update_simulation(self):
        """
        update_simulation() causes all objects in the game to update themselves
        """
        super().update_simulation()
        currentTime = time.time()  #Saves current timestamp for the update

        if self.ship:
            self.ship.update(self.width, self.height, self.dt)
        for asteroid in self.asteroids:
            asteroid.update(self.width, self.height, self.dt)
        for star in self.stars:
            star.update(self.width, self.height, self.dt)
        for bullet in self.bullets:
            bullet.update(self.width, self.height, self.dt)
            if bullet.time + 2 < currentTime:  #Deletes bullets that is older than 2 seconds
                self.bullets.pop(self.bullets.index(bullet))
        if self.ship.jump_timer + self.ship.jumpProtectionDuration < currentTime:  #Checks if jump protection is still active. if not, remove it
            self.ship.jumpProtection = False
        if self.ship.spawnProtectionTime + self.ship.spawnProtectionDuration < currentTime:
            self.ship.spawnProtection = False  #Checks if spawn protection is still active. if not, remove it
        self.handle_collisions()

    def render_objects(self):
        """
        render_objects() causes all objects in the game to draw themselves onto the screen
        """
        super().render_objects()
        # Render the ship:
        if self.ship:
            self.ship.draw(self.screen)
        # Render all the stars, if any:
        for star in self.stars:
            star.draw(self.screen)
        # Render all the asteroids, if any:
        for asteroid in self.asteroids:
            asteroid.draw(self.screen)
        # Render all the bullet, if any:
        for bullet in self.bullets:
            bullet.draw(self.screen)

    def handle_collisions(self):
        if self.ship:
            for asteroid in self.asteroids:
                if asteroid.collide(
                        self.ship
                ) and self.ship.spawnProtection == False and self.ship.jumpProtection == False:  #Checks if player is protected when colliding
                    self.ship.lives = -1  #NOT WORKING YET, Player has 3 lives. Plan is to do remove a life and gain 2-3 seconds immunity when losing a life.
                    if self.ship.lives < 0:  #If no more lives yet, > player dead
                        self.death_screen()
                    elif self.ship.lives > 1:
                        self.ship.spawnProtection = True
                        self.ship.spawnProtectionTime = time.time()

                for bullet in self.bullets:
                    if asteroid.contains(bullet.position):
                        self.score += 10
                        self.bullets.pop(self.bullets.index(bullet))
                        self.asteroids.pop(self.asteroids.index(asteroid))
                        if asteroid.health >= 2:
                            self.asteroids.append(
                                Debris(asteroid.position.copy()))
                            self.asteroids.append(
                                Debris(asteroid.position.copy()))
                            self.asteroids.append(
                                Debris(asteroid.position.copy()))
                            self.asteroids.append(
                                Debris(asteroid.position.copy()))
            #if asteroid.collide(self.asteroids):

    def death_screen(self):
        game = Asteroids("Asteroids", 1280, 720)
        label = self.myfont.render("Lives:" + str(self.ship.lives), 1,
                                   (255, 255, 255))
        label2 = self.myfont.render("You Died!", 1, (255, 255, 255))
        score = self.smallfont.render("Score:" + str(self.score), 1,
                                      (255, 255, 255))
        self.screen.blit(label, (self.width * 0.30, self.height * 0.35))
        self.screen.blit(label2, (self.width * 0.35, self.height * 0.40))
        self.screen.blit(score, (self.width * 0.4, self.height * 0.5))
        pygame.display.update()
        pygame.time.wait(2000)
        pygame.time.wait(500)
        for asteroids in self.asteroids:
            self.asteroids.pop(self.asteroids.index(asteroids))
        for bullet in self.bullets:
            self.bullets.pop(self.bullets.index(bullet))
        game.runGame()
Exemplo n.º 16
0
class App(EventManager):
    "Main application class that contain game loop logic"

    WHITE = (255, 255, 255)
    BLACK = (0, 0, 0)
    LGREY = (200, 200, 200)
    MAX_ASTEROIDS = 13

    def __init__(self):
        self._running = False
        self._display_surf = None
        self.size = self.width, self.height = 800, 600

    def init(self):
        pygame.init()
        self.clock = pygame.time.Clock()
        self._display_surf = pygame.display.set_mode(self.size, pygame.HWSURFACE | pygame.DOUBLEBUF)
        self._running = True
        pygame.display.set_caption("Asteroids")
        self.ship = None
        self.projectiles = []
        self.asteroids = []
        self.bg = pygame.image.load("assets/images/nebula_blue.s2014.png")
        self.debris_image = pygame.image.load("assets/images/debris2_blue.png")
        self.soundtrack = pygame.mixer.Sound("assets/sounds/soundtrack.wav")
        self.start_screen = self.make_start_screen()
        self.is_started = False
        self.is_paused = False
        self.is_over = False

    def start_game(self):
        self.step = 0
        self.score = 0
        self.ship = Ship(Vect(400, 400), Vect(0, 0), 0)
        self.soundtrack.play(-1)
        self.is_started = True
        self.is_over = False

    def stop_game(self):
        self.stop_all_sounds()
        self.is_over = True

    def stop_all_sounds(self):
        self.soundtrack.stop()
        self.ship.stop_sounds()

    def make_message_screen(self, title, subtitle):
        "make message surface with given title and subtitle under it"
        padding = 50
        bord_x = self.width - padding * 2
        bord_y = self.height - padding * 2
        font_file = pygame.font.match_font("Impact")
        font = pygame.font.Font(font_file, 88)
        title = font.render(title, True, self.WHITE)
        wtitle, htitle = title.get_size()
        sfont = pygame.font.Font(font_file, 28)
        sub = sfont.render(subtitle, True, self.WHITE)
        wsub, hsub = sub.get_size()
        screen = pygame.Surface(self.size)
        screen.fill(self.BLACK)
        pygame.draw.rect(screen, self.LGREY, (padding, padding, bord_x, bord_y), 2)
        screen.blit(title, (self.width / 2 - wtitle / 2, 200))
        screen.blit(sub, (self.width / 2 - wsub / 2, 400))
        return screen

    def make_start_screen(self):
        start = self.make_message_screen("Asteroids", "press any key to start")
        return start

    def make_over_screen(self):
        "game over screen with score"
        score_msg = "Your score is {}".format(self.score)
        return self.make_message_screen("Game over", score_msg)

    def make_stats(self):
        "make stats interface that displayes remaining lives and current score"
        font_file = pygame.font.match_font("Arial")
        font = pygame.font.Font(font_file, 20)
        lives = font.render("Lives: {}".format(self.ship.lives), True, self.WHITE)
        w, h = lives.get_size()
        score = font.render("Score: {}".format(self.score), True, self.WHITE)
        # put both texts one above the other on transparent bg with padding
        stats = pygame.Surface((w * 2, h * 3), pygame.SRCALPHA, 32)
        stats.blit(lives, (w / 2, h))
        stats.blit(score, (w / 2, h * 2))
        return stats

    def on_exit(self):
        self._running = False

    def is_playing(self):
        "True if game is played now, i.e. started and not over or paused"
        return self.is_started and not self.is_over and not self.is_paused

    def handle_bullets_collision(self):
        "find pairs of projectiles colliding with asteroids and remove both"
        asteroids = list(self.asteroids)
        for proj in list(self.projectiles):
            collisions = proj.collides_group(asteroids)
            if collisions:
                self.projectiles.remove(proj)
            for ast in collisions:
                if ast in self.asteroids:
                    ast.destroy()
                    self.score += 1

    def handle_ship_asteroid_collision(self):
        collide = self.ship.collides_group(self.asteroids)
        for ast in collide:
            ast.destroy()
        return collide

    def _keep_on_screen(self, obj):
        """update object coordinates to keep it on screen
        if the object is beyond screen, move it back
        do nothing if object is already on the screen"""
        obj.pos.x %= self.width
        obj.pos.y %= self.height

    def _update_obj(self, obj):
        "update object state and keep it on current screen"
        obj.update()
        self._keep_on_screen(obj)

    def spawn_asteroid(self):
        "spawn asteroid at random position, not in the ship's danger zone"
        pos = Vect.get_random(self.width, self.height)
        ast = Asteroid(pos)
        while self.ship.in_danger_zone(ast):
            pos = Vect.get_random(self.width, self.height)
            ast = Asteroid(pos)
        return ast

    def loop(self):
        if not self.is_playing():
            return
        self._update_obj(self.ship)
        if self.ship.is_shooting:
            proj = self.ship.shoot()
            if proj:
                self.projectiles.append(proj)
        if self.step % 15 == 0 and len(self.asteroids) < self.MAX_ASTEROIDS:
            self.asteroids.append(self.spawn_asteroid())
        for ast in self.asteroids:
            self._update_obj(ast)
        for proj in self.projectiles:
            self._update_obj(proj)
        if self.handle_ship_asteroid_collision():
            self.ship.hit()
            if not self.ship.lives:
                self.stop_game()
        self.projectiles = [proj for proj in self.projectiles if proj.active]
        self.asteroids = [ast for ast in self.asteroids if not ast.is_dead()]
        self.handle_bullets_collision()
        self.step += 1

    def _blit(self, surf, coord=(0, 0)):
        "blit given surface on the main surface using coordinates"
        self._display_surf.blit(surf, coord)

    def _render_obj(self, obj):
        "render given object on the main surface"
        surf, rect = obj.render()
        self._blit(surf, rect)

    def draw_bg(self):
        """draw animated background image using two identical asteroid images
        intially right image is centered and left one is beyond the screen
        as time passes images move to the right and left one takes position
        of the right one, and the the positions are reset to keep illusion of 
        infinite movement"""
        # width and height of flying asteroids image
        w, h = self.debris_image.get_size()
        # distance between two flying asteroids images
        d = self.width - w
        # initial coordinates of right image
        x, y = self.width / 2 - w / 2, self.height / 2 - h / 2
        # on this step left image is in the position of right
        reset_step = d + w
        offset = (self.step // 4) % reset_step
        self._blit(self.bg)
        self._blit(self.debris_image, (x + offset, y))
        self._blit(self.debris_image, (x - d - w + offset, y))

    def render(self):
        self._display_surf.fill(self.BLACK)
        if not self.is_started:
            self._blit(self.start_screen)
        elif self.is_over:
            self._blit(self.make_over_screen())
        else:
            self.draw_bg()
            self._render_obj(self.ship)
            for proj in self.projectiles:
                self._render_obj(proj)
            for ast in self.asteroids:
                self._render_obj(ast)
            self._blit(self.make_stats())
        pygame.display.flip()

    def cleanup(self):
        pygame.quit()
        sys.exit()

    def execute(self):

        if self.init() == False:
            self._running = False

        while self._running:
            self.clock.tick(60)
            for event in pygame.event.get():
                self.on_event(event)
            self.loop()
            self.render()
        self.cleanup()

    def on_key_down(self, event):

        if not self.is_playing():
            return
        if event.key == K_UP:
            self.ship.set_thrusting()
        elif event.key == K_LEFT:
            self.ship.turn_left()
        elif event.key == K_RIGHT:
            self.ship.turn_right()
        elif event.key == K_SPACE:
            if self.ship:
                self.ship.start_shooting()

    def on_key_up(self, event):

        if not self.is_started or self.is_over:
            self.start_game()
            return
        if event.key == K_ESCAPE:
            self.on_exit()
        elif event.key == K_UP:
            self.ship.set_idle()
        elif event.key == K_LEFT or event.key == K_RIGHT:
            self.ship.stop_turning()
        elif event.key == K_SPACE:
            self.ship.stop_shooting()
Exemplo n.º 17
0
 def create_enemy(self):
     ship = Ship()
     ship.set_part('body', self.items_factory.create_body())
     ship.set_part('leftwing', self.items_factory.create_left_wing())
     ship.set_part('rightwing', self.items_factory.create_right_wing())
     ship.set_part('leftrearwing',
                   self.items_factory.create_left_rear_wing())
     ship.set_part('rightrearwing',
                   self.items_factory.create_right_rear_wing())
     ship.set_part('weapon', self.items_factory.create_weapon())
     return ship
Exemplo n.º 18
0
class Asteroids(Game):
    """
    Asteroids extends the base class Game to provide logic for the specifics of the game
    """
    def __init__(self, name, width, height):
        super().__init__(name, width, height)

        self.ship = Ship()  # None  # TODO: should create a Ship object here
        # TODO: should create asteroids
        self.asteroids = []
        # TODO: should create stars
        self.stars = []
        self.bullets = []

    def handle_input(self):
        super().handle_input()
        keys_pressed = pygame.key.get_pressed()
        if keys_pressed[K_LEFT] and self.ship:
            self.ship.rotate(-0.1)
        if keys_pressed[K_RIGHT] and self.ship:
            self.ship.rotate(0.1)
        if keys_pressed[K_UP] and self.ship:
            self.ship.accelerate(0.0001)
        if keys_pressed[K_DOWN] and self.ship:
            self.ship.accelerate(0)
        if keys_pressed[K_SPACE] and self.ship:
            #self.bullet TODO: should create a bullet when the user fires
            pass

    def update_simulation(self):
        """
        update_simulation() causes all objects in the game to update themselves
        """
        super().update_simulation()

        if self.ship:
            self.ship.update(self.width, self.height)
        for asteroid in self.asteroids:
            asteroid.update(self.width, self.height)
        for star in self.stars:
            star.update(self.width, self.height)
        # TODO: should probably call update on our bullet/bullets here
        # TODO: should probably work out how to remove a bullet when it gets old
        self.handle_collisions()

    def render_objects(self):
        """
        render_objects() causes all objects in the game to draw themselves onto the screen
        """
        super().render_objects()
        # Render the ship:
        if self.ship:
            self.ship.draw(self.screen)
        # Render all the stars, if any:
        for star in self.stars:
            star.draw(self.screen)
        # Render all the asteroids, if any:
        for asteroid in self.asteroids:
            asteroid.draw(self.screen)
        # Render all the bullet, if any:
        for bullet in self.bullets:
            bullet.draw(self.screen)

    def handle_collisions(self):
        """
        handle_collisions() should check:
            - if our ship has crashed into an asteroid (the ship gets destroyed - game over!)
            - if a bullet has hit an asteroid (the asteroid gets destroyed)
        :return: 
        """
        # TODO: implement collission detection,
        #       using the collission detection methods in all of the shapes
        pass
Exemplo n.º 19
0
 def create_enemy(self):
     ship = Ship()
     ship.set_part('body', self.items_factory.create_body())
     return ship