Пример #1
0
def create_ufo(ai_settings, screen, ufo_imgs, points, ufo_group):
    ufo = Ufo(ai_settings, screen, ufo_imgs, points)
    ufo_width = ufo.rect.width
    ufo.x = 0 - ufo_width
    ufo.rect.x = ufo.x
    ufo.rect.y = 40
    ufo_group.add(ufo)
Пример #2
0
    def reset(self):
        self.laser = Laser()
        self.ufo = Ufo()

        self.alpha = 0 #angle between laserbeam and ufo
        self.gamma = 0 #angle between center and left/right end of ufo circle
        self.hit = False
Пример #3
0
    def __init__(self):
        coloroma_init(autoreset=False)
        self.__score = 0
        self.__last_level_score = 0
        self.__ticks = 0
        self.__level_ticks = 0
        self.__level = 1
        self.__lives_used = 0
        self.__paddle = Paddle()
        self.__bricks_broken = 0
        self.__balls = [Ball(paddle=self.__paddle)]
        self.__cnt_active_balls = 0
        self.__cnt_active_bricks = 100
        self.__game_status = GAME_END
        self.__powerups = []
        self.__kb = KBHit()
        self.__explode_ids = [x for x in range(8, 14)]
        self.__explode_nbrs_ids = [7, 14, 28, 29, 30, 31, 32, 33]
        self.__brick_structure_y_fall = 0
        self.__fall_bricks = 0
        self.__bullets = []
        self.__ufo = Ufo()
        self.__ufo_bombs = []
        self.__ufo_bricks = []
        self.__map_position_to_bricks = []

        clear_terminal_screen()
        self._draw_bricks()
        self._loop()
Пример #4
0
def create_startrek(ai_settings, screen, startreks, startrek_number, row_number):
	"""creaye a startrek and place it in the row"""
	startrek = Ufo(ai_settings, screen)
	startrek_width = startrek.rect.width
	startrek.x = startrek_width + 2 * startrek_width * startrek_number
	startrek.rect.x = startrek.x
	startrek.rect.y = startrek.rect.height + 2 * startrek.rect.height * row_number
	startreks.add(startrek)
Пример #5
0
 def _create_ufo(self, ufo_number, row_number):
     """Create and UFO and place it in the row."""
     ufo = Ufo(self)
     ufo_width, ufo_height = ufo.rect.size
     ufo.x = 5 * ufo_width + 2 * ufo_width * ufo_number
     ufo.rect.x = ufo.x
     ufo.y = ufo_height + 2 * ufo_height * row_number
     ufo.rect.y = ufo.y
     self.ufos.add(ufo)
Пример #6
0
def create_random_ufo(ai_settings, screen):
    # creates the random UFO
    ufo = None
    if random.randrange(0, 100) <= 15:  # 15% chance of ufo
        ufo = Ufo(ai_settings, screen)
    time_stamp = pygame.time.get_ticks()
    return time_stamp, ufo
Пример #7
0
def check_events(ai_settings, screen, stats, sb, play_button, ship, aliens, bullets, alienbullets, explosions, ufos):
    # Respond to keypresses and mouse events
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()
        elif event.type == pygame.KEYDOWN:
            check_keydown_events(event, ai_settings, screen, ship, bullets)
        elif event.type == pygame.KEYUP:
            check_keyup_events(event, ship)
        elif event.type == pygame.MOUSEBUTTONDOWN:
            mouse_x, mouse_y = pygame.mouse.get_pos()
            check_play_button(ai_settings, screen, stats, sb, play_button,
                              ship, aliens, bullets, mouse_x, mouse_y, alienbullets, explosions, ufos)

    randufonum = random.randint(1, 5000)
    if randufonum == 5 and not ufos:
        ufo = Ufo(ai_settings, screen)
        ufos.add(ufo)

    randintnum = random.randint(1, ai_settings.alien_bullet_prob)
    if randintnum == 5:
        randaliennum = random.randint(0, len(aliens) - 1)
        i = 0
        for alien in aliens:
            if i == randaliennum:
                fire_alien_bullet(ai_settings, screen, alien, alienbullets)
            i = i + 1
def create_fleet(ai_settings, screen, ufoes):
    ufo = Ufo(ai_settings, screen)
    ufo_width = ufo.rect.width
    #available_space_x = ai_settings.screen_width - 2 * ufo_width
    #number_x = int(available_space_x / (2 * ufo_width))

    for row in range(3):
        for u in range(10):
            ufo = Ufo(ai_settings, screen)

            ufo.x = ufo_width + 2 * ufo_width * u

            ufo.rect.x = ufo.x
            ufo.rect.y = ufo.rect.height + 2 * ufo.rect.height * row

            ufoes.add(ufo)
Пример #9
0
def create_ufo(ai_settings, screen):
    ufo = None
    if random.randrange(0, 100) <= 50:
        ufo = Ufo(ai_settings, screen)

    time_stamp = pygame.time.get_ticks()
    return time_stamp, ufo
Пример #10
0
def create_random_ufo(ai_settings, screen):
    """With a chance of 10% create a Ufo and return it with the time it was created"""
    ufo = None
    if random.randrange(0, 100) <= 15:  # 15% chance of ufo
        ufo = Ufo(ai_settings, screen)
    time_stamp = pygame.time.get_ticks()
    return time_stamp, ufo
Пример #11
0
def main():
    pygame.init()

    background_image = pygame.image.load("imagenes/space.png")
    background_rect = background_image.get_rect()

    pygame.display.set_caption("asteroids")

    ship = Ship(size)
    ufos = []
    for i in range(0, 10):
        ufos.append(Ufo(size, i, 10))

    while 1:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                sys.exit()

        ship.update()
        screen.blit(background_image, background_rect)
        screen.blit(ship.image, ship.rect)

        for bullet in ship.bullets:
            bullet.update()
            if bullet.rect.top <= 0:
                ship.bullets.remove(bullet)
            screen.blit(bullet.image, bullet.rect)

        for ufo in ufos:
            ufo.update()
            screen.blit(ufo.image, ufo.rect)

        pygame.display.update()
        pygame.time.delay(10)
Пример #12
0
def create_random_ufo(ai_settings, screen):
    """Create a random ufo to go across the screen."""
    ufo = None
    time_stamp = None
    if random.randrange(0, 100) <= 10:  # 10% chance of ufo
        ufo = Ufo(ai_settings, screen)
        time_stamp = pygame.time.get_ticks()
    return time_stamp, ufo
Пример #13
0
 def create_ufos(self):
     """Create ufos at a random interval."""
     if len(self.ufos) < 1:
         self.sounds.ufo_sound.play(-1)
         ufo = Ufo(ai_settings=self.ai_settings,
                   screen=self.screen,
                   sprite_sheet=self.sprite_sheet)
         ufo.rect.x = 50
         ufo.rect.y = 60
         self.ufos.add(ufo)
