Example #1
0
def test_blow_up():
    a = Spaceship(params['SPACE'])
    assert not hasattr(a, 'debris')
    assert a.intact
    a.blow_up(100)
    assert len(a.debris) == 3
    assert not a.intact
Example #2
0
class GameController:
    """
    Maintains the state of the game
    and manages interactions of game elements.
    """
    def __init__(self, SPACE, fadeout):
        """Initialize the game controller"""
        self.SPACE = SPACE
        self.fadeout = fadeout

        self.spaceship_hit = False
        self.asteroid_destroyed = False
        self.asteroids = [Asteroid(self.SPACE)]
        self.laser_beams = []
        self.spaceship = Spaceship(self.SPACE)

    def update(self):
        """Updates game state on every frame"""
        self.do_intersections()

        for asteroid in self.asteroids:
            asteroid.display()

        # Laser beam handler
        # replace (or augment) the next several
        # lines. Laser beam objects should remain in the scene
        # as many frames as their lifespan allows.

        life_span_list_check = []

        for l in range(len(self.laser_beams)):
            if self.laser_beams[l].lifespan > 0:
                self.laser_beams[l].lifespan -= 1
                self.laser_beams[l].display()
            elif self.laser_beams[l].lifespan == 0:
                life_span_list_check.append(l)

        for i in range(len(life_span_list_check)):
            self.laser_beams.pop(i)

        self.spaceship.display()

        # Carries out necessary actions if game over
        if self.spaceship_hit:
            if self.fadeout <= 0:
                fill(1)
                textSize(30)
                text("YOU HIT AN ASTEROID", self.SPACE['w'] / 2 - 165,
                     self.SPACE['h'] / 2)
            else:
                self.fadeout -= 1

        if self.asteroid_destroyed:
            fill(1)
            textSize(30)
            text("YOU DESTROYED THE ASTEROIDS!!!", self.SPACE['w'] / 2 - 250,
                 self.SPACE['h'] / 2)

    def fire_laser(self, x, y, rot):
        """Add a laser beam to the game"""
        x_vel = sin(radians(rot))
        y_vel = -cos(radians(rot))
        self.laser_beams.append(LaserBeam(self.SPACE, x, y, x_vel, y_vel))

    def handle_keypress(self, key, keycode=None):
        if (key == ' '):
            if self.spaceship.intact:
                self.spaceship.control(' ', self)
        if (keycode):
            if self.spaceship.intact:
                self.spaceship.control(keycode)

    def handle_keyup(self):
        if not self.spaceship.intact:
            self.spaceship.control('keyup')

    def do_intersections(self):
        """ intersections between 1) asteroids and laser beams
            2) asteroid and spaceship"""

        # ======================================================
        # Part 1: Intersections
        # check for intersections between asteroids and laser beams. Laser
        # beams should be removed
        # from the scene if they hit an asteroid, and the asteroid should
        # blow up

        new_list_asteroids = []
        new_list_laser_beams = []

        for j in range(len(self.laser_beams)):
            for i in range(len(self.asteroids)):
                if (abs(self.laser_beams[j].x - self.asteroids[i].x) < max(
                        self.asteroids[i].radius, self.laser_beams[j].radius)
                        and abs(self.laser_beams[j].y - self.asteroids[i].y) <
                        max(self.asteroids[i].radius,
                            self.laser_beams[j].radius)):
                    # We've intersected an asteroid
                    new_list_asteroids.append((j, i))
                    new_list_laser_beams.append(j)

        for a in new_list_asteroids:
            self.blow_up_asteroid(a[0], a[1])

        if len(self.asteroids) == 0:
            self.asteroid_destroyed = True

        # End of code changes for Intersections
        # ======================================================

        # If the space ship still hasn't been blown up
        if self.spaceship.intact:
            # Check each asteroid for intersection
            for i in range(len(self.asteroids)):
                if (abs(self.spaceship.x - self.asteroids[i].x) < max(
                        self.asteroids[i].radius, self.spaceship.radius)
                        and abs(self.spaceship.y - self.asteroids[i].y) < max(
                            self.asteroids[i].radius, self.spaceship.radius)):
                    # We've intersected an asteroid
                    self.spaceship.blow_up(self.fadeout)
                    self.spaceship_hit = True

    def blow_up_asteroid(self, j, i):
        """break a large asteriod into two medium asteroids
           ,break two medium asteriods into small asteroids
           ,and disappear small asteriods when hit by laser beams"""
        # ======================================================+

        # the code to blow up an asteroid.
        # The parameters represent the indexes for the list of
        # asteroids and the list of laser beams, indicating
        # which asteroid is hit by which laser beam.

        # I'll need to:
        # A) Remove the hit asteroid from the scene
        # B) Add appropriate smaller asteroids to the scene
        # C) Make sure that the smaller asteroids are positioned
        #    correctly and flying off in the correct directions

        # Specifically. If the large asteroid is hit, it should
        # break into two medium asteroids, which should fly off
        # perpendicularly to the direction of the laser beam.

        # If a medium asteroid is hit, it should break into three
        # small asteroids, two of which should fly off perpendicularly
        # to the direction of the laser beam, and the third
        # should fly off in the same direction that the laser
        # beam had been traveling.

        # If a small asteroid is hit, it disappears.

        # Begin code changes for Problem 4, Part 2: Asteroid blow-up
        SCALAR = 0.2
        if self.asteroids[i].asize == 'Large':
            self.asteroids.append(
                Asteroid(self.SPACE,
                         asize='Med',
                         x=self.asteroids[i].x,
                         y=self.asteroids[i].y,
                         x_vel=self.laser_beams[j].y_vel * SCALAR,
                         y_vel=-self.laser_beams[j].x_vel * SCALAR))
            self.asteroids.append(
                Asteroid(self.SPACE,
                         asize='Med',
                         x=self.asteroids[i].x,
                         y=self.asteroids[i].y,
                         x_vel=-self.laser_beams[j].y_vel * SCALAR,
                         y_vel=self.laser_beams[j].x_vel * SCALAR))
            self.asteroids.pop(i)
            self.laser_beams.pop(j)
        elif self.asteroids[i].asize == 'Med':
            self.asteroids.append(
                Asteroid(self.SPACE,
                         asize='Small',
                         x=self.asteroids[i].x,
                         y=self.asteroids[i].y,
                         x_vel=self.laser_beams[j].y_vel * SCALAR,
                         y_vel=-self.laser_beams[j].x_vel * SCALAR))
            self.asteroids.append(
                Asteroid(self.SPACE,
                         asize='Small',
                         x=self.asteroids[i].x,
                         y=self.asteroids[i].y,
                         x_vel=-self.laser_beams[j].y_vel * SCALAR,
                         y_vel=self.laser_beams[j].x_vel * SCALAR))
            self.asteroids.append(
                Asteroid(self.SPACE,
                         asize='Small',
                         x=self.asteroids[i].x,
                         y=self.asteroids[i].y,
                         x_vel=self.laser_beams[j].x_vel * SCALAR,
                         y_vel=self.laser_beams[j].y_vel * SCALAR))
            self.asteroids.pop(i)
            self.laser_beams.pop(j)
        else:
            self.asteroids.pop(i)
            self.laser_beams.pop(j)
