Esempio n. 1
0
class Rainball(Image):

    element = StringProperty()
    name = StringProperty()
    deployed = BooleanProperty(False)

    def __init__(self, **kw):
        self.source='img/rainball.png'
        self.speed = 10
        self.angle = 0
        self.rotation = 1
        self.target = None
        self.hitbox = self.size[0] * .5
        self.img_element = Image(
            source='img/blank.png',
            size=(self.width/2.,self.height/2.))
        self.bullets = Bullets(size=self.size)
        super(Rainball, self).__init__(**kw)
        self.add_widget(self.img_element)

    def on_size(self, *args):
        self.bullets.size = self.width * 2, self.height * 2

    def on_element(self, *args):
        self.img_element.source = 'img/%s.png' % self.element
        self.img_element.source = 'img/%s.png' % self.element
        if self.name == 'maxi':
            self.img_element.color = dark_colors[self.element]
            self.color = light_colors[self.element]
        else:
            self.img_element.color = light_colors[self.element]
            self.color = dark_colors[self.element]

    def on_deployed(self, *args):
        if self.deployed:
            self.hitbox = self.bullets.width / 2.
            if not self.bullets in self.children:
                self.add_widget(self.bullets)
        else:
            self.hitbox = self.width / 2.
            if self.bullets in self.children:
                self.remove_widget(self.bullets)

    def move(self):
        if self.target:
            if self.element != 'lightning':
                dx = self.center_x - self.target[0]
                dy = self.center_y - self.target[1]
                da = math.atan2(dy, dx)
                self.x += math.cos(da) * - self.speed
                self.y += math.sin(da) * - self.speed
                if math.sqrt(dx**2 + dy**2) < 10:
                    self.center = self.target
                    self.target = None
            else:
                self.center = self.target
                self.target = None
            self.img_element.center = self.center
        self.bullets.center = self.center
        self.bullets.move()
Esempio n. 2
0
class BulletsTestCase(unittest.TestCase):
    """ Tests the wrapper of sprite group of bullets """
    def setUp(self):
        self.bullets = Bullets()

    def test_initialization(self):
        self.assertIsNotNone(self.bullets.get_bullets())
        self.assertEqual(len(self.bullets.get_bullets()), 0)

    def test_maximum_threshold(self):
        for i in range(11):
            x = random.randint(0, 200)
            y = random.randint(0, 200)

            self.bullets.add(Bullet(x, y))

        self.assertEqual(len(self.bullets.get_bullets()), 10)

    def test_out_of_screen_bullet(self):
        bullets = Bullets()
        bullet_out_of_screen = Bullet(400, -1)

        bullets.add(bullet_out_of_screen)

        bullets.update()

        self.assertEqual(len(bullets.get_bullets()), 0)
Esempio n. 3
0
class Rainball(Image):

    element = StringProperty()
    name = StringProperty()
    deployed = BooleanProperty(False)

    def __init__(self, **kw):
        self.source = 'img/rainball.png'
        self.speed = 10
        self.angle = 0
        self.rotation = 1
        self.target = None
        self.hitbox = self.size[0] * .5
        self.img_element = Image(source='img/blank.png',
                                 size=(self.width / 2., self.height / 2.))
        self.bullets = Bullets(size=self.size)
        super(Rainball, self).__init__(**kw)
        self.add_widget(self.img_element)

    def on_size(self, *args):
        self.bullets.size = self.width * 2, self.height * 2

    def on_element(self, *args):
        self.img_element.source = 'img/%s.png' % self.element
        self.img_element.source = 'img/%s.png' % self.element
        if self.name == 'maxi':
            self.img_element.color = dark_colors[self.element]
            self.color = light_colors[self.element]
        else:
            self.img_element.color = light_colors[self.element]
            self.color = dark_colors[self.element]

    def on_deployed(self, *args):
        if self.deployed:
            self.hitbox = self.bullets.width / 2.
            if not self.bullets in self.children:
                self.add_widget(self.bullets)
        else:
            self.hitbox = self.width / 2.
            if self.bullets in self.children:
                self.remove_widget(self.bullets)

    def move(self):
        if self.target:
            if self.element != 'lightning':
                dx = self.center_x - self.target[0]
                dy = self.center_y - self.target[1]
                da = math.atan2(dy, dx)
                self.x += math.cos(da) * -self.speed
                self.y += math.sin(da) * -self.speed
                if math.sqrt(dx**2 + dy**2) < 10:
                    self.center = self.target
                    self.target = None
            else:
                self.center = self.target
                self.target = None
            self.img_element.center = self.center
        self.bullets.center = self.center
        self.bullets.move()