Пример #14
0
 def creat_fleet_ufos(self):
     "Determine avaialable space for UFOs"
     ufo_example = Ufo(self)
     available_width = self.settings.screen_width
     available_ufos = (available_width // (ufo_example.rect.width * 2))
     available_height = self.settings.screen_height
     available_rows = (available_height // (ufo_example.rect.height * 2) //
                       2)
     """create ufos"""
     for row in range(1, available_rows):
         print(row)
         for ufo_number in range(1, available_ufos):
             self._create_ufo_row(ufo_number, row)
Пример #15
0
    def nextLevel(self):
        self._level += 1
        self._screen.flash()
        if (self._level == 2):
            self.bricks_pos = self.bricks_pos_l2
        elif (self._level == 3):
            threading.Thread(target=playsound,
                             args=('boss.wav', ),
                             daemon=True).start()
            self.bricks_pos = self.bricks_pos_l3
            pos = self._paddle.getPosition()
            size = self._paddle.getSize()
            self._isUfo = True
            self._ufo = Ufo(np.array([2, pos[1] + size[1] / 2]))
        else:
            time_temp = int(time.time() - self._start_time)
            self._screen.gameOver(win=True,
                                  score=(self._score +
                                         max(0, (1000 - time_temp) / 100)))
            quit()

        self._move = False
        self._len = self.bricks_pos.shape[0]
        self.powerup = []
        self._laser = False
        self.laserbeams = []
        self.createBricks()
        self._paddle = Paddle(
            np.array([config.HEIGHT - 3, config.WIDTH / 2 - 7]),
            np.array([1, 16]))
        self._ball = []
        self._ball.append(
            Ball(np.array([config.HEIGHT - 4, config.WIDTH / 2]),
                 np.array([-1, 0]), True))
        self._balls = 1
        self.lastMove = time.time()
Пример #16
0
def create_fleet(ai_settings, screen,ship, startreks):
	"""create a full fleet of startreks"""
	# create a startrek and find the number of startreks in a row
	# spacing between each startrek is equal to one ufo width
	startrek = Ufo(ai_settings, screen)
	number_startreks_x = get_number_startreks(ai_settings, startrek.rect.width )
	number_rows = get_number_rows(ai_settings, ship.rect.height, startrek.rect.height)



	# create the fleet of startreks
	for row_number in range(number_rows):
		for startrek_number in range(number_startreks_x):
		# create a startrek and place it in the row
			create_startrek(ai_settings, screen, startreks, startrek_number, row_number)
Пример #17
0
 def newLevel(self):
     self.blocks = generateLevel(self.level)
     self.thruFlag = 0
     self.grabFlag = 0
     self.paddle.reset()
     self.powerups.clear()
     self.balls.clear()
     self.makeBall()
     self.activePowerups.clear()
     self.gameState = 0
     self.shootFlag = 0
     self.bullets.clear()
     if self.level == 3:
         self.ufo = Ufo([0, self.paddle.y])
         self.ufoTimer = time.monotonic()
         self.ufoLives = 5
Пример #18
0
 def _create_fleet(self):
     """Create the fleet of UFO."""
     # Create an UFO and find the number of UFOs in a row.
     ufo = Ufo(self)
     ufo_width, ufo_height = ufo.rect.size
     rocket_width = self.rocket.rect.width
     available_space_x = (self.settings.screen_width - 
                             (3 * ufo_width) - rocket_width)
     number_ufo_x = available_space_x // (2 * ufo_width)
     # Determine the number of rows of UFOs that fit on the screen.
     available_space_y = self.settings.screen_height - (2 * ufo_height)
     number_rows = available_space_y // (2 * ufo_height)
     # Create the full fleet of UFOs.
     for row_number in range(number_rows):
         for ufo_number in range(number_ufo_x):
             self._create_ufo(ufo_number, row_number)
Пример #19
0
class LaserGame:
    def __init__(self):
        self.won_by_ufo = 0
        self.won_by_laser = 0

        self.reset()
    
    def reset(self):
        self.laser = Laser()
        self.ufo = Ufo()

        self.alpha = 0 #angle between laserbeam and ufo
        self.gamma = 0 #angle between center and left/right end of ufo circle
        self.hit = False
    
    def rotate_laser(self, clockwise):
        self.laser.rotate(clockwise)
    
    def fire_laser(self):
        self.laser.fire()
    
    def set_ufo_target(self, x, y):
        self.ufo.set_target_pos(x, y)

    def update(self):
        self.ufo.update()
        self.laser.update()
        self.__calculate_angles()
        self.hit = self.laser.fires and self.alpha <= self.gamma

        if (self.hit):
            self.ufo.receive_damage(self.laser.power)
        
        if(not self.ufo.alive):
            self.won_by_laser += 1
            self.reset()
        elif(self.ufo.jumped):
            self.won_by_ufo += 1
            self.reset()

    def __calculate_angles(self):
        lx = math.sin(self.laser.rotation)
        ly = -math.cos(self.laser.rotation)

        ltx = self.ufo.x - 0.5
        lty = self.ufo.y - 0.5

        dot = lx * ltx + ly * lty
        det = lx * lty - ly * ltx
        self.alpha = abs(math.atan2(det, dot))

        d = math.sqrt(ltx * ltx + lty * lty)
        self.gamma = math.asin(self.ufo.radius / d) if d > self.ufo.radius else 2 * math.pi
Пример #20
0
def create_ufo(game_settings, screen, ufos, ufo_number, ufo_row):
    ufo = Ufo(game_settings, screen)
    ufo.set_position(ufo_number, ufo_row)
    ufos.add(ufo)
Пример #21
0
class Game:
    """
    The actual game and rendering related functions
    """

    _refresh_time = 1 / FRAME_RATE

    # DECLARING EVERYTHING
    def __init__(self):
        coloroma_init(autoreset=False)
        self.__score = 0
        self.__last_level_score = 0
        self.__ticks = 0
        self.__level_ticks = 0
        self.__level = 1
        self.__lives_used = 0
        self.__paddle = Paddle()
        self.__bricks_broken = 0
        self.__balls = [Ball(paddle=self.__paddle)]
        self.__cnt_active_balls = 0
        self.__cnt_active_bricks = 100
        self.__game_status = GAME_END
        self.__powerups = []
        self.__kb = KBHit()
        self.__explode_ids = [x for x in range(8, 14)]
        self.__explode_nbrs_ids = [7, 14, 28, 29, 30, 31, 32, 33]
        self.__brick_structure_y_fall = 0
        self.__fall_bricks = 0
        self.__bullets = []
        self.__ufo = Ufo()
        self.__ufo_bombs = []
        self.__ufo_bricks = []
        self.__map_position_to_bricks = []

        clear_terminal_screen()
        self._draw_bricks()
        self._loop()

    # DRAW THE OBJECT IN GIVEN RANGE
    def _draw_obj(self, coord, obj):
        y1 = 0
        for y in range(coord[1], coord[1] + coord[3]):
            x1 = 0
            for x in range(coord[0], coord[0] + coord[2]):
                # (x, y) wrt frame (x1, y1) wrt obj
                if 0 <= x < FRAME_WIDTH and 0 <= y < FRAME_HEIGHT:
                    self.__frame[y][x] = obj[y1][x1]
                x1 += 1
            y1 += 1

    # TOP INFO BAR
    def _top_info_print(self):
        s = f"SCORE:{self.__score}       "[:13]
        s += f"LIVES REMAINING:{LIVES - self.__lives_used}       "[:24]
        s += f"TIME: {self.__level_ticks//10}       "[:14]
        s += f"LEVEL: {self.__level}        "
        if self.__paddle.check_have_bullet_powerup():
            # (self.__ticks - self.__paddle.get_powerup_start_time())//10 >= POWERUP_LIFE
            # (X - S) // 10 = POWERUP_LIFE
            # X = S + 10*POWERUP_LIFE
            # ANSWER = X - NOW.
            x = self.__paddle.get_powerup_start_time() + 10 * POWERUP_LIFE
            s += f"POWERUP TIME LEFT: {x - self.__ticks}        "

        if self.__level == UFO_LEVEL:
            s += f"UFO HEALTH: {self.__ufo.get_health()}        "
            s += f"Press q to quit."
        else:
            s += f"Press q to quit."
        self.__frame[1][2:2 + len(s)] = [
            Style.BRIGHT + Fore.WHITE + Back.LIGHTBLACK_EX + x for x in s
        ]

    # DRAW THE BRICK STRUCTURE
    def _draw_bricks(self):
        self.__bricks = []
        y = BRICK_STRUCTURE_Y

        if self.__level == UFO_LEVEL:
            y += 7

        dummy_row = [
            "X" for i in range(len(BRICK_STRUCTURE[self.__level - 1][0]) + 2)
        ]

        self.__map_position_to_bricks = [dummy_row]

        for i, row in enumerate(BRICK_STRUCTURE[self.__level - 1]):
            x = BRICK_STRUCTURE_X
            row_bricks = ["X"]
            for j, brick_type in enumerate(row):
                if brick_type == " ":
                    row_bricks.append("X")
                    x += BRICK_WIDTH
                    continue
                if int(brick_type) == WEAK_BRICK_ID:
                    self.__bricks.append(WeakBrick(x, y, i + 1, j + 1))
                elif int(brick_type) == NORMAL_BRICK_ID:
                    self.__bricks.append(NormalBrick(x, y, i + 1, j + 1))
                elif int(brick_type) == STRONG_BRICK_ID:
                    self.__bricks.append(StrongBrick(x, y, i + 1, j + 1))
                elif int(brick_type) == UNBREAKABLE_BRICK_ID:
                    self.__bricks.append(UnbreakableBrick(x, y, i + 1, j + 1))
                elif int(brick_type) == EXPLODING_BRICK_ID:
                    self.__bricks.append(ExplodingBrick(x, y, i + 1, j + 1))
                elif int(brick_type) == RAINBOW_BRICK_ID:
                    self.__bricks.append(RainbowBrick(x, y, i + 1, j + 1))

                row_bricks.append(self.__bricks[-1])
                x += BRICK_WIDTH

            row_bricks.append("X")
            self.__map_position_to_bricks.append(row_bricks)
            y += BRICK_HEIGHT

        self.__map_position_to_bricks.append(dummy_row)
        # print(len(self.__map_position_to_bricks), len(self.__map_position_to_bricks[0]), len(B))
        # input()

    # HOLD SCREEN. BETWEEN LIFE LOSTS
    def _draw_hold_screen(self, message=""):
        self.__frame = np.array([[
            Style.BRIGHT + Fore.WHITE + Back.LIGHTBLACK_EX + " "
            for _ in range(FRAME_WIDTH)
        ] for _ in range(FRAME_HEIGHT)])
        self._top_info_print()
        s = message + " Press ENTER to continue."
        self.__frame[FRAME_HEIGHT // 2][50:50 + len(s)] = [x for x in s]
        sra = str(Style.RESET_ALL)
        # get the grid string
        grid_str = "\n".join(
            [sra + " " * 4 + "".join(row) + sra for row in self.__frame])
        # displaying the grid
        os.write(1, str.encode(grid_str))

    # DRAW ONE FRAME
    def _draw(self):
        # drawing the grid
        self.__frame = np.array([[
            Style.BRIGHT + Fore.WHITE + Back.LIGHTBLACK_EX + " "
            for _ in range(FRAME_WIDTH)
        ] for _ in range(FRAME_HEIGHT)])
        self.__bricks_broken = 0

        # TOP INFO BAR
        self._top_info_print()

        # PADDLE
        self._draw_obj(self.__paddle.get_box(), self.__paddle.get_obj())

        # UFO
        if self.__level == UFO_LEVEL:
            if self.__ufo.check_active():
                self._draw_obj(self.__ufo.get_box(), self.__ufo.get_obj())

        # UFO BRICKS
        for ufo_brick in self.__ufo_bricks:
            if not ufo_brick.check_active():
                continue
            self._draw_obj(ufo_brick.get_box(), ufo_brick.get_obj())

        # BRICKS
        for brick in self.__bricks:
            if brick.check_active():
                self._draw_obj(brick.get_box(), brick.get_obj())
            else:
                self.__bricks_broken += 1

        #BULLETS
        for bullet in self.__bullets:
            if bullet.check_active():
                self._draw_obj(bullet.get_box(), bullet.get_obj())

        #BOMBS
        for bomb in self.__ufo_bombs:
            if bomb.check_active():
                self._draw_obj(bomb.get_box(), bomb.get_obj())

        # BALLS
        for ball in self.__balls:
            if ball.check_active():
                self._draw_obj(ball.get_box(), ball.get_obj())

        # POWERUPS
        for powerup in self.__powerups:
            if powerup.check_active():
                self._draw_obj(powerup.get_box(), powerup.get_obj())

        sra = str(Style.RESET_ALL)
        grid_str = "\n".join(
            [sra + " " * 4 + "".join(row) + sra for row in self.__frame])
        os.write(1, str.encode(grid_str))

    # TAKE INPUT FROM KBHIT
    def _get_input(self):
        c = ""
        if self.__kb.kbhit():
            c = self.__kb.getch()
        self.__kb.flush()
        return c

    # HANDLE THE INPUT TAKEN
    def _handle_input(self, key):
        key = key.lower()
        if key == 'q':
            self.Quit()
        if key in "ad":
            if self.__level == UFO_LEVEL:
                self.__paddle.handle_key_press(key, self.__ufo)
                for idx, brick in enumerate(self.__ufo_bricks):
                    brick.set_x(self.__ufo.get_x() + idx * BRICK_WIDTH)
            else:
                self.__paddle.handle_key_press(key)
        if key in " ad":
            for ball in self.__balls:
                ball.handle_key_press(self.__paddle, key)
        if key == 'l':
            self.change_level()

    # DIVIDE THE BALL INTO TWO
    def divide_ball(self, ball):
        new_ball = Ball()
        x, y = ball.get_position()
        vx, vy = ball.get_velocity()
        if vx != 0:
            new_ball.set_velocity(vx * -1, vy)
        else:
            new_ball.set_velocity(-1, vy)
        new_ball.set_position(x, y)
        new_ball.set_state(BALL_RELEASED)
        return new_ball

    # DIFFRENT COLLISIONS
    def _ball_and_wall(self):
        for ball in self.__balls:
            if ball.check_active():
                ball.check_wall_collission()

    def _ball_and_paddle(self):
        for ball in self.__balls:
            if ball.check_active():
                if ball.check_paddle_collission(
                        self.__paddle) and self.__fall_bricks:
                    self.__brick_structure_y_fall += 1
                    if self.__brick_structure_y_fall + BRICK_STRUCTURE_Y + len(
                            BRICK_STRUCTURE[self.__level -
                                            1]) * BRICK_HEIGHT == PADDLE_Y:
                        self.Quit()

    def _bomb_and_paddle(self):
        for bomb in self.__ufo_bombs:
            if bomb.check_active():
                if bomb.check_paddle_collission(self.__paddle):
                    self.__cnt_active_balls = 0

    def _ball_and_ufo(self):
        for ball in self.__balls:
            if ball.check_active():
                if ball.check_ufo_collission(self.__ufo):
                    self.Quit()

    def _powerup_and_paddle(self):
        for powerup in self.__powerups:
            if not powerup.check_active():
                continue
            if check_intersection(powerup, self.__paddle):
                if powerup.get_type() == POWERUP_EXPAND_PADDLE:
                    self.__paddle.change_width(INC_PADDLE_WIDTH)

                elif powerup.get_type() == POWERUP_SHRINK_PADDLE:
                    self.__paddle.change_width(-1 * SHRINK_PADDLE_WIDTH)

                elif powerup.get_type() == POWERUP_FAST_BALL:
                    for ball in self.__balls:
                        ball.inc_speed(2)

                elif powerup.get_type() == POWERUP_BALL_MULITIPLIER:
                    new_balls = []
                    for ball in self.__balls:
                        if ball.check_active():
                            new_balls.append(self.divide_ball(ball))
                    for new_ball in new_balls:
                        self.__balls.append(new_ball)

                elif powerup.get_type() == POWERUP_THRU_BALL:
                    for ball in self.__balls:
                        ball.set_type(THRU_BALL)
                elif powerup.get_type() == POWERUP_GRAB_BALL:
                    for ball in self.__balls:
                        ball.set_grabbable()
                elif powerup.get_type() == POWERUP_SHOOTING_BULLET:
                    self.__paddle.set_have_bullet_powerup(1)
                    self.__paddle.set_powerup_start_time(self.__ticks)
                elif powerup.get_type() == POWERUP_FIREBALL:
                    for ball in self.__balls:
                        ball.set_fire()
                else:
                    continue
                powerup.deactivate()

    def _update(self):

        # ball moved
        self.__cnt_active_balls = 0
        for ball in self.__balls:
            if ball.check_active():
                ball.update()
                self.__cnt_active_balls += 1

        # Powerup moved
        powerup_remove = []
        for id, powerup in enumerate(self.__powerups):
            if powerup.check_active():
                powerup.update()
            else:
                powerup_remove.append(id)
        for id in sorted(powerup_remove, reverse=True):
            del self.__powerups[id]

        # Bullet moved
        bullet_remove = []
        for id, bullet in enumerate(self.__bullets):
            if bullet.check_active():
                bullet.update()
            else:
                bullet_remove.append(id)
        for id in sorted(bullet_remove, reverse=True):
            del self.__bullets[id]

        # Bomb moved
        bomb_remove = []
        for id, bomb in enumerate(self.__ufo_bombs):
            if bomb.check_active():
                bomb.update()
            else:
                bomb_remove.append(id)
        for id in sorted(bomb_remove, reverse=True):
            del self.__ufo_bombs[id]

        # Bullet powerup done
        if self.__paddle.check_have_bullet_powerup(
        ) and (self.__ticks -
               self.__paddle.get_powerup_start_time()) // 10 >= POWERUP_LIFE:
            self.__paddle.set_have_bullet_powerup(0)

        # Generate Bullet
        if self.__paddle.check_have_bullet_powerup() and self.__ticks % 8 == 0:
            x, y = self.__paddle.get_position()
            self.__bullets.append(Bullet(x + PADDLE_WIDTH // 2, y, -1))

        # Generate Bomb
        if self.__level == UFO_LEVEL and self.__ufo.can_drop_bomb():
            u_x, u_y, u_width, u_height = self.__ufo.get_box()
            self.__ufo_bombs.append(Bomb(u_x + u_width // 2, u_y + u_height))

        # ball and wall collissins
        self._ball_and_wall()
        # ball and paddle collissions
        self._ball_and_paddle()
        # bomb and paddle
        if self.__level == UFO_LEVEL:
            self._bomb_and_paddle()
        # powerup and paddle collissions
        self._powerup_and_paddle()

        # ufo bricks and ball
        if self.__level == UFO_LEVEL:
            for brick in self.__ufo_bricks:
                if not brick.check_active():
                    continue
                for ball in self.__balls:
                    if not ball.check_active():
                        continue
                    is_destroyed = brick.handle_collission(ball)

        # ufo and ball
        if self.__level == UFO_LEVEL:
            got_critical = True
            if self.__ufo.check_critical():
                got_critical = False

            self._ball_and_ufo()

            if not self.__ufo.check_critical():
                got_critical = False

            if got_critical:
                u_x, u_y, u_width, u_height = self.__ufo.get_box()
                for i in range(UFO_WIDTH // BRICK_WIDTH):
                    b_x = u_x + i * BRICK_WIDTH
                    b_y = u_y + u_height
                    self.__ufo_bricks.append(WeakBrick(b_x, b_y))

        for powerup in self.__powerups:
            if powerup.check_active():
                powerup.check_wall_collission()

        for brick in self.__bricks:
            if brick.check_active():
                for bullet in self.__bullets:
                    if bullet.check_active():
                        vx, vy = bullet.get_velocity()
                        is_destroyed = brick.handle_collission_bullet(bullet)
                        if not is_destroyed:
                            continue
                        if is_destroyed and brick.id == EXPLODING_BRICK_ID:
                            os.system('aplay -q ./sounds/explosions.wav&')
                            for i in self.__explode_ids:
                                if self.__bricks[i].check_active():
                                    self.__bricks[i].destroy()
                            for i in self.__explode_nbrs_ids:
                                if self.__bricks[i].check_active():
                                    self.__bricks[i].destroy()
                        if is_destroyed and random.random(
                        ) > POWERUP_PROBABILITY:
                            # generate power_up
                            (x, y, _, _) = brick.get_box()
                            powerup_type = random.randint(0, 7)
                            self.__powerups.append(
                                PowerUp(x, y, vx, vy, powerup_type))

        self.__cnt_active_bricks = 0
        for brick in self.__bricks:
            if brick.check_active():
                if brick.get_type() != UNBREAKABLE_BRICK_ID:
                    self.__cnt_active_bricks += 1
                for ball in self.__balls:
                    if ball.check_active():
                        vx, vy = ball.get_velocity()
                        is_destroyed = brick.handle_collission(
                            ball, self.__map_position_to_bricks)
                        if is_destroyed and brick.id == EXPLODING_BRICK_ID:
                            for i in self.__explode_ids:
                                if self.__bricks[i].check_active():
                                    self.__bricks[i].destroy()
                            for i in self.__explode_nbrs_ids:
                                if self.__bricks[i].check_active():
                                    self.__bricks[i].destroy()
                        if is_destroyed and random.random(
                        ) > POWERUP_PROBABILITY:
                            # generate power_up
                            (x, y, _, _) = brick.get_box()
                            powerup_type = random.randint(0, 7)
                            # powerup_type = POWERUP_FIREBALL
                            self.__powerups.append(
                                PowerUp(x, y, vx, vy, powerup_type))

        for brick in self.__bricks:
            if brick.check_active():
                brick.set_y_fall(self.__brick_structure_y_fall)

        if (self.__level_ticks // 10) == LEVEL_TIME[self.__level - 1]:
            self.__fall_bricks = 1

    def _get_score(self):
        self.__score = max(
            0, 100 * self.__bricks_broken - (self.__ticks // 100) * 10)

        if self.__level == UFO_LEVEL:
            self.__score += (max(0, 1000 *
                                 (UFO_HEALTH - self.__ufo.get_health())))

        return self.__score + self.__last_level_score

    def refresh(self):
        self.__powerups = []
        self.__paddle.set_default()
        self.__balls = [Ball(paddle=self.__paddle)]
        self.__bullets = []

    def change_level(self):
        if self.__level == MAX_LEVEL:
            self.Quit()

        self.__level += 1

        while True:
            print("\033[0;0H")
            self._draw_hold_screen(f"Moving to level {self.__level}.")
            last_key_pressed = self._get_input().lower()
            if last_key_pressed == "\n":
                print("\033[0;0H")
                break
            elif last_key_pressed == "q":
                self.Quit()
                break

        if self.__level == UFO_LEVEL:
            os.system('aplay -q ./sounds/ufo.wav& 2>/dev/null')

        self._draw_bricks()
        self.__brick_structure_y_fall = 0
        self.__fall_bricks = 0
        self.__level_ticks = 0
        self.__last_level_score = self.__score
        self.refresh()

    # loop over frames
    def _loop(self):
        self.__game_status = GAME_START
        clear_terminal_screen()

        while self.__game_status == GAME_START:

            # 1. Clear Screen
            # 2. update positions and handle collisions
            # 3. update info
            # 4. draw
            # 5. handle input

            # clear screen and reposition cursor.
            print("\033[0;0H")

            self._update()

            if self.__cnt_active_bricks == 0 and self.__level != UFO_LEVEL:
                self.change_level()

            if self.__cnt_active_balls == 0:
                self.refresh()
                self.__lives_used += 1
                self.__game_status = GAME_HOLD
                while self.__game_status == GAME_HOLD:
                    print("\033[0;0H")
                    self._draw_hold_screen("Life lost. Game Paused.")
                    last_key_pressed = self._get_input().lower()
                    if last_key_pressed == "\n":
                        print("\033[0;0H")
                        self.__game_status = GAME_START
                    elif last_key_pressed == "q":
                        self.Quit()
                        break

            if LIVES - self.__lives_used == 0:
                self.Quit()
                break

            self._draw()
            last = time.time()

            last_key_pressed = self._get_input()
            self._handle_input(last_key_pressed)

            self.__score = self._get_score()
            self.__ticks += 1
            self.__level_ticks += 1

            while time.time() - last < self._refresh_time:
                pass

    def Quit(self):
        clear_terminal_screen()
        self.__game_status = GAME_END
        s = " " * 5
        s = "GAME OVER!\n"
        s += f"SCORE:{self.__score}\n"[:13]
        s += f"LIVES USED:{self.__lives_used}\n"[:24]
        s += f"TIME: {self.__ticks//10}\n"
        os.write(1, str.encode(s))
        os.system('setterm -cursor on')
        os._exit(0)
Пример #22
0
 def respawn(self):
     self.allUfo.add(Ufo(self))
def run_game():
    # Initialize pygame, settings, and screen object.
    pygame.init()
    ai_settings = Settings()
    screen = pygame.display.set_mode(
        (ai_settings.screen_width, ai_settings.screen_height))
    pygame.display.set_caption("Space Invaders")
    # Makes the Play button.
    play_button = Button(ai_settings, screen, "Play Game")
    # Makes the game title.
    titlefont = pygame.font.SysFont('Comic Sans MS', 70)
    game_title = titlefont.render('Alien Invasion', False, (255, 255, 255))
    # Makes the infosheet
    scoresheet = pygame.image.load('images/infosheet.png')
    # Make the High Scores button.
    high_scores_button = Button(ai_settings, screen, "High Scores")
    high_scores_button.make_high_scores_button("High Scores")
    stats = GameStats(ai_settings)
    sb = Scoreboard(ai_settings, screen, stats)
    # Make a ship
    ship = Ship(ai_settings, screen)
    bullets = Group()
    aliens = Group()
    albullets = Group()
    bunkers = Group()
    gf.create_bunkers(ai_settings, screen, bunkers)
    ufo = Ufo(ai_settings, screen)
    ufo.blitme()
    # Create the fleet of aliens.
    gf.create_fleet(ai_settings, screen, ship, aliens)
    # Load sounds
    ai_settings.change_sound = pygame.mixer.Sound("sounds/boop.wav")

    # Start the main loop for the game.
    while True:
        # Check for key presses or mouse clicks
        gf.check_events(ai_settings, screen, stats, sb, play_button,
                        high_scores_button, ship, aliens, bullets, bunkers)
        if stats.game_active:
            ticks = pygame.time.get_ticks()
            ai_settings.time = ticks
            if ai_settings.time >= 13000:
                ai_settings.change_sound = pygame.mixer.Sound(
                    "sounds/boop2.wav")
            if ai_settings.time >= 20000:
                ai_settings.change_sound = pygame.mixer.Sound(
                    "sounds/boop3.wav")
            # Move the ship left/right
            ship.update(ai_settings)
            # Move bullets and check for alien collisions
            gf.update_bullets(ai_settings, screen, stats, sb, ship, aliens,
                              bullets, albullets, ufo, bunkers)
            # Move the aliens and check for edge collisions
            gf.update_aliens(ai_settings, screen, stats, sb, ship, aliens,
                             bullets, bunkers)
            # Move the UFO across
            gf.update_ufo(ai_settings, screen, stats, sb, ship, aliens,
                          bullets, ufo)
            gf.drop_lead(ai_settings, screen, stats, sb, ship, aliens, bullets,
                         albullets, bunkers)
        gf.update_screen(ai_settings, screen, stats, sb, ship, aliens, bullets,
                         albullets, play_button, high_scores_button,
                         game_title, scoresheet, ufo, bunkers)
Пример #24
0
 def spawn_ufo(self):
     for i in range(1, Ufo(self).spawn_rate):
         ufo = Ufo(self)
         self.allUfo.add(ufo)
Пример #25
0
def run_game():
	# initialize game and create a screen object.
	pygame.init()
	# make an instance of the class Settings 
	ai_settings= Settings()
	screen = pygame.display.set_mode((ai_settings.screen_width,ai_settings.screen_height))
	pygame.display.set_caption("corona virus pandemic")
	# lets create an instance to stor game statistics and create a scoreboard
	stats = Gamestats(ai_settings)
	sb = Scoreboard(ai_settings, screen, stats)
	# make a ship
	ship = Ship(ai_settings, screen)
	# make a group to store the bullets in 
	# bullets an instance of the class Group. created outside the loop to avoid repetition
	bullets = Group()
	# make a group of ufos 
	startreks = Group()

	# create the fleet of startreks
	gf.create_fleet(ai_settings, screen, ship, startreks)
	# make an instance of a ufo
	startrek= Ufo(ai_settings, screen)
	# start the mainloop for the game.
	#  lets create an instance of gameover 
	gameover = Gameover(screen)
	# creatign an instance of the class button for the play button
	play_button = Button(ai_settings, screen, "Play", 0 , 0)

	# creating a restart button 
	restart_button = Button(ai_settings, screen, "Restart", 800, 0)

	# gameover button to be displayed when the player runs out ships
	gameover_button = Button(ai_settings, screen, "Gameover", 200, 0)

	class Backround(pygame.sprite.Sprite):
		"""a Background class for the background image of the game"""
		def __init__(self, image_file, location):
			# call the sprite initializer
			pygame.sprite.Sprite.__init__(self) 
			self.image = pygame.image.load(image_file)
			self.rect = self.image.get_rect()
			self.rect.left, self.rect.top = location

	background = Backround('images/background.bmp', [0,0])

	screen.fill([255, 255, 255])
	screen.blit(background.image, background.rect)

	# boolean for quiting the game and setting the while loop to true
	running = True
			
	while running:
		for event in pygame.event.get():
			if event.type == pygame.QUIT:
				running = False
			elif event.type == pygame.KEYDOWN:
				if event.key == pygame.K_ESCAPE:
					sys.exit()
				if event.key == pygame.K_RIGHT:
					ship.moving_right = True

				if event.key == pygame.K_LEFT:
					ship.moving_left = True
				if event.key == pygame.K_SPACE:
					gf.fire_bullet(ai_settings, screen, ship, bullets)
				if event.key == pygame.K_p and  K_BACKSPACE:
					gf.p_keyboardplay(ai_settings, screen, stats, ship, startreks, bullets)
				# if event.key== pygame.K_BACKSPACE:
				# 	sleep(2)
			elif event.type == pygame.KEYUP:
				if event.key == pygame.K_RIGHT:
					ship.moving_right = False

				if event.key == pygame.K_LEFT:
					ship.moving_left = False

			elif event.type == pygame.MOUSEBUTTONDOWN:
				mouse_x, mouse_y = pygame.mouse.get_pos()
				gf.check_play_button(ai_settings, screen, stats,sb,  play_button,ship, startreks, bullets, mouse_x, mouse_y)
				gf.check_restart_button(ai_settings, screen, stats, restart_button, ship, startreks, bullets, mouse_x, mouse_y)

		# keyboard and mouse events
		# gf.check_events(ai_settings ,screen,ship, bullets)
		if stats.game_active:
			ship.update()
			gf.update_bullets(ai_settings, screen, stats, sb, ship, startreks, bullets)
			gf.update_startreks(ai_settings,stats, screen, ship, startreks, bullets)

		gf.update_screen(ai_settings,screen,stats,sb ,ship, startreks, bullets, play_button, restart_button, gameover_button)
Пример #26
0
class Game:
    def start(self):
        if config.HEIGHT < 38 or config.WIDTH < 168:
            print("Please play on full screen")
            quit()
        print("\033[?25l\033[2J", end='')
        self._screen = Screen()
        self._paddle = Paddle(
            np.array([config.HEIGHT - 3, config.WIDTH / 2 - 7]),
            np.array([1, 16]))
        self._ball = []
        self._ball.append(
            Ball(np.array([config.HEIGHT - 4, config.WIDTH / 2]),
                 np.array([-1, 0]), True))
        self._lives = 5
        self._balls = 1
        self._score = 0
        self._level = 1
        self._start_time = time.time()
        self._printscore = 0
        self._move = False
        self._laser = False
        self._lasertime = self._start_time
        self._ufo = None
        self._isUfo = False
        get = Get()
        self.bricks_pos_l2 = np.array([
            [18, 66, 2, 2, 0],
            [18, 75, 3, 1, 1],
            [18, 84, 1, 3, 2],
            [16, 70, 2, 4, 3],
            [16, 79, 2, 5, 4],
            [16, 88, 3, 6, 5],
            [16, 61, 3, 2, 6],
            [14, 75, -1, 0, 0],
            [14, 84, -1, 0, 0],
            [14, 66, -1, 0, 0],
            [14, 93, -1, 0, 0],
            [14, 57, -1, 0, 0],
            [14, 48, -1, 0, 0],
            [14, 102, -1, 0, 0],
            [12, 79, 1, 1, 7],
            [12, 70, 1, 3, 8],
            [12, 88, 0, 2, 9],
            [12, 61, 0, 6, 10],
            [10, 75, 1, 4, 11],
            [10, 66, 2, 5, 12],
            [10, 84, 3, 6, 13],
        ])
        self.bricks_pos_l1 = np.array([
            [8, 14, 0, 0, 0],
            [8, 23, 1, 1, 0],
            [8, 32, 0, 0, 0],
            [6, 23, 2, 4, 1],
            [4, 14, 0, 0, 0],
            [4, 23, 1, 2, 2],
            [4, 32, 0, 0, 0],
            [8, 127, 0, 0, 0],
            [8, 136, 1, 3, 3],
            [8, 145, 0, 0, 0],
            [6, 136, 2, 5, 4],
            [4, 127, 0, 0, 0],
            [4, 136, 1, 6, 5],
            [4, 145, 0, 0, 0],
            [14, 75, 4, 7, 6],
            [14, 84, 4, 8, 7],
            [12, 75, 4, 0, 0],
            [12, 84, 4, 0, 0],
            [10, 75, 4, 0, 0],
            [10, 84, 4, 0, 0],
        ])
        self.bricks_pos_l3 = np.array([[15, 5, 0, 0, 0], [15, 150, 0, 0, 0]])
        self.ufo_layer1 = np.array([[15, 5, 0, 0, 0], [15, 150, 0, 0, 0],
                                    [10, 3, 1, 0, 0], [10, 12, 2, 0, 0],
                                    [10, 21, 3, 0, 0], [10, 30, 2, 0, 0],
                                    [10, 39, 1, 0, 0], [10, 48, 2, 0, 0],
                                    [10, 57, 3, 0, 0], [10, 66, 2, 0, 0],
                                    [10, 75, 1, 0, 0], [10, 84, 2, 0, 0],
                                    [10, 93, 3, 0, 0], [10, 102, 2, 0, 0],
                                    [10, 111, 1, 0, 0], [10, 120, 2, 0, 0],
                                    [10, 129, 3, 0, 0], [10, 138, 2, 0, 0],
                                    [10, 147, 1, 0, 0], [10, 156, 2, 0, 0]])
        self.ufo_layer2 = np.array([[15, 5, 0, 0, 0], [15, 150, 0, 0, 0],
                                    [10, 3, 1, 0, 0], [10, 12, 2, 0, 0],
                                    [10, 21, 3, 0, 0], [10, 30, 2, 0, 0],
                                    [10, 39, 1, 0, 0], [10, 48, 2, 0, 0],
                                    [10, 57, 3, 0, 0], [10, 66, 2, 0, 0],
                                    [10, 75, 1, 0, 0], [10, 84, 2, 0, 0],
                                    [10, 93, 3, 0, 0], [10, 102, 2, 0, 0],
                                    [10, 111, 1, 0, 0], [10, 120, 2, 0, 0],
                                    [10, 129, 3, 0, 0], [10, 138, 2, 0, 0],
                                    [10, 147, 1, 0, 0], [10, 156, 2, 0, 0],
                                    [13, 3, 1, 0, 0], [13, 12, 2, 0, 0],
                                    [13, 21, 3, 0, 0], [13, 30, 2, 0, 0],
                                    [13, 39, 1, 0, 0], [13, 48, 2, 0, 0],
                                    [13, 57, 3, 0, 0], [13, 66, 2, 0, 0],
                                    [13, 75, 1, 0, 0], [13, 84, 2, 0, 0],
                                    [13, 93, 3, 0, 0], [13, 102, 2, 0, 0],
                                    [13, 111, 1, 0, 0], [13, 120, 2, 0, 0],
                                    [13, 129, 3, 0, 0], [13, 138, 2, 0, 0],
                                    [13, 147, 1, 0, 0], [13, 156, 2, 0, 0]])
        self.bricks_pos = self.bricks_pos_l1
        self.powerup = []
        self._len = self.bricks_pos.shape[0]
        self.createBricks()
        self.laserbeams = []
        self.lastlaser = self._start_time
        self.bombtime = self._start_time
        self._bombs = []
        self._spawn1 = False
        self._spawn2 = False

        self.lastMove = self._start_time
        while True:
            self._screen.clear()
            self._screen.drawBackGround()
            inchar = input_to(get.__call__)
            self.handleInput(inchar)
            self.createLaser()
            self.moveBalls()
            self._screen.drawObject(self._paddle)
            self.spawnBricks()
            self.drawBricks()
            self.handleCollisionBallPaddle()
            self.handleCollisionBallBrick()
            self.drawUfo()
            self.drawBalls()
            self._screen.printScreen()
            time_temp = int(time.time() - self._start_time)
            self._printscore = int(self._score +
                                   max(0, (1000 - time_temp) / 100))
            print("\r Lives ", self._lives, "   Score ", self._printscore,
                  "   Time ", time_temp, "   Level ", self._level, "    ")
            if (self._laser):
                print("Remaining Time ", -int(time.time() - self._lasertime))
            elif self._isUfo:
                print("Boss Strenth: ", end="")
                strength = self._ufo.getStrength()
                for i in range(0, strength):
                    print('o', end="")
                for i in range(strength, 20):
                    print(' ', end="")
                print()
            else:
                for i in range(0, 30):
                    print(' ', end="")
                print()

    def drawUfo(self):
        if self._isUfo and self.bombtime + 5 < time.time():
            pos = self._ufo.getPosition()
            size = self._ufo.getSize()
            temp = Bomb(np.array([pos[0] + size[0], pos[1] + size[1] / 2]))
            self._bombs.append(temp)
            self.bombtime = time.time()
            threading.Thread(target=playsound,
                             args=('laser.wav', ),
                             daemon=True).start()

        if self._isUfo:
            if self._ufo.isVisible:
                self._screen.drawObject(self._ufo)

            for i in self._bombs:
                if i.isVisible():
                    self._screen.drawObject(i)

    def spawnBricks(self):
        if self._isUfo:
            if self._ufo.getStrength() <= 10 and self._spawn1 is False:
                self._spawn1 = True
                self.bricks_pos = self.ufo_layer1

                for j in range(self._len, len(self.ufo_layer1)):
                    i = self.ufo_layer1[j]
                    temp = Breakable(np.array([i[0], i[1]]), i[2])
                    self._brick.append(temp)
                self._len = len(self._brick)

            if self._ufo.getStrength() <= 5 and self._spawn2 is False:
                self._spawn2 = True
                self.bricks_pos = self.ufo_layer2

                for j in range(self._len, len(self.ufo_layer2)):
                    i = self.ufo_layer2[j]
                    temp = Breakable(np.array([i[0], i[1]]), i[2])
                    self._brick.append(temp)
                self._len = len(self._brick)

    def removeUfo(self):
        self._isUfo = False

    def createLaser(self):
        if (self.lastlaser + 1 < time.time() and self._laser):
            threading.Thread(target=playsound,
                             args=('laser.wav', ),
                             daemon=True).start()
            pos = self._paddle.getPosition()
            size = self._paddle.getSize()
            temp = Laser(np.array([pos[0], pos[1] + 1]))
            self.laserbeams.append(temp)
            temp = Laser(np.array([pos[0], pos[1] + size[1] - 1]))
            self.laserbeams.append(temp)
            self.lastlaser = time.time()

    def decreaseLives(self):
        threading.Thread(target=playsound, args=('life.wav', ),
                         daemon=True).start()
        self._lives = self._lives - 1
        self._screen.flash()
        if self._lives == 0:
            self._screen.gameOver(win=False, score=0)
            quit()
        for i in self.powerup:
            if i.isActivated():
                p = i.getType()
                if p == 'F' or p == 'B' or p == 'T':
                    i.deactivate(self._ball)
                elif p == 'L' or p == 'S' or p == 'M':
                    i.deactivate(self)
                elif p == '|':
                    i.deactivate(self._paddle, self)

        self._balls = 1
        x, y = self._paddle.getPosition()
        _, w = self._paddle.getSize()
        self._ball = []
        self._ball.append(
            Ball(np.array([x - 1, y + w / 2]), np.array([-1, 0]), True))

    def moveBalls(self):
        for i in self._ball:
            if i.move():
                self._ball.remove(i)
                self._balls = self._balls - 1

        if self._balls == 0:
            self.decreaseLives()

        for i in self.laserbeams:
            if i.isVisible():
                i.move()

        for i in self._bombs:
            if i.isVisible():
                i.move()

    def moveBricks(self):
        for i in self._brick:
            if (i.moveDown()):
                self._screen.flash()
                self._screen.gameOver(win=False, score=0)
                quit()

        for i in self.powerup:
            i.moveDown()

    def drawBalls(self):
        if (self.lastMove + 100 <= time.time() and not self._move):
            self._move = True
        for i in self._ball:
            self._screen.drawObject(i)
        for i in self.laserbeams:
            if i._isVisible:
                self._screen.drawObject(i)

    def createBricks(self):
        self._brick = []
        for i in self.bricks_pos:
            if (i[2] == 0):
                temp = Brick(np.array([i[0], i[1]]))

            elif i[2] == -1:
                temp = ExplodingBrick(np.array([i[0], i[1]]))

            elif i[2] == 4:
                temp = RainbowBrick(np.array([i[0], i[1]]))

            else:
                temp = Breakable(np.array([i[0], i[1]]), i[2])

            self._brick.append(temp)

            if (i[3] != 0):
                if (i[3] == 1):
                    temp1 = FastBall(np.array([i[0], i[1]]))
                elif (i[3] == 2):
                    temp1 = LongPaddlePowerup(np.array([i[0], i[1]]))
                elif (i[3] == 3):
                    temp1 = ShortPaddlePowerup(np.array([i[0], i[1]]))
                elif (i[3] == 4):
                    temp1 = StickBall(np.array([i[0], i[1]]))
                elif (i[3] == 5):
                    temp1 = ThruBall(np.array([i[0], i[1]]))
                elif (i[3] == 6):
                    temp1 = MultiplyBall(np.array([i[0], i[1]]))
                elif (i[3] == 7):
                    temp1 = ShootLaser(np.array([i[0], i[1]]))
                elif (i[3] == 8):
                    temp1 = FireBall(np.array([i[0], i[1]]))

                self.powerup.append(temp1)

    def nextLevel(self):
        self._level += 1
        self._screen.flash()
        if (self._level == 2):
            self.bricks_pos = self.bricks_pos_l2
        elif (self._level == 3):
            threading.Thread(target=playsound,
                             args=('boss.wav', ),
                             daemon=True).start()
            self.bricks_pos = self.bricks_pos_l3
            pos = self._paddle.getPosition()
            size = self._paddle.getSize()
            self._isUfo = True
            self._ufo = Ufo(np.array([2, pos[1] + size[1] / 2]))
        else:
            time_temp = int(time.time() - self._start_time)
            self._screen.gameOver(win=True,
                                  score=(self._score +
                                         max(0, (1000 - time_temp) / 100)))
            quit()

        self._move = False
        self._len = self.bricks_pos.shape[0]
        self.powerup = []
        self._laser = False
        self.laserbeams = []
        self.createBricks()
        self._paddle = Paddle(
            np.array([config.HEIGHT - 3, config.WIDTH / 2 - 7]),
            np.array([1, 16]))
        self._ball = []
        self._ball.append(
            Ball(np.array([config.HEIGHT - 4, config.WIDTH / 2]),
                 np.array([-1, 0]), True))
        self._balls = 1
        self.lastMove = time.time()

    def drawBricks(self):

        levelDone = True
        for i in self._brick:
            if i.isRainbow():
                i.changeStrength()
            if i.isVisible():
                self._screen.drawObject(i)
                if i.getType() != 0:
                    levelDone = False

        if self._isUfo and self._ufo.isVisible():
            levelDone = False

        if levelDone == True:
            self.nextLevel()

        for i in self.powerup:
            if i.isVisible():
                i.move(self._paddle)
                p = i.getType()
                if p == 'F' or p == 'B' or p == 'T' or p == '!':
                    i.activate(self._ball)
                    i.setTime(time.time() + 50)
                elif p == 'L' or p == 'S':
                    i.activate(self)
                    i.setTime(time.time() + 50)
                elif p == 'M':
                    i.activate(self, len(self._ball))
                    i.setTime(time.time() + 50)
                elif p == '|':
                    i.activate(self._paddle, self)
                    self._lasertime = time.time() + 50
                    i.setTime(self._lasertime)

                self._screen.drawObject(i)
            if i.isActivated() and i.getTime() < time.time():
                p = i.getType()
                if p == 'F' or p == 'B' or p == 'T' or p == '!':
                    i.deactivate(self._ball)
                elif p == 'L' or p == 'S' or p == 'M':
                    i.deactivate(self)
                elif p == '|':
                    i.deactivate(self._paddle, self)

    def changeLaserStatus(self, val):
        self._laser = val
        if val == False:
            if self._lasertime < time.time():
                self._laser = True

    def changeLongPaddle(self):
        x, y = self._paddle.getPosition()
        _, w = self._paddle.getSize()

        self._paddle = Paddle(np.array([x, y]), np.array([1, w + 3]),
                              self._paddle.isShoots())

    def changeShortPaddle(self):
        x, y = self._paddle.getPosition()
        _, w = self._paddle.getSize()

        if (w > 8):
            self._paddle = Paddle(np.array([x, y]), np.array([1, w - 3]),
                                  self._paddle.isShoots())

    def multiplyBalls(self):
        length = len(self._ball)
        for j in range(length):
            i = self._ball[j]
            vx, vy = i.getVelocity()
            x, y = i.getPosition()
            self._balls += 1
            self._ball.append(
                Ball(np.array([x, y]), np.array([-vx, -vy]), False))

    def decreaseBalls(self, balls):
        length = len(self._ball)
        if length > balls:
            while (balls > 0):
                self._ball.pop()
                balls = balls - 1
                self._balls = self._balls - 1

    def incrementScore(self, val):
        self._score = self._score + val

    def handleCollisionBallBrick(self):

        for ball in self._ball:
            for j in range(self._len):
                i = self._brick[j]
                if i.isVisible():
                    if i.collideBall(ball,
                                     self) and self.bricks_pos[j][3] != 0:
                        ball_vel = ball.getVelocity()
                        self.powerup[self.bricks_pos[j][4]].release(
                            np.array([ball_vel[0], ball_vel[1]],
                                     dtype='float'))

        for beam in self.laserbeams:
            for j in range(self._len):
                i = self._brick[j]

                if i.isVisible() and beam.isVisible():
                    if i.collideBall(beam,
                                     self) and self.bricks_pos[j][3] != 0:
                        self.powerup[self.bricks_pos[j][4]].release(
                            np.array([1, 0], dtype='float'))

        if self._isUfo:
            self._ufo.collideBall(ball, self)

    def explodeBricks(self, pos, size):
        threading.Thread(target=playsound,
                         args=('explosion.wav', ),
                         daemon=True).start()
        for j in range(self._len):
            i = self._brick[j]
            if i.isVisible():
                x2, y2 = i.getPosition()

                if ((x2 == pos[0] or x2 == pos[0] + size[0] - 1
                     or x2 + size[0] - 1 == pos[0]) and
                    (pos[1] <= y2 <= pos[1] + size[1]
                     or pos[1] <= y2 + size[1] - 1 <= pos[1] + size[1])) or (
                         (y2 == pos[1] or y2 == pos[1] + size[1] - 1
                          or y2 + size[1] - 1 == pos[1]) and
                         (pos[0] <= x2 <= pos[0] + size[0]
                          or pos[0] <= x2 + size[0] - 1 <= pos[0] + size[0])):
                    i.explodeBrick(self)
                    if self.bricks_pos[j][3] != 0:
                        self.powerup[self.bricks_pos[j][4]].release(
                            np.array([1, 1], dtype='float'))

    def handleCollisionBallPaddle(self):

        collide = False

        for i in self._ball:
            x1, y1 = i.getPosition()
            x2, y2 = self._paddle.getPosition()
            _, w = self._paddle.getSize()

            if x1 == x2 - 1 and y2 <= y1 <= y2 + w:
                speed = y1 - y2 - w / 2
                if not i.isStuckPaddle():
                    collide = True
                    threading.Thread(target=playsound,
                                     args=('ball.wav', ),
                                     daemon=True).start()

                i.collidePaddle(speed / 2)

        for i in self._bombs:
            if i.isVisible():
                x1, y1 = i.getPosition()
                x2, y2 = self._paddle.getPosition()
                _, w = self._paddle.getSize()

                if x1 == x2 and y2 <= y1 <= y2 + w:
                    i.makeInvisible()
                    self.decreaseLives()

        if (collide and self._move):
            self.moveBricks()

    def handleInput(self, ch):
        if ch == 'q':
            raise SystemExit
        if ch == 's':
            for i in self._ball:
                i.release()
        if ch == 'l':
            self.nextLevel()
        self._paddle.move(ch, self._ball)
        if self._isUfo:
            pos = self._paddle.getPosition()
            size = self._paddle.getSize()
            self._ufo.setPosition(np.array([2, pos[1] + (size[1] / 2)]))
Пример #27
0
def get_num_ufo_rows(game_settings, screen, ship):
    ufo = Ufo(game_settings, screen)
    ufo_height = ufo.get_size()[1]
    available_space_y = (game_settings.get_screen_size()[1] - (3 * ufo_height) - ship.get_size()[1])
    return int(available_space_y / (2 * ufo_height))
Пример #28
0
 def _create_ufo_row(self, ufo_number, row):
     new_ufo = Ufo(self)
     new_ufo.rect.x = new_ufo.rect.x * (ufo_number * 2)
     new_ufo.rect.y = new_ufo.rect.y * (row * 2)
     self.ufos.add(new_ufo)
Пример #29
0
def get_num_ufo_x(game_settings, screen):
    ufo = Ufo(game_settings, screen)
    ufo_width = ufo.get_size()[0]
    availible_space_x = game_settings.get_screen_size()[0] - 2 * ufo_width
    return  int(availible_space_x /(2 * ufo_width))
Пример #30
0
def run_game():
    # Initialize pygame, settings, and create a screen object
    pygame.init()
    ai_settings = Settings()
    screen = pygame.display.set_mode(
        (ai_settings.screen_width, ai_settings.screen_height))
    pygame.display.set_caption("Space Potaters")

    # Make buttons
    play_button = Button(ai_settings, screen, 'play')
    high_score_button = Button(ai_settings, screen, 'hs')
    back_button = Button(ai_settings, screen, 'back')

    # Create background
    background = Background(ai_settings, screen)

    # Create instance to store game states and create scoreboard
    stats = GameStats(ai_settings)
    sb = Scoreboard(ai_settings, screen, stats)

    #  Make a ship.
    ship = Ship(ai_settings, screen)

    # Make group to store bullets
    bullets = Group()
    # Make alien group
    aliens = Group()
    # Made group to store alien bullets
    a_bullets = Group()

    # Create alien fleet
    gf.create_fleet(ai_settings, screen, ship, aliens)

    # Create timer
    timer = Timer(ai_settings)

    # create ufo
    ufo = Ufo(ai_settings, screen)

    # Create explosion group
    kabooms = Group()

    # Make a bunker
    bunker = Group()

    background.blitme()

    # start main game loop
    while True:
        gf.check_events(ai_settings, screen, stats, sb, play_button, ship,
                        aliens, bullets, a_bullets, background, bunker,
                        high_score_button, back_button)

        if stats.game_active:
            timer.update()
            ship.update()
            gf.update_bullets(ai_settings, screen, stats, sb, ship, aliens,
                              bullets, a_bullets, bunker, kabooms, ufo)
            gf.update_aliens(ai_settings, screen, stats, sb, ship, aliens,
                             bullets, a_bullets, bunker, timer)
            gf.update_a_bullets(ai_settings, screen, stats, sb, ship, aliens,
                                bullets, a_bullets, bunker, timer)

        gf.update_screen(ai_settings, screen, stats, sb, ship, aliens, bullets,
                         a_bullets, play_button, timer, bunker, background,
                         high_score_button, back_button, kabooms, ufo)