Example #3
0
class GameController:
    """
    Maintains the state of the game
    and manages interactions of game elements.
    """

    def __init__(self, SPACE, fadeout):
        """Initialize the game controller"""
        self.SPACE = SPACE
        self.fadeout = fadeout

        self.spaceship_hit = False
        self.asteroid_destroyed = False
        self.asteroids = [Asteroid(self.SPACE)]
        self.laser_beams = []
        self.spaceship = Spaceship(self.SPACE)

    def update(self):
        """Updates game state on every frame"""
        self.do_intersections()

        for asteroid in self.asteroids:
            asteroid.display()
        
         
        # ======================================================
        # TODO: Problem 3, Part 2: Laser beam handler
        # Your code will replace (or augment) the next several
        # lines. Laser beam objects should remain in the scene
        # as many frames as their lifespan allows.
        # Begin problem 3 code changes
        
        self.laser_beams = [l for l in self.laser_beams 
                            if frameCount - l.count < 100]

        for l in range(len(self.laser_beams)):
            self.laser_beams[l].display()

        # End problem 3, part 2 code changes
        # =======================================================

        self.spaceship.display()

        # Carries out necessary actions if game over
        if self.spaceship_hit:
            if self.fadeout <= 0:
                fill(1)
                textSize(30)
                text("YOU HIT AN ASTEROID",
                     self.SPACE['w']/2 - 165, self.SPACE['h']/2)
            else:
                self.fadeout -= 1

        if self.asteroid_destroyed:
            fill(1)
            textSize(30)
            text("YOU DESTROYED THE ASTEROIDS!!!",
                 self.SPACE['w']/2 - 250, self.SPACE['h']/2)

    def fire_laser(self, x, y, rot):
        """Add a laser beam to the game"""
        x_vel = sin(radians(rot))
        y_vel = -cos(radians(rot))
        new_laser_beam = LaserBeam(self.SPACE, x, y, x_vel, y_vel, frameCount)
        self.laser_beams.append(new_laser_beam)

    def handle_keypress(self, key, keycode=None):
        if (key == ' '):
            if self.spaceship.intact:
                self.spaceship.control(' ', self)
        if (keycode):
            if self.spaceship.intact:
                self.spaceship.control(keycode)

    def handle_keyup(self):
        if self.spaceship.intact:
            self.spaceship.control('keyup')

    def do_intersections(self):
        # ======================================================
        # TODO: Problem 4, Part 1: Intersections
        # Here's where you'll probably want to check for intersections
        # between asteroids and laser beams. Laser beams should be removed
        # from the scene if they hit an asteroid, and the asteroid should
        # blow up (the blow_up_asteroid method also must be written. It's
        # been started for you below).
        #
        # The intersection logic below between the spaceship
        # and asteroids should give a hint as to how this will work.
        # Begin code changes for Problem 4, Part 1: Intersections

        new_laser_beams = []
        for lb_index, laser_beam in enumerate(self.laser_beams):
            for a_index, asteroid in enumerate(self.asteroids):
                if (abs(laser_beam.x - asteroid.x)
                    < max(asteroid.radius, laser_beam.radius)
                    and
                    abs(laser_beam.y - asteroid.y)
                    < max(asteroid.radius, laser_beam.radius)):
                    self.blow_up_asteroid(lb_index, a_index)
                    break
            else:
                new_laser_beams.append(laser_beam)
            
        self.laser_beams = new_laser_beams
                                       

        # End of code changes for Problem 4, Part 1: Intersections
        # ======================================================

        # If the space ship still hasn't been blown up
        if self.spaceship.intact:
            # Check each asteroid for intersection
            for i in range(len(self.asteroids)):
                if (
                      abs(self.spaceship.x - self.asteroids[i].x)
                      < max(self.asteroids[i].radius, self.spaceship.radius)
                      and
                      abs(self.spaceship.y - self.asteroids[i].y)
                      < max(self.asteroids[i].radius, self.spaceship.radius)):
                    # We've intersected an asteroid
                    self.spaceship.blow_up(self.fadeout)
                    self.spaceship_hit = True

    def blow_up_asteroid(self, lb_index, a_index):
        # ======================================================
        # TODO: Problem 4, Part 2: Asteroid blow-up

        # Here you'll write the code to blow up an asteroid.
        # The parameters represent the indexes for the list of
        # asteroids and the list of laser beams, indicating
        # which asteroid is hit by which laser beam.

        # You'll need to:
        # A) Remove the hit asteroid from the scene
        # B) Add appropriate smaller asteroids to the scene
        # C) Make sure that the smaller asteroids are positioned
        #    correctly and flying off in the correct directions

        # Specifically. If the large asteroid is hit, it should
        # break into two medium asteroids, which should fly off
        # perpendicularly to the direction of the laser beam.

        # If a medium asteroid is hit, it should break into three
        # small asteroids, two of which should fly off perpendicularly
        # to the direction of the laser beam, and the third
        # should fly off in the same direction that the laser
        # beam had been traveling.

        # If a small asteroid is hit, it disappears.

        # Begin code changes for Problem 4, Part 2: Asteroid blow-up
        blown_asteroid = self.asteroids.pop(a_index)
        hit_laser_beam = self.laser_beams[lb_index]
        if blown_asteroid.asize == 'Large':
            asteroid_med1 = Asteroid(self.SPACE, asize='Med',x=blown_asteroid.x, y=blown_asteroid.y, x_vel=-hit_laser_beam.x_vel/2, y_vel=hit_laser_beam.y_vel/2)
            self.asteroids.append(asteroid_med1)
            asteroid_med2 = Asteroid(self.SPACE, asize='Med', x=blown_asteroid.x, y=blown_asteroid.y, x_vel=hit_laser_beam.x_vel/2, y_vel=-hit_laser_beam.y_vel/2)
            self.asteroids.append(asteroid_med2)
        if blown_asteroid.asize == 'Med':
            asteroid_sm1 = Asteroid(self.SPACE, asize='Small',x=blown_asteroid.x, y=blown_asteroid.y, x_vel=-hit_laser_beam.x_vel/2, y_vel=hit_laser_beam.y_vel/2)
            self.asteroids.append(asteroid_sm1)
            asteroid_sm2 = Asteroid(self.SPACE, asize='Small', x=blown_asteroid.x, y=blown_asteroid.y, x_vel=hit_laser_beam.x_vel/2, y_vel=-hit_laser_beam.y_vel/2)
            self.asteroids.append(asteroid_sm2)
            asteroid_sm3 = Asteroid(self.SPACE, asize='Small', x=blown_asteroid.x, y=blown_asteroid.y, x_vel=hit_laser_beam.x_vel/2, y_vel=hit_laser_beam.y_vel/2)
            self.asteroids.append(asteroid_sm3)
        if not self.asteroids:
            self.asteroid_destroyed = True