def update_bullets(Bullets,aliens,game_s,score,setting,h_score):
    Bullets.update()
    collisions = pygame.sprite.groupcollide(Bullets, aliens, True, True)
    if collisions:
        ship_alien_collied(game_s,score,setting,collisions,h_score)
    for bullete in Bullets.copy():
        #DO NOT use "==" becos bullet jump from if 2 to -2 it never == so
        #use >= or <=
        if bullete.rect.bottom <=0:
            print("bullet removes")
            Bullets.remove(bullete)
Esempio n. 5
0
 def __init__(self, **kw):
     self.source = 'img/rainball.png'
     self.speed = 10
     self.angle = 0
     self.rotation = 1
     self.target = None
     self.hitbox = self.size[0] * .5
     self.img_element = Image(source='img/blank.png',
                              size=(self.width / 2., self.height / 2.))
     self.bullets = Bullets(size=self.size)
     super(Rainball, self).__init__(**kw)
     self.add_widget(self.img_element)
Esempio n. 6
0
 def _create_bullet(self):
     if self.stats.game_status:
         self.sounds.shoot_sound.play()
         num_bullet = self.settings.number_bullets
         new_bullet = Bullets(self, num_bullet)
         self.bullets.add(new_bullet)
         self.settings.number_bullets += 1
Esempio n. 7
0
def update_bullet(ai_settings, stats, screen, people, alien, bullets):
    # 更新外星飞船发射子弹
    new_bullet = Bullets(ai_settings, screen, alien)
    bullets.add(new_bullet)
    for bullet in bullets.copy():
        if bullet.rect.bottom >= ai_settings.screen_height:
            bullets.remove(bullet)
    check_bullet_people_collision(stats, people, alien, bullets)
Esempio n. 8
0
    def test_out_of_screen_bullet(self):
        bullets = Bullets()
        bullet_out_of_screen = Bullet(400, -1)

        bullets.add(bullet_out_of_screen)

        bullets.update()

        self.assertEqual(len(bullets.get_bullets()), 0)
Esempio n. 9
0
def bullets_update(bullets, enemies, nlo_settings, screen, korabl, sfera):
    """обновление пуль вражеского корабля, контроль их количества"""
    if nlo_settings.enemies_view == True:
        bullets.update()
        if len(bullets) < nlo_settings.bullets_screen_number:
            new_bullet = Bullets(nlo_settings, screen, enemies)
            bullets.add(new_bullet)
        for bullet in bullets.copy():
            if bullet.rect.bottom >= nlo_settings.screen_height or bullet.rect.colliderect(
                    sfera.rect):
                bullets.remove(bullet)
Esempio n. 10
0
def run_game():
    pg.init()

    screen = pg.set_display_dimensions(settings.screen_dim)
    pg.set_caption(settings.caption)
    screen_rect = screen.get_rect()

    # Make a ship
    img = pg.load_img('img/ship.bmp')
    ship = Ship(screen_rect.centerx, screen_rect.bottom, img)

    bullets = Bullets()

    while True:
        pg.watch_user_events(ship, bullets)

        screen.fill(settings.background_color)

        ship.update(screen_rect)
        bullets.update()

        ship.draw(screen)
        bullets.draw(screen)

        pg.flip()
Esempio n. 11
0
 def __init__(self, **kw):
     self.source='img/rainball.png'
     self.speed = 10
     self.angle = 0
     self.rotation = 1
     self.target = None
     self.hitbox = self.size[0] * .5
     self.img_element = Image(
         source='img/blank.png',
         size=(self.width/2.,self.height/2.))
     self.bullets = Bullets(size=self.size)
     super(Rainball, self).__init__(**kw)
     self.add_widget(self.img_element)
Esempio n. 12
0
    def __init__(self, mode='normal'):
        self.mode = mode

        self.alien_field = AlienField(self)
        self.player = Player(self)
        self.bullets = Bullets()
        self.barriers = Barriers()

        self._updatables = (self.alien_field,
                            self.player,
                            self.bullets)
        self._collidables = (self.alien_field, self.barriers, self.player)

        self.last_updated = time.time()
Esempio n. 13
0
def create_bullets(tower_group, enemy_group, path):
    for tower in tower_group:
        if tower.active:
            tower.counter += DT
            tower.in_range = []
            if tower.counter >= tower.wait_time:
                # Check for enemies in bounding box
                r = pg.Rect(0, 0, tower.range*TILE_SIZE*2, tower.range*TILE_SIZE*2)
                r.center = tower.rect.center
                for enemy in enemy_group:
                    if r.collidepoint(enemy.rect.centerx, enemy.rect.centery):
                        # Check if enemy is inside range
                        p1 = tower.rect.center
                        p2 = enemy.rect.center
                        if math.sqrt((p1[0] - p2[0]) ** 2 + (p1[1] - p2[1]) ** 2) <= tower.range*TILE_SIZE:
                            # If enemy is in range, add it to the tower's in_range list
                            tower.in_range.append(enemy)

                if len(tower.in_range) > 0:
                    # If there are enemies in range, create a bullet with the furthest enemy as it's target
                    b = Bullets(tower.rect.center, tower.damage)
                    bullets.add(b)
                    b.target_sprite = furthest(tower.in_range, path)
                    tower.counter = 0