Example #4
0
class GameController:
    """
    Maintains the state of the game
    and manages interactions of game elements.
    """
    def __init__(self, SPACE, fadeout):
        """Initialize the game controller"""
        self.fadeout = fadeout
        self.SPACE = SPACE

        self.spaceship_hit = False
        self.asteroid_destroyed = False
        self.asteroids = [Asteroid(self.SPACE)]
        self.laser_beams = []
        self.spaceship = Spaceship(self.SPACE)

    def update(self):
        """Updates game state on every frame"""
        # asteroid_blow_up is an boolean that break the
        # for loop in intersection
        self.asteroid_blow_up = False
        self.do_intersections()

        for asteroid in self.asteroids:
            asteroid.display()

        # ======================================================
        # Problem 3, Part 2: Laser beam handler
        # Your code will replace (or augment) the next several
        # lines. Laser beam objects should remain in the scene
        # as many frames as their lifespan allows.
        # Begin problem 3 code changes

        for l in range(len(self.laser_beams)):
            if (self.laser_beams[l].counter > 0):
                self.laser_beams[l].display()

        # =======================================================

        self.spaceship.display()

        # Carries out necessary actions if game over
        if self.spaceship_hit:
            if self.fadeout <= 0:
                fill(1)
                textSize(30)
                text("YOU HIT AN ASTEROID", self.SPACE['w'] / 2 - 165,
                     self.SPACE['h'] / 2)
            else:
                self.fadeout -= 1

        if self.asteroid_destroyed:
            fill(1)
            textSize(30)
            text("YOU DESTROYED THE ASTEROIDS!!!", self.SPACE['w'] / 2 - 250,
                 self.SPACE['h'] / 2)

    def fire_laser(self, x, y, rot):
        """Add a laser beam to the game"""
        x_vel = sin(radians(rot))
        y_vel = -cos(radians(rot))
        self.laser_beams.append(LaserBeam(self.SPACE, x, y, x_vel, y_vel))

    def handle_keypress(self, key, keycode=None):
        if (key == ' '):
            if self.spaceship.intact:
                self.spaceship.control(' ', self)
        if (keycode):
            if self.spaceship.intact:
                self.spaceship.control(keycode)

    def handle_keyup(self):
        if self.spaceship.intact:
            self.spaceship.control('keyup')

    def do_intersections(self):
        ''' determine where asteroids and laser beam itersect!!
        It also determine the intersect btw asteroids and spaceship'''
        # Here's where you'll probably want to check for intersections
        # between asteroids and laser beams. Laser beams should be removed
        # from the scene if they hit an asteroid, and the asteroid should
        # blow up (the blow_up_asteroid method also must be written. It's
        # been started for you below).

        for j in range(len(self.asteroids)):
            if self.asteroid_blow_up:
                break
            for i in range(len(self.laser_beams)):
                if (abs(self.asteroids[j].x - self.laser_beams[i].x) < max(
                        self.laser_beams[i].radius, self.asteroids[j].radius)
                        and abs(self.asteroids[j].y - self.laser_beams[i].y) <
                        max(self.laser_beams[i].radius,
                            self.asteroids[j].radius)):
                    self.blow_up_asteroid(i, j)
                    self.laser_beams[i].lifespan = False
                    self.laser_beams.remove(self.laser_beams[i])
                    if self.asteroid_blow_up:
                        break
        # ======================================================

        # If the space ship still hasn't been blown up
        if self.spaceship.intact:
            # Check each asteroid for intersection
            for i in range(len(self.asteroids)):
                # if self.asteroids[i].existance is True:

                if (abs(self.spaceship.x - self.asteroids[i].x) < max(
                        self.asteroids[i].radius, self.spaceship.radius)
                        and abs(self.spaceship.y - self.asteroids[i].y) < max(
                            self.asteroids[i].radius, self.spaceship.radius)):
                    # We've intersected an asteroid
                    self.spaceship.blow_up(self.fadeout)
                    self.spaceship_hit = True

    def blow_up_asteroid(self, i, j):
        '''decide what is going happend after asteroid hit by
        laser beam!'''
        if self.asteroids[j].asize == 'Large':
            self.asteroids.append(
                Asteroid(self.SPACE, 'Med', self.laser_beams[i].x,
                         self.laser_beams[i].y, self.laser_beams[i].x_vel,
                         -self.laser_beams[i].y_vel, 0, 0.0))
            self.asteroids.append(
                Asteroid(self.SPACE, 'Med', self.laser_beams[i].x,
                         self.laser_beams[i].y, -self.laser_beams[i].x_vel,
                         self.laser_beams[i].y_vel, 0, 0.0))

        elif self.asteroids[j].asize == 'Med':
            self.asteroids.append(
                Asteroid(self.SPACE, 'Small', self.laser_beams[i].x,
                         self.laser_beams[i].y, self.laser_beams[i].x_vel,
                         -self.laser_beams[i].y_vel, 0, 0.0))
            self.asteroids.append(
                Asteroid(self.SPACE, 'Small', self.laser_beams[i].x,
                         self.laser_beams[i].y, -self.laser_beams[i].x_vel,
                         self.laser_beams[i].y_vel, 0, 0.0))
            self.asteroids.append(
                Asteroid(self.SPACE, 'Small', self.laser_beams[i].x,
                         self.laser_beams[i].y, self.laser_beams[i].x_vel,
                         self.laser_beams[i].y_vel, 0, 0.0))

        elif self.asteroids[j].asize == 'Small':
            self.asteroids[j].asize = ' '

        self.asteroids.remove(self.asteroids[j])
        self.asteroid_blow_up = True
        if len(self.asteroids) == 0:
            self.asteroid_destroyed = True
Example #5
0
class GameController:
    """
    Maintains the state of the game
    and manages interactions of game elements.
    """
    def __init__(self, SPACE, fadeout):
        """Initialize the game controller"""
        self.SPACE = SPACE
        self.fadeout = fadeout

        self.spaceship_hit = False
        self.asteroid_destroyed = False
        self.asteroids = [Asteroid(self.SPACE)]
        self.laser_beams = []
        self.spaceship = Spaceship(self.SPACE)

    def update(self):
        """Updates game state on every frame"""
        self.do_intersections()

        for asteroid in self.asteroids:
            if asteroid.intact:
                asteroid.display()
            else:
                self.asteroids.remove(asteroid)
        if not self.asteroids:
            self.asteroid_destroyed = True

        # Laser beam handler

        for l in (self.laser_beams):
            if l.start_frame >= frameCount - 100 and l.intact:
                l.display()
            else:
                self.laser_beams.remove(l)

        self.spaceship.display()

        # Carries out necessary actions if game over
        if self.spaceship_hit:
            if self.fadeout <= 0:
                fill(1)
                textSize(30)
                text("YOU HIT AN ASTEROID", self.SPACE['w'] / 2 - 165,
                     self.SPACE['h'] / 2)
            else:
                self.fadeout -= 1

        if self.asteroid_destroyed:
            fill(1)
            textSize(30)
            text("YOU DESTROYED THE ASTEROIDS!!!", self.SPACE['w'] / 2 - 250,
                 self.SPACE['h'] / 2)

    def fire_laser(self, x, y, rot):
        """Add a laser beam to the game"""
        x_vel = sin(radians(rot))
        y_vel = -cos(radians(rot))
        self.laser_beams.append(
            LaserBeam(self.SPACE, x, y, x_vel, y_vel, frameCount))

    def handle_keypress(self, key, keycode=None):
        if (key == ' '):
            if self.spaceship.intact:
                self.spaceship.control(' ', self)
        if (keycode):
            if self.spaceship.intact:
                self.spaceship.control(keycode)

    def handle_keyup(self):
        if self.spaceship.intact:
            self.spaceship.control('keyup')

    def do_intersections(self):
        # Check each asteroid for intersection
        for i in range(len(self.asteroids)):
            for j in range(len(self.laser_beams)):
                if (abs(self.asteroids[i].x - self.laser_beams[j].x) < max(
                        self.asteroids[i].radius, self.laser_beams[j].radius)
                        and abs(self.asteroids[i].y - self.laser_beams[j].y) <
                        max(self.asteroids[i].radius,
                            self.laser_beams[j].radius)):
                    self.blow_up_asteroid(i, j)

        # If the space ship still hasn't been blown up
        if self.spaceship.intact:
            # Check each asteroid for intersection
            for i in range(len(self.asteroids)):
                if (abs(self.spaceship.x - self.asteroids[i].x) < max(
                        self.asteroids[i].radius, self.spaceship.radius)
                        and abs(self.spaceship.y - self.asteroids[i].y) < max(
                            self.asteroids[i].radius, self.spaceship.radius)):
                    # We've intersected an asteroid
                    self.spaceship.blow_up(self.fadeout)
                    self.spaceship_hit = True

    def blow_up_asteroid(self, i, j):
        # Asteroid blow-up

        self.asteroids[i].intact = False
        self.laser_beams[j].intact = False
        # Add new astroids.
        x = self.asteroids[i].x
        y = self.asteroids[i].y
        x_vel = self.laser_beams[j].x_vel
        y_vel = self.laser_beams[j].y_vel
        if self.asteroids[i].asize == 'Large':
            self.asteroids.append(
                Asteroid(self.SPACE,
                         'Med',
                         x,
                         y,
                         x_vel=y_vel / 5,
                         y_vel=-x_vel / 5))
            self.asteroids.append(
                Asteroid(self.SPACE,
                         'Med',
                         x,
                         y,
                         x_vel=-y_vel / 5,
                         y_vel=x_vel / 5))
        if self.asteroids[i].asize == 'Med':
            self.asteroids.append(
                Asteroid(self.SPACE,
                         'Small',
                         x,
                         y,
                         x_vel=y_vel / 5,
                         y_vel=-x_vel / 5))
            self.asteroids.append(
                Asteroid(self.SPACE,
                         'Small',
                         x,
                         y,
                         x_vel=-y_vel / 5,
                         y_vel=x_vel / 5))
            self.asteroids.append(
                Asteroid(self.SPACE,
                         'Small',
                         x,
                         y,
                         x_vel=x_vel / 5,
                         y_vel=y_vel / 5))