Esempio n. 14
0
    def __init__(self):
        self.__game_settings = GameSettings()
        self.__screen = Screen(self.__game_settings.screen_settings)
        self.__ship = Ship(self.__game_settings.ship_settings, self.__screen)

        self.__bullets = Bullets(self.__game_settings.bullets_settings,
                                 self.__ship, self.__screen)

        self.__dvd_logos = DVDLogos(self.__game_settings.dvd_logos_settings,
                                    self.__ship, self.__screen)

        self.__collison_detector = CollisionDetector(
            self.__game_settings.collison_detector_settings, self.__ship,
            self.__bullets, self.__dvd_logos)

        self.__event_checker = EventChecker(self.__game_settings, self.__ship,
                                            self.__bullets)
Esempio n. 15
0
def check_KEYDOWN_events(event, screen, ai_settings, ship, bullets,
                         game_stats):
    """监听按下键盘事件"""
    #按下右
    if event.key == pygame.K_RIGHT:
        ship.mviong_right = True
    #按下左
    elif event.key == pygame.K_LEFT:
        ship.moving_left = True
    #按下空格
    elif event.key == pygame.K_SPACE and game_stats.game_stats:
        new_bullet = Bullets(screen, ai_settings, ship)
        if len(bullets) <= ai_settings.bullets_allowed:
            bullets.add(new_bullet)
    #按q结束游戏
    elif event.key == pygame.K_q:
        sys.exit()
Esempio n. 16
0
	

	for enem in Rem.remar:
		if enem.liv==1:
			enem.destroy(brd)
			os.system('aplay sound/stomp.wav&')
			brd.score+=500
	#input = sys.stdin.read(1)
	os.system('clear')
	print(brd.retBoardStr())
	if input is not None:
		if input == 'h':
			if mario.lvl == 3:
				os.system('aplay sound/fireball.wav')
				for i in range(0,4):
					bula = Bullets(1,1,'b')
					bula.setNewPosition(brd,mario.x+1,mario.y+4)
					bul.append(bula)
					for cord in bul:
						if cord.liv == 1:
							cord.moveRight(brd)


		if input != 'w' and input!= 'q' and input!='e' and input!= 'h':
			mario.move(input,brd)
			time.sleep(0.05)
		if input == 'w':
			if mario.lvl == 1:
				os.system('aplay sound/small_jump.wav&')
			else:
				os.system('aplay sound/big_jump.wav&')
Esempio n. 17
0
def fire_bullets(bullets, game_settings, screen, ship):
    """Fire shells when spacebar is pressed """
    if len(bullets) < game_settings.amo:
        new_bullet = Bullets(game_settings, screen, ship)
        bullets.add(new_bullet)
Esempio n. 18
0
 def _fire_bullets(self):
     """Create a new bullet and at it to the bullets group."""
     if len(self.bullets) < self.settings.bullet_allowed:
         new_bullet = Bullets(self)
         self.bullets.add(new_bullet)
         pygame.mixer.Channel(1).play(self.settings.shoot)
Esempio n. 19
0
 def setUp(self):
     self.bullets = Bullets()
Esempio n. 20
0
class World():
    def __init__(self, mode='normal'):
        self.mode = mode

        self.alien_field = AlienField(self)
        self.player = Player(self)
        self.bullets = Bullets()
        self.barriers = Barriers()

        self._updatables = (self.alien_field,
                            self.player,
                            self.bullets)
        self._collidables = (self.alien_field, self.barriers, self.player)

        self.last_updated = time.time()

    def get_collisions(self):
        to_remove = None
        for b in self.bullets:
            if to_remove is not None:
                break
            for c in self._collidables:
                if c.collide(b):
                    to_remove = b

        if to_remove is not None:
            self.bullets.remove(to_remove)
            return True
        return False

    def update(self):
        for x in self._updatables:
            x.update()

        while True:
            if not self.get_collisions():
                break
        self.last_updated = time.time()

    def disable_update(self):
        self._update = self.update
        self.update = lambda: None

    def player_hit(self):
        self.disable_update()
        you_lose()

    def player_wins(self):
        self.disable_update()
        congratulations()

    def aliens_hit_barriers(self):
        self.barriers.field = (0, 0, 0)

    def receive_up(self):
        self.player.receive_up()

    def receive_left(self):
        self.player.receive_left()

    def receive_right(self):
        self.player.receive_right()

    def add_bullet(self, pos, owner):
        self.bullets.add(pos, owner)