Example #6
0
class GameController:
    """
    Maintains the state of the game
    and manages interactions of game elements.
    """
    def __init__(self, SPACE, fadeout):
        """Initialize the game controller"""
        self.SPACE = SPACE
        self.fadeout = fadeout

        self.spaceship_hit = False
        self.asteroid_destroyed = False
        self.asteroids = [Asteroid(self.SPACE)]
        self.laser_beams = []
        self.spaceship = Spaceship(self.SPACE)
        # Problem 3: set lifespan for passing to laserbeam class
        self.lifespan = 100
        # magic number for laser beam run out of lifespan
        self.DIE = 0

    def update(self):
        """Updates game state on every frame"""
        self.do_intersections()

        for asteroid in self.asteroids:
            asteroid.display()
        # ======================================================
        # Problem 3, Part 2: Laser beam handler
        # Your code will replace (or augment) the next several
        # lines. Laser beam objects should remain in the scene
        # as many frames as their lifespan allows.
        # Begin problem 3 code changes

        for l in range(len(self.laser_beams)):
            if self.laser_beams[l].lifespan > self.DIE:
                self.laser_beams[l].display()
                self.laser_beams[l].lifespan -= 1

        # End problem 3, part 2 code changes
        # =======================================================

        self.spaceship.display()

        # Carries out necessary actions if game over
        if self.spaceship_hit:
            if self.fadeout <= 0:
                fill(1)
                textSize(30)
                text("YOU HIT AN ASTEROID", self.SPACE['w'] / 2 - 165,
                     self.SPACE['h'] / 2)
            else:
                self.fadeout -= 1

        if self.asteroid_destroyed:
            fill(1)
            textSize(30)
            text("YOU DESTROYED THE ASTEROIDS!!!", self.SPACE['w'] / 2 - 250,
                 self.SPACE['h'] / 2)

    def fire_laser(self, x, y, rot):
        """Add a laser beam to the game"""
        x_vel = sin(radians(rot))
        y_vel = -cos(radians(rot))
        self.laser_beams.append(
            LaserBeam(self.SPACE, x, y, x_vel, y_vel, self.lifespan))

    def handle_keypress(self, key, keycode=None):
        if (key == ' '):
            if self.spaceship.intact:
                self.spaceship.control(' ', self)
        if (keycode):
            if self.spaceship.intact:
                self.spaceship.control(keycode)

    def handle_keyup(self):
        # problem 2: delete the wrong condition
        # if not self.spaceship.intact:
        self.spaceship.control('keyup')

    def do_intersections(self):
        # ======================================================
        # Problem 4, Part 1: Intersections
        # Here's where you'll probably want to check for intersections
        # between asteroids and laser beams. Laser beams should be removed
        # from the scene if they hit an asteroid, and the asteroid should
        # blow up (the blow_up_asteroid method also must be written. It's
        # been started for you below).
        # The intersection logic below between the spaceship
        # and asteroids should give a hint as to how this will work.
        # Begin code changes for Problem 4, Part 1: Intersections
        if len(self.asteroids) == 0:
            self.asteroid_destroyed = True
        else:
            for asteroid in self.asteroids:
                for beam in self.laser_beams:
                    if (abs(beam.x - asteroid.x) < max(asteroid.radius,
                                                       beam.radius)
                            and abs(beam.y - asteroid.y) < max(
                                asteroid.radius, beam.radius)
                            # make sure that the laser beam is active
                            and beam.lifespan > self.DIE):
                        # end the lifespan of laser beam after intersection
                        beam.lifespan = self.DIE
                        # call blow_up_asteroid function
                        self.blow_up_asteroid(asteroid, beam)
        # End of code changes for Problem 4, Part 1: Intersections
        # ======================================================

        # If the space ship still hasn't been blown up
        if self.spaceship.intact:
            # Check each asteroid for intersection
            for i in range(len(self.asteroids)):
                if (abs(self.spaceship.x - self.asteroids[i].x) < max(
                        self.asteroids[i].radius, self.spaceship.radius)
                        and abs(self.spaceship.y - self.asteroids[i].y) < max(
                            self.asteroids[i].radius, self.spaceship.radius)):
                    # We've intersected an asteroid
                    self.spaceship.blow_up(self.fadeout)
                    self.spaceship_hit = True

    def blow_up_asteroid(self, i, j):
        # ======================================================
        # Problem 4, Part 2: Asteroid blow-up
        # Begin code changes for Problem 4, Part 2: Asteroid blow-up

        # slow down the speed of asteroids pieces
        speed_factor = 0.5
        # I understand that usually we don't name item using index,
        # but I find using item instead of index in the loop is much more
        # efficient and I don't want to change names in starter's code
        if i.asize == 'Large':
            # B) Add appropriate smaller asteroids to the scene
            # Specifically. If the large asteroid is hit, it should
            # break into two medium asteroids, which should fly off
            # perpendicularly to the direction of the laser beam.
            piece_1 = Asteroid(self.SPACE)
            piece_1.asize = 'Med'
            # C) Make sure that the smaller asteroids are positioned
            # correctly and flying off in the correct directions
            piece_1.x = i.x
            piece_1.y = i.y
            piece_1.x_vel = -j.x_vel * speed_factor
            piece_1.y_vel = j.y_vel * speed_factor
            self.asteroids.append(piece_1)
            piece_2 = Asteroid(self.SPACE)
            piece_2.asize = 'Med'
            piece_2.x = i.x
            piece_2.y = i.y
            piece_2.x_vel = j.x_vel * speed_factor
            piece_2.y_vel = -j.y_vel * speed_factor
            self.asteroids.append(piece_2)
            # A) Remove the hit asteroid from the scene
            self.asteroids.remove(i)

        # If a medium asteroid is hit, it should break into 3 small asteroids
        if i.asize == 'Med':
            # two of which should fly off perpendicularly
            # to the direction of the laser beam
            piece_1 = Asteroid(self.SPACE)
            piece_1.asize = 'Small'
            piece_1.x = i.x
            piece_1.y = i.y
            piece_1.x_vel = -j.x_vel * speed_factor
            piece_1.y_vel = j.y_vel * speed_factor
            self.asteroids.append(piece_1)
            piece_2 = Asteroid(self.SPACE)
            piece_2.asize = 'Small'
            piece_2.x = i.x
            piece_2.y = i.y
            piece_2.x_vel = j.x_vel * speed_factor
            piece_2.y_vel = -j.y_vel * speed_factor
            self.asteroids.append(piece_2)
            # the third should fly off in the same direction that the laser
            # beam had been traveling.
            piece_3 = Asteroid(self.SPACE)
            piece_3.asize = 'Small'
            piece_3.x = i.x
            piece_3.y = i.y
            piece_3.x_vel = j.x_vel * speed_factor
            piece_3.y_vel = j.y_vel * speed_factor
            self.asteroids.append(piece_3)
            self.asteroids.remove(i)

        # If a small asteroid is hit, it disappears.
        if i.asize == 'Small':
            self.asteroids.remove(i)