Esempio n. 21
0
def fire_bullet(aa_settings, screen, ship, bullets):
    ''' handles firing of bullets'''
    if len(bullets) < aa_settings.bullet_allowed:
        new_bullet = Bullets(aa_settings, screen, ship)
        bullets.add(new_bullet)
Esempio n. 22
0
 def _fire_bullet(self):
     """Create a new bullet and add it to the bullets group."""
     if len(self.bullets) < self.settings.bullets_allowed:
         new_bullet = Bullets(self)
         self.bullets.add(new_bullet)
def fire_bullet(Bulletss,setting, ship1, screen):
    if len(Bulletss) <= 40 :
        noval_bullets = Bullets(setting, ship1, screen)
        Bulletss.add(noval_bullets)
def fire_bullet(bullets, settings, screen, ship):
    """Function to fire bullet when player presses space button"""
    if len(bullets) < settings.bullets_allowed:
        new_player_bullet = Bullets(settings, screen, ship)
        bullets.add(new_player_bullet)
Esempio n. 25
0
def run_game():
    # Initialize pygame, settings, and screen object.
    pygame.mixer.pre_init(44100, -16, 2, 2048)
    pygame.mixer.init()
    pygame.init()
    clock = pygame.time.Clock()
    clock.tick(60)
    ai_settings = Settings()
    screen = pygame.display.set_mode(
        (ai_settings.screen_width, ai_settings.screen_height))
    pygame.display.set_caption("Alien Invader")

    # Import sprite sheet
    sprite_sheet = SpriteSheet(file_name='images/spritesheet.png')

    # Make the Play and Scores button.
    play_button = Button(screen=screen, msg="Play", order=0)
    score_button = Button(screen=screen, msg="High Scores", order=1)

    # Open high score file
    try:
        high_score_file = open("high_score_file.txt", "r+")
    except FileNotFoundError:
        high_score_file = open("high_score_file.txt", "w+")

    # Make sound manager
    sounds = Sounds()

    # Create an instance to store game statistics and create a scoreboard.
    stats = GameStats(ai_settings=ai_settings)
    sb = Scoreboard(ai_settings=ai_settings,
                    screen=screen,
                    stats=stats,
                    sprite_sheet=sprite_sheet,
                    high_score_file=high_score_file)

    # Make the game objects.
    ship = Ship(ai_settings=ai_settings,
                screen=screen,
                sprite_sheet=sprite_sheet,
                stats=stats,
                sb=sb,
                sounds=sounds)
    explosions = Group()
    barriers = []
    fleet = Fleet(ai_settings=ai_settings,
                  screen=screen,
                  sprite_sheet=sprite_sheet,
                  sounds=sounds)
    bullets = Bullets(ai_settings=ai_settings,
                      screen=screen,
                      sprite_sheet=sprite_sheet,
                      stats=stats,
                      sb=sb,
                      ship=ship,
                      fleet=fleet,
                      barriers=barriers,
                      explosions=explosions,
                      sounds=sounds)

    # Make the event handler
    event_handler = EventHandler(ai_settings=ai_settings,
                                 play_button=play_button,
                                 score_button=score_button,
                                 stats=stats,
                                 sb=sb,
                                 ship=ship,
                                 bullets=bullets,
                                 fleet=fleet,
                                 sounds=sounds)

    # Make the display manager
    display = Display(ai_settings=ai_settings,
                      screen=screen,
                      sprite_sheet=sprite_sheet,
                      play_button=play_button,
                      score_button=score_button,
                      stats=stats,
                      sb=sb,
                      ship=ship,
                      bullets=bullets,
                      fleet=fleet,
                      barriers=barriers,
                      explosions=explosions,
                      event_handler=event_handler)

    # Start the main loop for the game.
    while True:
        event_handler.check_events(display=display)

        if stats.game_active:
            ship.update()
            bullets.update_bullets(display=display)
            fleet.update_aliens(ship=ship, display=display, bullets=bullets)
            fleet.update_ufos()

        display.update_screen()
Esempio n. 26
0
 def _fire_bullet(self):
     if len(self.bullets) < self.setting1.max_valid_bullet:
         new_bullet = Bullets(self)
         self.bullets.add(new_bullet)
Esempio n. 27
0
 def fire(self):
     if len(self.bullets) < 3:
         self.bullets.add(Bullets(self.rect))