Example #7
0
class GameController:

    def __init__(self, SPACE, fadeout):
        """Initialize the game controller"""
        self.fadeout = fadeout
        self.SPACE = SPACE

        self.spaceship_hit = False
        self.asteroid_destroyed = False
        self.asteroids = [Asteroid(self.SPACE)]
        self.laser_beams = []
        self.spaceship = Spaceship(self.SPACE)

    def update(self):
        """Updates game state on every frame"""
        # asteroid_blow_up is an boolean that break the
        # for loop in intersection
        self.asteroid_blow_up = False
        self.do_intersections()

        for asteroid in self.asteroids:
            asteroid.display()

        for l in range(len(self.laser_beams)):
            if(self.laser_beams[l].counter > 0):
                self.laser_beams[l].display()

        self.spaceship.display()

        # Carries out necessary actions if game over
        if self.spaceship_hit:
            if self.fadeout <= 0:
                fill(1)
                textSize(30)
                text("YOU HIT AN ASTEROID",
                     self.SPACE['w']/2 - 165, self.SPACE['h']/2)
            else:
                self.fadeout -= 1

        if self.asteroid_destroyed:
            fill(1)
            textSize(30)
            text("YOU DESTROYED THE ASTEROIDS!!!",
                 self.SPACE['w']/2 - 250, self.SPACE['h']/2)

    def fire_laser(self, x, y, rot):
        """Add a laser beam to the game"""
        x_vel = sin(radians(rot))
        y_vel = -cos(radians(rot))
        self.laser_beams.append(
            LaserBeam(self.SPACE, x, y, x_vel, y_vel)
            )

    def handle_keypress(self, key, keycode=None):
        if (key == ' '):
            if self.spaceship.intact:
                self.spaceship.control(' ', self)
        if (keycode):
            if self.spaceship.intact:
                self.spaceship.control(keycode)

    def handle_keyup(self):
        if self.spaceship.intact:
            self.spaceship.control('keyup')

    def do_intersections(self):
        ''' determine where asteroids and laser beam itersect!!
        It also determine the intersect btw asteroids and spaceship'''

        for j in range(len(self.asteroids)):
            if self.asteroid_blow_up:
                break
            for i in range(len(self.laser_beams)):
                if (
                        abs(self.asteroids[j].x - self.laser_beams[i].x)
                        < max(self.laser_beams[i].radius, self.asteroids[j].
                              radius)
                        and
                        abs(self.asteroids[j].y - self.laser_beams[i].y)
                        < max(self.laser_beams[i].radius, self.asteroids[j].
                              radius)):
                    self.blow_up_asteroid(i, j)
                    self.laser_beams[i].lifespan = False
                    self.laser_beams.remove(self.laser_beams[i])
                    if self.asteroid_blow_up:
                        break

        # If the space ship still hasn't been blown up
        if self.spaceship.intact:
            # Check each asteroid for intersection
            for i in range(len(self.asteroids)):

                if (
                        abs(self.spaceship.x - self.asteroids[i].x)
                        < max(self.asteroids[i].radius,
                              self.spaceship.radius)
                        and
                        abs(self.spaceship.y - self.asteroids[i].y)
                        < max(self.asteroids[i].radius,
                              self.spaceship.radius)):

                    # We've intersected an asteroid
                    self.spaceship.blow_up(self.fadeout)
                    self.spaceship_hit = True

    def blow_up_asteroid(self, i, j):
        '''decide what is going happend after asteroid hit by
        laser beam!'''
        if self.asteroids[j].asize == 'Large':
            self.asteroids.append(Asteroid(self.SPACE, 'Med',
                                           self.laser_beams[i].x,
                                           self.laser_beams[i].y,
                                           self.laser_beams[i].x_vel,
                                           - self.laser_beams[i].y_vel,
                                           0, 0.0))
            self.asteroids.append(Asteroid(self.SPACE, 'Med',
                                           self.laser_beams[i].x,
                                           self.laser_beams[i].y,
                                           - self.laser_beams[i].x_vel,
                                           self.laser_beams[i].y_vel,
                                           0, 0.0))

        elif self.asteroids[j].asize == 'Med':
            self.asteroids.append(Asteroid(self.SPACE, 'Small',
                                           self.laser_beams[i].x,
                                           self.laser_beams[i].y,
                                           self.laser_beams[i].x_vel,
                                           - self.laser_beams[i].y_vel,
                                           0, 0.0))
            self.asteroids.append(Asteroid(self.SPACE, 'Small',
                                           self.laser_beams[i].x,
                                           self.laser_beams[i].y,
                                           - self.laser_beams[i].x_vel,
                                           self.laser_beams[i].y_vel, 0,
                                           0.0))
            self.asteroids.append(Asteroid(self.SPACE, 'Small',
                                           self.laser_beams[i].x,
                                           self.laser_beams[i].y,
                                           self.laser_beams[i].x_vel,
                                           self.laser_beams[i].y_vel, 0,
                                           0.0))

        elif self.asteroids[j].asize == 'Small':
            self.asteroids[j].asize = ' '

        self.asteroids.remove(self.asteroids[j])
        self.asteroid_blow_up = True
        if len(self.asteroids) == 0:
            self.asteroid_destroyed = True