コード例 #1
0
ファイル: map.py プロジェクト: treesseven/sokoban
 def data_process(self, line, y):
     for x in range(len(line)):
         if line[x] == rep["player"]: self.player = Player(x=x, y=y)
         if line[x] == rep["door"]: self.doors.append(Door(x=x, y=y))
         if line[x] == rep["box"]: self.boxes.append(Box(x=x, y=y))
         if line[x] == rep["wall"]: self.walls.append(Wall(x=x, y=y))
         if line[x] == rep["ground"]: self.grounds.append(Ground(x=x, y=y))
コード例 #2
0
    def players_sprite_init(self):
        self.playlist = arcade.SpriteList()

        self.player1 = Player(3, 4, self.health)
        self.playlist.append(self.player1)

        self.player2 = Player(5, 3, self.health)
        self.playlist.append(self.player2)
コード例 #3
0
    def load(self):
        self.all_sprites = pg.sprite.Group()
        self.solid = pg.sprite.Group()
        self.items_on_floor = pg.sprite.Group()
        self.doors = pg.sprite.Group()

        assets_folder = path.join(getcwd(), 'assets')
        self.map = Map(path.join(assets_folder, 'maps/map1.json'))

        self.spritesheet = Spritesheet(
            path.join(assets_folder, 'spritesheet.png'), 32)
        wall_img = self.spritesheet.get_image_at_col_row(0, 0)
        apple_img = self.spritesheet.get_image_alpha_at_col_row(1, 0)
        keycard_img = self.spritesheet.get_image_alpha_at_col_row(0, 3)
        self.background_surface = pg.Surface(
            (self.map.width * TILE_SIZE, self.map.height * TILE_SIZE))

        self.visibility_data = [[True] * self.map.height
                                for i in range(self.map.width)]
        self.fov_data = [[True] * self.map.height
                         for i in range(self.map.width)]

        for node in self.map.objects:
            x, y = node['x'], node['y']
            if node["name"] == 'WALL':
                #self.collisions.append(pg.Rect(x, y, TILE_SIZE, TILE_SIZE))  # TODO big rectangles
                wall = Wall(self, x, y, wall_img)
                if not LIMIT_FOV_FOR_STATIC_SPRITES:
                    wall.remove(self.all_sprites)  # skip drawing
                    self.background_surface.blit(
                        wall_img, (x * TILE_SIZE, y * TILE_SIZE))
                self.visibility_data[x][y] = False
            elif node["name"] == 'PLAYER':
                self.player = Player(self, x, y)
            elif node["name"] == 'APPLE':
                item = Item(self, x, y, apple_img)
                item.pickable = Pickable(item, 'apple', False, 1, False)
            elif node["name"] == 'KEYCARD':  # key card
                item = Item(self, x, y, keycard_img)
                item.pickable = Pickable(item, 'keycard', False, 1, False)
            elif node["name"] == "DOOR":
                Door(self, x, y, node["dir"])
                self.visibility_data[x][
                    y] = False  # TODO opened doors visibility

        for trigger in self.map.triggers:
            TextTrigger(
                self,
                pg.Rect(trigger["x"], trigger["y"], trigger["width"],
                        trigger["height"]), trigger["text"])

        self.camera = Camera(self.map.width_screen, self.map.height_screen)
コード例 #4
0
    def new(self):
        """Create new game
        """

        self.all_sprites = pg.sprite.Group()  # 4
        self.score = 0  # 5
        self.pipes = pg.sprite.Group()  # 6
        self.player = Player()  # 7
        self.all_sprites.add(self.player)
        pipe = PipePair()
        self.all_sprites.add(pipe)
        self.pipes.add(pipe)
        self.last_pipe = pg.time.get_ticks()  # 8
        self.run()
コード例 #5
0
    def __init__(self, level_file, level_width, level_height):
        '''
        Constructor
        '''
        self.platform_list = []
        self.player = None
        self.mobile_sprites = []

        with open(level_file) as file:
            self._level = file.readlines()

        self._width_scale = level_width / _get_longest_line_len(self._level)
        self._height_scale = level_height / len(self._level)

        for line_num in range(len(self._level)):
            for col_num in range(len(self._level[line_num])):
                if self._level[line_num][col_num] == "P":
                    self._add_platform(line_num, col_num)

                elif self._level[line_num][col_num] == "p":
                    x = col_num * self._width_scale
                    y = line_num * self._height_scale
                    self.player = Player(x, y)

                elif self._level[line_num][col_num] == "O":
                    self._add_power_up(line_num, col_num, PowerUpColors.ORANGE)

                elif self._level[line_num][col_num] == "s":
                    self._add_enemy(line_num, col_num, SimpleEnemy)
コード例 #6
0
 def new_game(self):
     self.all_sprites = pg.sprite.LayeredUpdates()
     self.enemys = pg.sprite.Group()
     self.players = pg.sprite.Group()
     self.buffs = pg.sprite.Group()
     self.player = Player(self)
     self.run()
コード例 #7
0
    def start(self):
        pg.display.set_caption("Demo")

        self.player = Player(self, 16 * self.tile_size, 8 * self.tile_size)
        self.camera.set_focus(self.player)

        self.kill_depth = max([p.rect.bottom
                               for p in self.static_bodies]) + 200
        print(self.kill_depth)
コード例 #8
0
    def start(self, origin):
        self.__init__(self.game)
        pg.display.set_caption("Combat Test")

        self.player = Player(self, self.screen.get_width() // 2, 600)
        self.camera.set_focus(self.player)

        for edge in self.edges:
            edge.player = self.player
        for sprite in self.rigid_bodies:
            if isinstance(sprite, Mob):
                sprite.set_target(self.player)
コード例 #9
0
    def new(self):
        # start a new game
        self.score = 0
        self.all_sprites = pg.sprite.Group()
        self.enemies = pg.sprite.Group()
        self.projectiles = pg.sprite.Group()
        self.allies = pg.sprite.Group()
        self.player = Player(self)
        self.alliesCreated = 0

        self.backgroundImg = pygame.image.load(path.join(IMG_DIR, 'background.png')).convert()
        self.gameoverImg = pygame.image.load(path.join(IMG_DIR, 'gameover.png')).convert()
        self.backgroundRect = self.backgroundImg.get_rect()

        #Create the enemies
        for i in range(ENEMIES):
            m = Enemy(self)
            self.all_sprites.add(m)
            self.enemies.add(m)

        self.run()
コード例 #10
0
    def reset(self):
        if self.players_list:
            for player in self.players_list:
                if not player.visible:
                    continue
                if not self.points[player.tank_id]:
                    self.points[player.tank_id] = 1
                else:
                    self.points[player.tank_id] += 1

        # Load level
        self.level = Level()

        self.players_list = pygame.sprite.Group()
        self.walls_list = pygame.sprite.Group()
        self.path_list = pygame.sprite.Group()
        self.bullets_list = pygame.sprite.Group()
        self.power_up_list = pygame.sprite.Group()
        sprite_groups = {
            'players_list': self.players_list,
            'walls_list': self.walls_list,
            'path_list': self.path_list,
            'bullets_list': self.bullets_list,
            'power_up_list': self.power_up_list
        }

        self.walls_list.add(self.level.walls)
        # Players
        free_spot = self.level.get_free_spot(False)
        if free_spot:
            self.player1 = Player("red", *free_spot, sprite_groups, 0, "Mads")
            self.players_list.add(self.player1)
        free_spot = self.level.get_free_spot(False)
        if free_spot:
            self.player2 = Player("blue", *free_spot, sprite_groups, 1,
                                  "Kasper")
            self.players_list.add(self.player2)
コード例 #11
0
    def load(self, map_name):
        """
        Loads new map with the given name
        :param map_name: map to be loaded
        :return: nothing
        """
        assets_folder = path.join(getcwd(), 'assets')
        self.__map__ = Map(path.join(assets_folder, 'maps/' + map_name + '.json'))

        self.spritesheet = Spritesheet(path.join(assets_folder, 'spritesheet.png'), 32)
        wall_img = self.spritesheet.get_image_at_row_col(0, 0)
        apple_img = self.spritesheet.get_image_alpha_at_row_col(1, 0)

        self.__visibility_data__ = [[True] * self.__map__.height for i in range(self.__map__.width)]
        self.__fov_data__ = [[True] * self.__map__.height for i in range(self.__map__.width)]

        for node in self.__map__.objects:
            x, y = node['x'], node['y']
            if node["name"] == 'WALL':
                Wall(self, x, y, wall_img)
                self.__visibility_data__[x][y] = False
            elif node["name"] == 'PLAYER':
                self.player = Player(self, x, y)
            elif node["name"] == 'APPLE':
                item = Item(self, x, y, apple_img)
                item.pickable = Pickable(item, 'apple', False, 1, False)
            elif node["name"] == "DOOR":
                Door(self, x, y, node["dir"])
                self.__visibility_data__[x][y] = False  # TODO opened doors visibility

        for trigger in self.__map__.triggers:
            TextTrigger(self,
                        pg.Rect(trigger["x"], trigger["y"], trigger["width"], trigger["height"]),
                        trigger["text"])

        self.__camera__ = Camera(self.__map__.width_screen, self.__map__.height_screen)
コード例 #12
0
    def start(self):
        pg.display.set_caption("Demo")

        for i in range(10):
            Platform(self, i * 2000 + 550, 350, 2000, 32)
        Platform(self, 400, 200, 32, 500)
        Platform(self, 500, 200, 32, 500)

        a = Platform(self, 300, 100, 32, 32)
        b = Platform(self, 300, 132, 32, 32)
        c = Platform(self, 332, 132, 32, 32)
        d = Platform(self, 332, 100, 32, 32)
        e = a.compress_with(b, True, True)[0]
        f = c.compress_with(d, True, True)[0]
        e.compress_with(f, True, True)

        self.player = Player(self, 450, 0)
        self.camera_focus = self.player
コード例 #13
0
ファイル: game.py プロジェクト: soupss/space-invaders
 def new(self):
     self.score = 0
     self.level = 0
     self.pre_wave_begin = None
     self.sprites = pg.sprite.Group()  # all sprites
     self.player = pg.sprite.GroupSingle()
     self.mobs = MobGroup(self)  # spritegroup sub class
     self.bunkers = pg.sprite.Group()
     self.bullets = pg.sprite.Group()  # all bullets
     self.player_bullets = pg.sprite.Group()
     self.mob_bullets = pg.sprite.Group()
     Player(self)
     # spawn bunkers
     for i in range(4):
         spacing = WIDTH / 5
         offset = (WIDTH - (BUNKER_WIDTH * 4 +
                            (spacing - BUNKER_WIDTH) * 3)) / 2
         Bunker(self, i * spacing + offset, BUNKER_Y)
     self.run()
コード例 #14
0
    def start(self, _):
        pg.display.set_caption("Combat Test")

        self.player = Player(self, self.screen.get_width() // 2, 300)

        for i in range(2):
            m = Mob(self, 2 * self.screen.get_width() // 3, 300 + i * 20)
            m.set_target(self.player)

            m = Mob(self, self.screen.get_width() // 3, 300 + i * 20)
            m.set_target(self.player)

            m = Mob(self, self.screen.get_width() * 1.5, 600 + i * 20)
            m.set_target(self.player)

        self.camera.set_focus(self.player)

        for edge in self.edges:
            edge.player = self.player
コード例 #15
0
ファイル: map.py プロジェクト: chynes2/dnd
    def __init__(self, game, map_name):
        self.game = game
        self.npcs = set()

        game_folder = os.path.dirname('..')
        image_folder = os.path.join(game_folder, 'images', 'maps')
        with open(os.path.join(image_folder, map_name)) as f:
            map = f.readlines()
        for y, tiles in enumerate(map):
            for x, tile in enumerate(tiles):
                if tile == '1':
                    Wall(game, x, y)
                elif tile == 'P':
                    self.game.p1 = Player(self.game, x * tile_size,
                                          y * tile_size)
                    self.game.p1.rect.x += (tile_size -
                                            self.game.p1.rect.width) / 2
                elif tile == 'N':
                    self.npcs.add(NPC(self.game, x * tile_size, y * tile_size))

        self.tilewidth = len(map[0].strip())
        self.tileheight = len(map)
        self.width = self.tilewidth * tile_size
        self.height = self.tileheight * tile_size
コード例 #16
0
class Game:
    def __init__(self, display):

        # Contains pictures displayed on the player's screen
        self.picture_queue = [] # TODO: finish

        # Contains text displayed on the player's screen
        self.text_queue = []

        # Contains menus displayed on the player's screen
        self.menu_queue = [] # TODO: finish

        # Contains the user-controlled player
        self.player = None

        # Contains keyboard keys just pressed
        self.keys_just_pressed = set()

        # Contains joystick controls just pressed
        self.joystick_just_pressed = set()

        # Contains the spritesheet. Useful for defining sprites
        self.spritesheet = None

        # Updates user's FOV
        self.update_fov = True

        self.__display__ = display
        self.__clock__ = pg.time.Clock()
        pg.display.set_caption(WINDOW_TITLE)

        joysticks = [pg.joystick.Joystick(x) for x in range(pg.joystick.get_count())]
        self.__joystick__ = None
        if len(joysticks) > 0:
            self.__joystick__ = joysticks[0]
            self.__joystick__.init()

        self.__map__ = None
        self.__camera__ = None
        self.__playing__ = False
        self.__dt__ = 0.0

        self.__textBox__ = pg.image.load("assets/textBox.png").convert_alpha()
        self.__font__ = pg.font.Font("assets/fonts/Arcon.otf", 20)
        self.__fontSpace__ = pg.font.Font("assets/fonts/Arcon.otf", 14)

        self.__gui__ = Nanogui()
        self.__visibility_data__ = None  # [x][y] -> True, False
        self.__fov_data__ = None  # [x][y] -> True, False

    def load(self, map_name):
        """
        Loads new map with the given name
        :param map_name: map to be loaded
        :return: nothing
        """
        assets_folder = path.join(getcwd(), 'assets')
        self.__map__ = Map(path.join(assets_folder, 'maps/' + map_name + '.json'))

        self.spritesheet = Spritesheet(path.join(assets_folder, 'spritesheet.png'), 32)
        wall_img = self.spritesheet.get_image_at_row_col(0, 0)
        apple_img = self.spritesheet.get_image_alpha_at_row_col(1, 0)

        self.__visibility_data__ = [[True] * self.__map__.height for i in range(self.__map__.width)]
        self.__fov_data__ = [[True] * self.__map__.height for i in range(self.__map__.width)]

        for node in self.__map__.objects:
            x, y = node['x'], node['y']
            if node["name"] == 'WALL':
                Wall(self, x, y, wall_img)
                self.__visibility_data__[x][y] = False
            elif node["name"] == 'PLAYER':
                self.player = Player(self, x, y)
            elif node["name"] == 'APPLE':
                item = Item(self, x, y, apple_img)
                item.pickable = Pickable(item, 'apple', False, 1, False)
            elif node["name"] == "DOOR":
                Door(self, x, y, node["dir"])
                self.__visibility_data__[x][y] = False  # TODO opened doors visibility

        for trigger in self.__map__.triggers:
            TextTrigger(self,
                        pg.Rect(trigger["x"], trigger["y"], trigger["width"], trigger["height"]),
                        trigger["text"])

        self.__camera__ = Camera(self.__map__.width_screen, self.__map__.height_screen)

    def run(self):
        """
        Run the game
        :return: nothing
        """
        self.__playing__ = True
        while self.__playing__:
            self.__dt__ = self.__clock__.tick(FPS) / 1000
            self.__events__()
            self.__update__()
            self.__draw__()

    def get_axis(self, axis_number):
        """
        Produce the position of joystick axis

        The axis number must be an integer from zero to get_numaxes()-1.

        :param axis_number: Axis number
        :return: if there is joystick, produce the position of the joystick axis,
        otherwise produce 0
        """
        if self.__joystick__ is not None:
            return self.__joystick__.get_axis(axis_number)
        return 0.0

    def set_visibility(self, tilex, tiley, value):
        """
        Sets the visibility of the sprite at the given tile position
        :param tilex:
        :param tiley:
        :param value:
        :return:
        """
        self.__visibility_data__[tilex][tiley] = value
        self.update_fov = True

    #  ___________________________________________________________________
    # |                        _                   _                      |
    # |         _ __    _ __  (_) __   __   __ _  | |_    ___             |
    # |        | '_ \  | '__| | | \ \ / /  / _` | | __|  / _ \            |
    # |        | |_) | | |    | |  \ V /  | (_| | | |_  |  __/            |
    # |        | .__/  |_|    |_|   \_/    \__,_|  \__|  \___|            |
    # |        |_|                                                        |
    # |___________________________________________________________________|

    def __put_text_on_screen__(self, text):
        self.__display__.blit(self.__textBox__, (0, 360))
        self.__display__.blit(self.__font__.render(text, True, (255, 255, 255)), (150, 390))
        self.__display__.blit(self.__fontSpace__.render("[SPACE]", True, (255, 255, 255)), (560, 440))
        pg.display.flip()

    def __draw_fov__(self):
        for x in range(len(self.__fov_data__)):
            for y in range(len(self.__fov_data__[0])):
                if self.__fov_data__[x][y]:
                    newx, newy = self.__camera__.transform_xy(x * TILE_SIZE, y * TILE_SIZE)
                    pg.draw.rect(self.__display__, (200, 200, 200), pg.Rect(newx, newy,
                                                                            TILE_SIZE, TILE_SIZE), 1)

    def __toggle_fullscreen__(self):
        """Taken from http://pygame.org/wiki/__toggle_fullscreen__"""

        screen = pg.display.get_surface()
        tmp = screen.convert()
        caption = pg.display.get_caption()
        cursor = pg.mouse.get_cursor()

        w, h = screen.get_width(), screen.get_height()
        flags = screen.get_flags()
        bits = screen.get_bitsize()

        pg.display.quit()
        pg.display.init()

        self.__display__ = pg.display.set_mode((w, h), flags ^ pg.FULLSCREEN, bits)
        self.__display__.blit(tmp, (0, 0))
        pg.display.set_caption(*caption)

        pg.key.set_mods(0)

        pg.mouse.set_cursor(*cursor)

        return screen

    def __quit__(self):
        pg.quit()
        sys.exit()

    def __events__(self):
        self.keys_just_pressed.clear()
        self.joystick_just_pressed.clear()
        for event in pg.event.get():
            if event.type == pg.QUIT:
                self.__quit__()
            if event.type == pg.KEYDOWN:
                self.keys_just_pressed.add(event.key)
                if event.key == pg.K_ESCAPE:
                    self.__quit__()
                if event.key == pg.K_F11:
                    self.__toggle_fullscreen__()
            if event.type == pg.JOYBUTTONDOWN:
                self.joystick_just_pressed.add(event.button)

    def __update__(self):
        self.__gui__.pre(self.__joystick__)

        for sprite in sprite_groups.all_sprites:
            sprite.update(self.__dt__)

        if self.__camera__.update(self.player) or self.update_fov:
            player_hit_rect = self.player.get_hit_rect()
            player_tilex = math.floor(player_hit_rect.x / TILE_SIZE)
            player_tiley = math.floor(player_hit_rect.y / TILE_SIZE)

            self.__fov_data__ = calc_fov(player_tilex, player_tiley, FOV_RADIUS,
                                         self.__visibility_data__, self.__fov_data__)
            self.update_fov = False

        self.__gui__.after()

    def __draw__(self):
        self.__display__.fill(BG_COLOR)

        # TODO layering
        for sprite in sprite_groups.all_sprites:
            if sprite != self.player and not isinstance(sprite, Item):
                self.__display__.blit(sprite.image, self.__camera__.transform(sprite))

        for sprite in sprite_groups.items_on_floor:
            tilex = math.floor(sprite.x)
            tiley = math.floor(sprite.y)
            if self.__fov_data__[tilex][tiley]:
                self.__display__.blit(sprite.image, self.__camera__.transform(sprite))

        if DEBUG_FOV:
            self.__draw_fov__()

        self.__display__.blit(self.player.image, self.__camera__.transform(self.player))
        if self.text_queue:
            self.__put_text_on_screen__(self.text_queue[-1])

        self.__gui__.draw()
        pg.display.flip()
コード例 #17
0
class Game:
    def __init__(self):
        # initialize game window, etc
        pg.init()
        pg.mixer.init()
        self.screen = pg.display.set_mode((WIDTH, HEIGHT))
        pg.display.set_caption(TITLE)
        self.clock = pg.time.Clock()
        self.running = True

    def new(self):
        # start a new game
        self.score = 0
        self.all_sprites = pg.sprite.Group()
        self.enemies = pg.sprite.Group()
        self.projectiles = pg.sprite.Group()
        self.allies = pg.sprite.Group()
        self.player = Player(self)
        self.alliesCreated = 0

        self.backgroundImg = pygame.image.load(path.join(IMG_DIR, 'background.png')).convert()
        self.gameoverImg = pygame.image.load(path.join(IMG_DIR, 'gameover.png')).convert()
        self.backgroundRect = self.backgroundImg.get_rect()

        #Create the enemies
        for i in range(ENEMIES):
            m = Enemy(self)
            self.all_sprites.add(m)
            self.enemies.add(m)

        self.run()

    def run(self):
        # Game Loop
        self.playing = True
        while self.playing:
            self.clock.tick(FPS)
            self.events()
            self.update()
            self.draw()

    def update(self):
        # Game Loop - Update
        self.all_sprites.update()

        #Detects hits between enemies and lasers
        hits = pygame.sprite.groupcollide(self.enemies, self.projectiles, False, True)
        for enemy, projectile in hits.items():

            #Remove one life of the enemy and delete if lives=0
            enemy.lives -= 1
            if(enemy.lives == 0):
                enemy.kill()
                self.score += 1

                #Add a new enemy instead
                m = Enemy(self)

        #Asteroid and Ally collision
        hits = pygame.sprite.groupcollide(self.allies, self.enemies, True, True)
        for enemy in hits:
            m = Enemy(self)

        hits = pygame.sprite.spritecollide(self.player, self.enemies, True)
        for enemy in hits:
            if enemy.type == "meteor":
                damage = 1
            elif enemy.type == "bomb":
                damage = 2

            self.player.lives = self.player.lives - damage
            m = Enemy(self)

            if(self.player.lives <= 0):
                self.playing = False

        if (self.score % 30) == 0 and self.score != 0 and self.alliesCreated < self.score/30:
            a = Ally(self)
            self.alliesCreated += 1

    def events(self):
        # Game Loop - events
        for event in pg.event.get():
            # check for closing window
            if event.type == pg.QUIT:
                if self.playing:
                    self.playing = False
                self.running = False
            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_LEFT:
                    self.player.speedx = -5
                if event.key == pygame.K_RIGHT:
                    self.player.speedx = 5
                if event.key == pygame.K_SPACE:
                    self.player.shoot()
            elif event.type == pygame.KEYUP:
                if event.key == pygame.K_LEFT:
                    self.player.speedx = 0
                if event.key == pygame.K_RIGHT:
                    self.player.speedx = 0

    def draw(self):
        # Game Loop - draw
        self.screen.fill(BLACK)

        self.screen.blit(self.backgroundImg, self.backgroundRect)
        self.all_sprites.draw(self.screen)
        self.draw_text(str(self.score), 24, WIDTH/2, 20)
        self.draw_text(str(self.player.lives) + " LIVES", 20, 40, HEIGHT-30)

        allyWord = " ALLY" if len(self.allies) == 1 else " ALLIES"
        self.draw_text(str(len(self.allies)) + allyWord, 20, WIDTH-40, HEIGHT-30)

        # *after* drawing everything, flip the display
        pg.display.flip()

    def show_start_screen(self):
        # game splash/start screen
        pass

    def show_gameover(self):
        if not self.running:
            return
        self.screen.fill(BLACK)
        self.screen.blit(self.gameoverImg, self.backgroundRect)
        self.draw_text("SCORE: "+str(self.score), 40, WIDTH/2, HEIGHT/2+50)
        self.draw_text("Press g to try again.", 40, WIDTH/2, HEIGHT/2+80)

        pg.display.flip()
        self.wait_for_key(pygame.K_g)


    def draw_text(self, message, fontSize, x, y):
        font = pygame.font.Font(FONT_NAME, fontSize)
        text_surface = font.render(message, True, WHITE)
        text_rect = text_surface.get_rect()
        text_rect.midtop = (x, y)
        self.screen.blit(text_surface, text_rect)

    def wait_for_key(self, key = pygame.K_SPACE):
        waiting = True
        while waiting:
            self.clock.tick(FPS)
            for event in pg.event.get():
                if event.type == pg.QUIT:
                    waiting = False
                    self.running = False
                if event.type == pg.KEYUP:
                    if event.key == key:
                        waiting = False
コード例 #18
0
ファイル: game.py プロジェクト: MikaEleFant/PyWave-Slasher
from sprites.background import Background
from sprites.ground import Ground
from sprites.player import Player
from sprites.enemies.slime import Slime
from sprites.attacks.slime_attack import SlimeAttack
from stage import stages

pygame.init()

pygame.display.set_caption("Test Game")
stage = stages[0]

background = Background(stage["background"])
ground = Ground(stage["ground"])
player = Player()
slime = Slime()
slime_atk = SlimeAttack()
enemy_group = pygame.sprite.Group()
enemy_group.add(slime)
player_group = pygame.sprite.Group()
player_group.add(player)

hits = pygame.sprite.spritecollide(player, enemy_group, False)

while True:
    keys = pygame.key.get_pressed()
    player.gravity_check()

    for event in pygame.event.get():
        if event.type == QUIT:
コード例 #19
0
            print(data[1].x)

            if not data:
                print("Disconnected")
                break
            else:
                players[data[0]].disconnected = False
                reply = players

                # print("Received: ", data)
                # print("Sending : ", reply)

            conn.sendall(pickle.dumps(reply))
        except:
            break

    print("Lost connection")
    players[data[0]].disconnected = True
    conn.close()


currentPlayer = 0
while True:
    conn, addr = s.accept()
    print("conn")
    print("Connected to:", addr)
    players.append(
        Player(randint(50, 400), randint(50, 400), 50, 50, (255, 0, 0)))

    start_new_thread(threaded_client, (conn, currentPlayer))
    currentPlayer += 1
コード例 #20
0
 def create_player(self, x, y):
     '''
     Creates a sprite object of type Player
     '''
     return Player(x, y)
コード例 #21
0
import events
import global_vars
import loader
from sprites import bullets
from sprites import enemy
from sprites.background import Background
from sprites.player import Player

pygame.init()
loader.load()

pygame.display.set_mode(global_vars.SCREEN_SIZE)
pygame.display.set_caption("Hell Of Bullets")

clk = pygame.time.Clock()
player = Player()
bg = Background()
enemy_spawn_ctrl = enemy.Controller()


fps_target = 30
last = 0
running = True
while running:
    deltaT = clk.tick(60) / 1000
    events.process_events()

    if events.QUIT:
        running = False

    # PHYSICS AND CONTROLLER UPDATES
コード例 #22
0
ファイル: map.py プロジェクト: treesseven/sokoban
class Map:
    def __init__(self, level):
        self.level = level
        # dx, dy = direction x and y of game

    def get_data_file(self):
        data_file = str(self.level)
        while len(data_file) < 3:
            data_file = '0' + data_file
        data_file = "soko" + data_file + ".txt"
        return data_file

    def data_process(self, line, y):
        for x in range(len(line)):
            if line[x] == rep["player"]: self.player = Player(x=x, y=y)
            if line[x] == rep["door"]: self.doors.append(Door(x=x, y=y))
            if line[x] == rep["box"]: self.boxes.append(Box(x=x, y=y))
            if line[x] == rep["wall"]: self.walls.append(Wall(x=x, y=y))
            if line[x] == rep["ground"]: self.grounds.append(Ground(x=x, y=y))

    def move(self, object, dx, dy):
        object.move(self.current_dx, self.current_dy)

    def load(self):
        self.doors = []
        self.boxes = []
        self.walls = []
        self.grounds = []
        data_file = self.get_data_file()
        with open("./maps/" + data_file, "r") as myfile:
            y = -1
            max_width = 0
            for line in myfile:
                y += 1
                self.data_process(line, y)
                max_width = max(max_width, len(line) - 1)

        self.width = max_width
        self.height = y
        self.loaded = True

    def update(self, dx, dy):
        self.player.dx = dx
        self.player.dy = dy
        if self.player.collide(self.walls) is None:
            box = self.player.collide(self.boxes)
            if box is not None:
                box.dx = dx
                box.dy = dy
                if box.collide(self.walls) is None and box.collide(
                        self.boxes) is None:
                    box.move()
                    if box.overlap(self.doors):
                        box.overlapped = True
                        sound_effect["box_in_door"].play()
                    self.player.move()
                else:
                    sound_effect["box_deny"].play()
            else:
                self.player.move()
        else:
            sound_effect["box_deny"].play()

    def get_actual_coords(self, x, y):
        return x * UNIT_PIXEL, y * UNIT_PIXEL

    def draw(self):

        for y in range(self.height):
            for x in range(self.width):
                self.screen_surf.blit(image["ground"],
                                      (x * UNIT_PIXEL, y * UNIT_PIXEL))

        for door in self.doors:
            self.screen_surf.blit(image["door"],
                                  (door.x * UNIT_PIXEL + DOOR_PADDLE,
                                   door.y * UNIT_PIXEL + DOOR_PADDLE))

        self.screen_surf.blit(image["player"][self.player.state],
                              (self.player.x * UNIT_PIXEL + PLAYER_PADDLE,
                               self.player.y * UNIT_PIXEL))

        for wall in self.walls:
            self.screen_surf.blit(image["wall"],
                                  (wall.x * UNIT_PIXEL, wall.y * UNIT_PIXEL))

        for box in self.boxes:
            state = "norm"
            if box.overlap(self.doors):
                state = "overlapped"
            self.screen_surf.blit(image["box"][state],
                                  (box.x * UNIT_PIXEL, box.y * UNIT_PIXEL))

    def music(self):
        pygame.mixer.music.load("./music/loading_music.mp3")
        pygame.mixer.music.play(-1, 0.0)

    def play_sound(self, sound):
        sound_effect[sound].play()

    def stop_music(self):
        pygame.mixer.music.stop()

    def check_win(self):
        for box in self.boxes:
            if not box.overlap(self.doors):
                return False
        self.GAME = False
        return True

    def add_text(self, text, x, y):
        self.screen_surf.blit(textSurf[text], (x, y))

    def add_screen_text(self):
        self.add_text("next_level", 600, 350)
        self.add_text("back_level", 600, 400)
        self.add_text("reset_level", 600, 450)

    def play(self):
        self.load()
        sound_effect["win"].stop()
        print(self.player.x, self.player.y)
        self.GAME = True
        self.screen_surf = pygame.display.set_mode(
            (SCREEN_WIDTH * UNIT_PIXEL, SCREEN_HEIGHT * UNIT_PIXEL))
        self.music()
        self.played_sound = False
        self.time = pygame.time.get_ticks()
        while True:
            dx = 0
            dy = 0
            for event in pygame.event.get():
                if event.type == pygame.QUIT or \
                ( event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE):
                    pygame.quit()
                    sys.exit()

                if event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_n:
                        ## Chuyen man tiep theo
                        pygame.time.wait(500)
                        return +1

                    if event.key == pygame.K_b:
                        ## Lui` man` truoc
                        pygame.time.wait(500)
                        return -1

                    if event.key == pygame.K_r:
                        ## Choi lai man
                        pygame.time.wait(200)
                        return 0

                    ####################################################
                    if self.GAME is not DONE:

                        if event.key == pygame.K_LEFT:
                            dx -= 1
                            self.player.state = "LEFT"

                        if event.key == pygame.K_RIGHT:
                            dx += 1
                            self.player.state = "RIGHT"

                        if event.key == pygame.K_UP:
                            dy -= 1
                            self.player.state = "UP"

                        if event.key == pygame.K_DOWN:
                            dy += 1
                            self.player.state = "DOWN"
            self.screen_surf.fill(BGCOLOR)
            self.draw()
            self.update(dx, dy)
            self.add_screen_text()
            if self.check_win():
                if pygame.time.get_ticks() - self.time <= 400:
                    self.add_text("win", 600, 100)
                elif pygame.time.get_ticks() - self.time >= 800:
                    self.time = pygame.time.get_ticks()

                self.player.state = "DOWN"
                if not self.played_sound:
                    self.stop_music()
                    self.play_sound("win")
                    self.played_sound = True
            pygame.display.update()
コード例 #23
0
ファイル: Gunny.py プロジェクト: trileminh94/game2
def main(screen):
    pygame.mouse.set_visible(0)
    # Load image
    background = pygame.image.load("resources\image\TileSet\\background.png").convert()
    img = Utils.load_image('explosion1.gif')
    coins_image = pygame.image.load('resources\image\TileSet\Coins.png')
    Explosion.images = [img, pygame.transform.flip(img, 1, 1)]

    # Load font
    coin_font = pygame.font.Font("resources\Fonts\Number.ttf", 32)

    # Load the sound effects
    boom_sound = Utils.load_sound('boom.wav')
    shoot_sound = Utils.load_sound('1.wav')

    if pygame.mixer:
        music = 'resources/data/1037.wav'
        pygame.mixer.music.load(music)
        pygame.mixer.music.play(-1)

    # Initialize Game Groups
    aliens = pygame.sprite.Group()
    bombs = pygame.sprite.Group()
    monsterbombs = pygame.sprite.Group()
    render_group = pygame.sprite.OrderedUpdates()
    creeps = pygame.sprite.Group()
    items = pygame.sprite.Group()

    # Assign default groups to each sprite class

    # Ground.containers = all_group
    # Player.containers = all_group
    # BasicCreep.containers = all_group, creeps
    coreItem.containers = render_group

    Player.containers = render_group
    Player.screen = screen

    BasicCreep.containers = creeps, render_group
    Bullet.containers = bombs, render_group
    MonsterBullet.containers = monsterbombs,render_group
    Explosion.containers = render_group

    Live_bar.containers = render_group
    Energy_bar.containers = render_group
    Power_bar.containers = render_group

    # Create Some Starting Values
    # Global score

    clock = pygame.time.Clock()


    #ground = Ground()
    player = Player('nhan vat 1', 'character1', 1, 1, 350, screen)

    #*************************************
    # Init creeps
    #*************************************
    BasicCreep.screen = screen
    Player.screen = screen
    #*************************************
    # Init item
    #*************************************

    money_item = money(360, 200, "money")
    items.add(money_item)
    money_item = money(400, 200, "money")
    items.add(money_item)
    money_item = money(440, 200, "money")
    items.add(money_item)
    money_item = money(480, 200, "money")
    items.add(money_item)
    money_item = money(520, 200, "money")
    items.add(money_item)

    money_item = money(360, 80, "money")
    items.add(money_item)
    money_item = money(400, 80, "money")
    items.add(money_item)
    money_item = money(440, 80, "money")
    items.add(money_item)
    money_item = money(480, 80, "money")
    items.add(money_item)
    money_item = money(520, 80, "money")
    items.add(money_item)

    money_item = money(680, 40, "money")
    items.add(money_item)
    money_item = money(720, 40, "money")
    items.add(money_item)
    money_item = money(760, 40, "money")
    items.add(money_item)
    money_item = money(800, 40, "money")
    items.add(money_item)
    money_item = money(840, 40, "money")
    items.add(money_item)

    money_item = money(1600, 180, "money")
    items.add(money_item)
    money_item = money(1640, 180, "money")
    items.add(money_item)
    money_item = money(1680, 180, "money")
    items.add(money_item)
    money_item = money(1720, 180, "money")
    items.add(money_item)
    money_item = money(2592, 128, "money")
    items.add(money_item)
    money_item = money(2624, 128, "money")
    items.add(money_item)
    money_item = money(2656, 128, "money")
    items.add(money_item)
    money_item = money(2688, 128, "money")
    items.add(money_item)
    money_item = money(3744, 384, "money")
    items.add(money_item)
    money_item = money(3776, 384, "money")
    items.add(money_item)
    money_item = money(3808, 384, "money")
    items.add(money_item)
    money_item = money(3840, 384, "money")
    items.add(money_item)
    money_item = money(4736, 64, "money")
    items.add(money_item)
    money_item = money(4736, 32, "money")
    items.add(money_item)
    money_item = money(4768, 64, "money")
    items.add(money_item)
    money_item = money(4768, 32, "money")
    items.add(money_item)
    money_item = money(4800, 64, "money")
    items.add(money_item)
    money_item = money(4800, 32, "money")
    items.add(money_item)
    money_item = money(4832, 64, "money")
    items.add(money_item)
    money_item = money(4832, 32, "money")
    items.add(money_item)
    money_item = money(4864, 64, "money")
    items.add(money_item)
    money_item = money(4896, 32, "money")
    items.add(money_item)
    money_item = money(4928, 64, "money")
    items.add(money_item)
    money_item = money(4928, 32, "money")
    items.add(money_item)
    money_item = money(4960, 64, "money")
    items.add(money_item)
    money_item = money(4992, 32, "money")
    items.add(money_item)
    money_item = money(5024, 64, "money")
    items.add(money_item)
    money_item = money(5024, 32, "money")
    items.add(money_item)
    money_item = money(5056, 64, "money")
    items.add(money_item)
    money_item = money(5056, 32, "money")
    items.add(money_item)
    money_item = money(5088, 64, "money")
    items.add(money_item)
    money_item = money(5088, 32, "money")
    items.add(money_item)
    money_item = money(5120, 64, "money")
    items.add(money_item)
    money_item = money(5120, 32, "money")
    items.add(money_item)
    money_item = money(5152, 64, "money")
    items.add(money_item)
    money_item = money(5152, 32, "money")
    items.add(money_item)
    money_item = money(5184, 64, "money")
    items.add(money_item)
    money_item = money(5184, 32, "money")
    items.add(money_item)
    money_item = money(5216, 64, "money")
    items.add(money_item)
    money_item = money(5216, 32, "money")
    items.add(money_item)
    money_item = money(5248, 64, "money")
    items.add(money_item)
    money_item = money(5248, 32, "money")
    items.add(money_item)

    money_item = berry(2890, 100, "berry")
    items.add(money_item)


    money_item = money(5440, 192, "money")
    items.add(money_item)
    money_item = money(5472, 192, "money")
    items.add(money_item)
    money_item = money(5504, 192, "money")
    items.add(money_item)
    money_item = money(5472, 192, "money")
    items.add(money_item)

    money_item = money(5792, 160, "money")
    items.add(money_item)
    money_item = money(5824, 160, "money")
    items.add(money_item)
    money_item = money(5856, 160, "money")
    items.add(money_item)
    money_item = money(5888, 160, "money")
    items.add(money_item)

    money_item = money(6080, 160, "money")
    items.add(money_item)
    money_item = money(6112, 160, "money")
    items.add(money_item)
    money_item = money(6144, 160, "money")
    items.add(money_item)

    CreepManager.create_creep(creeps, 'A', 365, 332, 365, 480, 0, 1)
    CreepManager.create_creep(creeps, 'A', 611, 332, 576, 989, 0, 1)
    CreepManager.create_creep(creeps, 'A', 874, 332, 576, 989, 1, 1)
    CreepManager.create_creep(creeps, 'D', 1472+10, 316-50, 1472+10, 1588, 1, 1)
    CreepManager.create_creep(creeps, 'D', 1218+10, 380-50, 1218+10, 1374, 1, 1)

    CreepManager.create_creep(creeps, 'B', 1280+20, 508-30, 1280+20, 1374-20, 1, 1)
    CreepManager.create_creep(creeps, 'B', 1474+20, 508-30, 1474+20, 1628-50, 1, 1)
    CreepManager.create_creep(creeps, 'B', 1664+45, 508-30, 1664+45, 1782-20, 1, 1)

    CreepManager.create_creep(creeps, 'A', 2592+45, 442-48, 2592+45, 2876-20, 1, 1)
    CreepManager.create_creep(creeps, 'F', 2592+45, 100, 2592+45, 2876-20, 1, 4)

    CreepManager.create_creep(creeps, 'B', 3302+45, 442 - 30, 3302+45-20, 3548-20, 1, 2)
    CreepManager.create_creep(creeps, 'F', 3312+45, 300, 3302+45-20, 3548-20, 1, 4)
    CreepManager.create_creep(creeps, 'F', 3400, 200, 3302+45-20, 3548-20, 0, 3)
    CreepManager.create_creep(creeps, 'F', 3390, 70, 3302+45-20, 3548-20, 0, 3)

    CreepManager.create_creep(creeps, 'A', 3840+55, 442 - 15, 3840+50, 4000-20-20, 0, 1)

    CreepManager.create_creep(creeps, 'A', 4706+55, 362, 4706, 4862-20, 0, 1)

    CreepManager.create_creep(creeps, 'C', 5365, 162, 5365, 6000, 0, 4)
    CreepManager.create_creep(creeps, 'C', 5365, 62, 5365, 6000, 0, 4)

    CreepManager.create_creep(creeps, 'B', 6505, 316, 6505, 6645, 0, 4)

    CreepManager.create_creep(creeps, 'A_SPECIAL', 4917, 381, 4907, 5033, 0, 1)

    tileset = TileCache("resources/image/TileSet/ImageSheet.png", Constant.TILE_WIDTH, Constant.TILE_HEIGHT).load_tile_table()
    invisible_tiles = (((9,14), (9,15), (9, 16),(9, 17)),
                        ((6, 19), (6, 20), (6, 21), (6,22)),
                       ((12, 68), (12, 69), (12, 70), (13, 70), (14, 70)),
                       ((5, 81), (5, 82), (5, 83), (5, 84)),
                       ((7,144), (7, 145), (6, 146), (6, 147)))

    """ CREATE LIST OF SPECIAL OBJECTS """
    special_tiles = []
    for line in invisible_tiles:
        for element in line:
            special_tile = SpecialObject(tileset, element, (Constant.TILE_WIDTH * element[1], Constant.TILE_HEIGHT * element[0]))
            special_tiles.append(special_tile)

    camera_left = 0
    camera_right = Constant.SCREENRECT.width
    hCount = 1

    player.typeOfBullet = EBulletType.BASIC
    mymonster = monster(7400, 270, "monster")
    items.add(mymonster)
    player.sound_money = pygame.mixer.Sound('resources/data/yahoo.ogg')
    # Main loop
    while player.health > -10:

        # CREEP MANAGER
        CreepManager.update(creeps, player.pos[0], player.pos[1], player.rect.left)
        CreepManager.create_creep_dynamic(player.pos[0], creeps)
        if player.state == Constant.DIE_STATE:
            player.health -= 0.1

        # Get input
        player1_down_to_up = player.fire_down

        for event in pygame.event.get():
            if event.type == QUIT or (event.type == KEYDOWN and event.key == K_ESCAPE):
                return
            elif event.type == KEYDOWN:
                if event.key == Constant.PLAYER1FIREKEY:
                    player.fire_down = True
                elif event.key == Constant.PLAYER1CHANGEBULLET:
                    player.typeOfBullet += 1
                    if player.typeOfBullet >= Constant.NUM_BULLET_TYPE:
                        player.typeOfBullet = EBulletType.BASIC
                elif event.key == Constant.PLAYER1JUMPKEY:
                    if not player.downable:
                        player.jump = 20
            elif event.type == KEYUP:
                if event.key == Constant.PLAYER1FIREKEY:
                    player.fire_down = False
                    if player.enegery >= 20:
                        player.state = Constant.THROW_STATE

        # Clear/erase the last drawn sprites
        render_group.clear(screen, background)
        screen.fill((0, 0, 0))
        if (camera_right < Constant.SCREENRECT.width * 8):
            if camera_left < (hCount - 1) * background.get_width():
                hCount -= 1
            elif (camera_left < hCount * background.get_width()):
                if (camera_right > hCount * background.get_width()):
                        screen.blit(background, (0  - camera_left + (hCount - 1) * background.get_width(), 0))
                        screen.blit(background, (hCount * background.get_width() - camera_left, 0))
                else:
                        screen.blit(background, (0  - camera_left + (hCount -1) * background.get_width(), 0))
            else:
                hCount += 1

        tiles = []
        for y in range(int(camera_left) / Constant.TILE_WIDTH, (int(camera_right) / Constant.TILE_WIDTH) + 1):
            if y > 239:
                y = 239
            for x in range(0, 20):
                if Constant.MAP[x][y] is not 0:
                    tile = Tile(tileset, (x, y), (32 * y, 32 * x))
                    for line in invisible_tiles:
                        if tile.id in line:
                            tile.visible = False
                            break
                    if tile.visible:
                        screen.blit(tile.image, (Constant.TILE_WIDTH * y - camera_left, Constant.TILE_HEIGHT * x))
                    tiles.append(tile)

        # Update all the sprites
        render_group.update()
        monsterbombs.update()
        
        for item in items.sprites():
            item.update_pos(player.pos[0], player.rect.left)

        screen.blit(coins_image, (440, 0))
        screen.blit(coin_font.render(' X  ' + str(player.money), True, (0, 0, 0)), (480, 0))
        items.update()

        # Handle player input
        key_state = pygame.key.get_pressed()

        player.check(key_state)

        if player1_down_to_up and not player.fire_down and player.enegery >= 25:
            if player.typeOfBullet == EBulletType.BASIC:
                butllet = Bullet(player.angle, player.power, player, "fireball.png")
                shoot_sound.play()
                player.enegery -= butllet.energy_cost
            else:
                butllet = Bullet(player.angle, player.power, player, "simple.png")
                butllet = Bullet(player.angle+10, player.power, player, "simple.png")
                butllet = Bullet(player.angle-10, player.power, player, "simple.png")
                shoot_sound.play()
                player.enegery -= butllet.energy_cost

        # *************************************************************
        # CHECK COLLISION HERE!
        # *************************************************************
        for b in bombs.sprites():
            b.update_pos(player.pos[0], player.rect.x)



        """ COLLIDE WITH SPECIAL OBJECT"""
        for tile in tiles:
            if tile.id ==  (11, 21) and Utils.check_collision(player, tile):
                for special_tile in special_tiles:
                    if special_tile.id in invisible_tiles[0]:
                        special_tile.visible = True
            if tile.id == (11, 27) and Utils.check_collision(player, tile):
                for special_tile in special_tiles:
                    if special_tile.id in invisible_tiles[1]:
                        special_tile.visible = True
            if tile.id == (14, 58) and Utils.check_collision(player, tile):
                for special_tile in special_tiles:
                    if special_tile.id in invisible_tiles[2]:
                        special_tile.visible = True
            if tile.id == (6, 77) and Utils.check_collision(player, tile):
                for special_tile in special_tiles:
                    if special_tile.id in invisible_tiles[3]:
                        special_tile.visible = True
            if tile.id == (9, 143) and Utils.check_collision(player, tile):
                for special_tile in special_tiles:
                    if special_tile.id in invisible_tiles[4]:
                        special_tile.visible = True
        for special_tile in special_tiles:
            if special_tile.visible:
                screen.blit(special_tile.image, (Constant.TILE_WIDTH * special_tile.id[1] - camera_left, Constant.TILE_HEIGHT * special_tile.id[0]))
        """ OUT OF MAP"""
        if (player.pos[1] + Constant.PLAYERHEIGHT >= Constant.SCREENRECT.height):
            game_state = Constant.GAMEOVER
            break

        """PLAYER GOES DOWN"""
        player.downable = True
        for tile in tiles:
            is_Visible = True
            for special_tile in special_tiles:
                if special_tile.id == tile.id and special_tile.visible == False:
                    is_Visible = False
                    break
            if not is_Visible :
                continue
            if tile.downable == True:
                continue;
            if (player.pos[0]  >= tile.pos[0] and player.pos[0]  <= tile.pos[0] + Constant.TILE_WIDTH) \
                    or ( player.pos[0] + Constant.PLAYERWIDTH  >= tile.pos [0] and player.pos[0] + Constant.PLAYERWIDTH  <= tile.pos[0] + Constant.TILE_WIDTH):
                if (player.pos[1] + Constant.PLAYERHEIGHT  >= tile.pos[1] and player.pos[1] + Constant.PLAYERHEIGHT <= tile.pos[1] + Constant.TILE_HEIGHT):
                    player.downable = False
                    break;
        """ WALL BLOCK """
        player.isBlockByWall = False
        for tile in tiles:
            is_Visible = True
            for special_tile in special_tiles:
                if special_tile.id == tile.id and special_tile.visible == False:
                    is_Visible = False
                    break
            if is_Visible and tile.isBlockByWall == True and player.pos[1] <= tile.pos[1] and player.pos[1] + Constant.PLAYERHEIGHT >= tile.pos[1] \
                and player.pos[1] > tile.pos[1] - Constant.TILE_HEIGHT:
                """ Player goes to the right """

                if player.direction == 1:
                    if player.pos[0] + Constant.PLAYERWIDTH + player.speed>= tile.pos[0] \
                            and player.pos[0] + Constant.PLAYERWIDTH  + player.speed <= tile.pos[0] + Constant.TILE_WIDTH:

                        player.isBlockByWall = True
                else:
                    if player.pos[0] - player.speed  >= tile.pos[0] \
                            and player.pos[0] - player.speed <= tile.pos[0] + Constant.TILE_WIDTH:
                        player.isBlockByWall = True
        """ GROUND BLOCK """
        player.is_block_by_ground = False
        for tile in tiles:
            is_Visible = True
            for special_tile in special_tiles:
                if special_tile.id == tile.id and special_tile.visible == False:
                    is_Visible = False
                    break
            if is_Visible and tile.isBlockByGround and player.jump > 0 and player.pos[1] >= tile.pos[1] and player.pos[1] <= tile.pos[1] + Constant.TILE_HEIGHT:
                if(player.pos[0]  >= tile.pos[0] and player.pos[0]  <= tile.pos[0] + Constant.TILE_WIDTH) \
                or ( player.pos[0] + Constant.PLAYERWIDTH  >= tile.pos [0] and player.pos[0] + Constant.PLAYERWIDTH  <= tile.pos[0] + Constant.TILE_WIDTH):
                    player.jump = 0

        """ Move with world """
        if not player.isBlockByWall and player.state == Constant.MOVE_STATE:
            if (((player.pos[0] + player.direction * player.speed) >= 0 ) and (player.pos[0] + player.direction * player.speed <= Constant.SCREENRECT.width * 8)):
                player.pos[0] += player.direction * player.speed
            if (camera_left + player.direction * player.speed >= 0) and (camera_right + player.direction * player.speed < Constant.SCREENRECT.width * 8):
                camera_left += player.direction * player.speed
                camera_right += player.direction * player.speed
                player.moveWithScreen = False
            else:
                player.moveWithScreen = True



        dict_collide = pygame.sprite.groupcollide(bombs, creeps, True, False)
        for key in dict_collide.keys():
            boom_sound.play()
            Explosion(key)
            for creep in dict_collide[key]:
                if not isinstance(creep, CreepASpecial):
                    creep.kill()
                else:
                    creep.check_die()
        #check va cham cua player voi dan cua monster
        dict_collide1 = pygame.sprite.spritecollide(player,monsterbombs, True)
        for key in dict_collide1:
            boom_sound.play()
            Explosion(key)
            player.lost_blood(70)
        #check va cham cua monster voi dan cua player
        if mymonster:
            dict_collide2 = pygame.sprite.spritecollide(mymonster,bombs, True)
            for key in dict_collide2:
                boom_sound.play()
                Explosion(key)
                mymonster.lost_blood(5)

        if pygame.sprite.spritecollide(player, creeps, True):
            player.lost_blood(40)

        item_collides = pygame.sprite.spritecollide(player, items, True)
        for item in item_collides:
            if isinstance(item, berry):
                player.typeOfBullet = EBulletType.THREE
                continue
            #item.playEffect()
            player.sound_money.play()
            player.money += 1
            player.enegery += 5

        for b in monsterbombs.sprites():
           b.update_pos(player.pos[0], player.rect.x)

        dirty = render_group.draw(screen)  # Draw all sprite, return list of rect
        pygame.display.update(dirty)    # Draw only changed rect
        pygame.display.flip()
        # Cap the frame rate
        clock.tick(Constant.FPS)
        #Clear tile list
        tiles[:] = []


    game_state = Constant.GAMEOVER

    game_over(screen, game_state)
コード例 #24
0
ファイル: run_game.py プロジェクト: Krristiina/pynnis
# player positions
PLAYER1_X = FIELD_X + 20
PLAYER2_X = FIELD_X + FIELD_WIDTH - 20

# initializing pygame & creating window
pygame.init()
screen = pygame.display.set_mode((display_width, display_height))
background = pygame.Surface(screen.get_size())
pygame.display.set_caption('Pynnis')
clock = pygame.time.Clock()

# sprites
all_sprites = pygame.sprite.Group()
field = Field(FIELD_X, FIELD_Y, FIELD_WIDTH, FIELD_HEIGHT, green)
player1 = Player(PLAYER1_X, field.rect, red, pygame.K_a, pygame.K_s)
player2 = Player(PLAYER2_X, field.rect, red, pygame.K_k, pygame.K_l)
ball = Ball(field.rect, yellow)
score = Score(FIELD_X + FIELD_WIDTH / 2 - 100, 5, 200, 50, 32, white, black)

all_sprites.add(field)
all_sprites.add(player1)
all_sprites.add(player2)
all_sprites.add(ball)
all_sprites.add(score)

quitted = False
# Creating game loop
while not quitted:
    # Speed of game loop defined by frames/second
    clock.tick(frames_per_second)
コード例 #25
0
class Game:
    """ Represents board, start
    and game-over screens
    """
    def __init__(self):
        """Initialise a new Game instance.
            initialize game window, sounds, font, images etc.
        """
        pg.init()
        pg.mixer.init()
        self.screen = pg.display.set_mode((WIDTH, HEIGHT))
        pg.display.set_caption(TITLE)
        self.clock = pg.time.Clock()
        self.running = True
        self.pipes = None
        self.last_pipe = None
        self.playing = None
        self.all_sprites = None
        self.player = None
        self.score = None

    def new(self):
        """Create new game
        """

        self.all_sprites = pg.sprite.Group()  # 4
        self.score = 0  # 5
        self.pipes = pg.sprite.Group()  # 6
        self.player = Player()  # 7
        self.all_sprites.add(self.player)
        pipe = PipePair()
        self.all_sprites.add(pipe)
        self.pipes.add(pipe)
        self.last_pipe = pg.time.get_ticks()  # 8
        self.run()

    def run(self):
        """Represents a game loop
        """

        self.playing = True
        while self.playing:
            self.clock.tick(FPS)
            self.events()
            self.update()
            self.draw()

    def update(self):
        """Update the player's position.
        """

        self.all_sprites.update()
        time_now = pg.time.get_ticks()
        if time_now - self.last_pipe > PIPE_FREQUENCY:
            pipe = PipePair()
            self.pipes.add(pipe)
            self.all_sprites.add(pipe)
            self.last_pipe = time_now

        pipe_collision = any(p.collides_with(self.player) for p in self.pipes)
        if pipe_collision or self.player.rect.y <= 0:
            pg.mixer.Sound(SOUNDS_DIR + SOUNDS['hit']).play()
            self.playing = False

        for pipe in self.pipes:
            if pipe.rect.x < -pipe.PIECE_WIDTH:
                pg.mixer.Sound(SOUNDS_DIR + SOUNDS['point']).play()
                self.score += 5
                pipe.kill()

        if self.player.rect.bottom > HEIGHT:
            for sprite in self.all_sprites:
                sprite.rect.y -= max(self.player.vel.y, 10)
                if sprite.rect.bottom < 0:
                    sprite.kill()
            pg.mixer.Sound(SOUNDS_DIR + SOUNDS['die']).play()
            self.playing = False

    def events(self):
        """Define events for game loop
        check for closing window and control the player
        """
        for event in pg.event.get():
            if event.type == pg.QUIT:
                if self.playing:
                    self.playing = False
                self.running = False
            if event.type == pg.KEYDOWN:
                if event.key == pg.K_SPACE or event.key == pg.K_UP:
                    self.player.jump()
            if event.type == pg.MOUSEBUTTONUP:
                self.player.jump()

    def draw(self):
        """Drawing scene for game
        All sprites drawing on screen
        """

        for x_val in (0, WIDTH / 2):
            self.screen.blit(pg.image.load(IMAGES_DIR + IMAGES['background']),
                             (x_val, 0))

        self.all_sprites.draw(self.screen)
        self.draw_text('Score: ' + str(self.score), 22, WHITE,
                       Vec(WIDTH / 2, 15))

        pg.display.flip()

    def wait_for_key(self):
        """Represents part of start game element
        Wait for key at start
        """
        waiting = True
        while waiting:
            self.clock.tick(FPS)
            for event in pg.event.get():
                if event.type == pg.QUIT:
                    waiting = False
                    self.running = False
                if event.type == pg.KEYUP or event.type == pg.MOUSEBUTTONDOWN:
                    waiting = False

    def draw_text(self, text, size, color, position):
        """Represents an drawing text

        :param text: Message, wich will be display on screen.
        :param size: Size of font
        :param position: Tuple which contains left corner x,y position.
        :param color: Text's color
        """
        font_name = pg.font.match_font(FONT_NAME)
        font = pg.font.Font(font_name, size)
        text_surface = font.render(text, True, color)
        text_rect = text_surface.get_rect()
        text_rect.midtop = (position.x, position.y)
        self.screen.blit(text_surface, text_rect)

    def show_start_screen(self):
        """Represents a start panel in start screen
        """
        pg.mixer.music.load(SOUNDS_DIR + SOUNDS['intro'])
        pg.mixer.music.play(loops=-1)
        self.screen.fill(BG_COLOR)
        self.draw_text(TITLE, 48, WHITE, Vec(WIDTH / 2, HEIGHT / 4))
        self.draw_text("Click, KeyUP or Space to jump", 22, WHITE,
                       Vec(WIDTH / 2, HEIGHT / 2))
        self.draw_text("Press a key to play", 22, WHITE,
                       Vec(WIDTH / 2, HEIGHT * 3 / 4))
        self.draw_text("High Score: " + str(get_high_score()), 22, WHITE,
                       Vec(WIDTH / 2, 15))
        pg.display.flip()
        self.wait_for_key()
        pg.mixer.music.fadeout(500)

    def show_go_screen(self):
        """Represents game-over and continue screen
        """

        if not self.running:
            return
        pg.mixer.music.load(SOUNDS_DIR + SOUNDS['intro'])
        pg.mixer.music.play(loops=-1)
        self.screen.fill(BG_COLOR)
        self.draw_text("GAME OVER", 48, WHITE, Vec(WIDTH / 2, HEIGHT / 4))
        self.draw_text("Score: " + str(self.score), 22, WHITE,
                       Vec(WIDTH / 2, HEIGHT / 2))
        self.draw_text("Press a key to play again", 22, WHITE,
                       Vec(WIDTH / 2, HEIGHT * 3 / 4))
        high_score = get_high_score()
        if self.score > high_score:
            high_score = self.score
            self.draw_text("NEW HIGH SCORE!", 22, WHITE,
                           Vec(WIDTH / 2, HEIGHT / 2 + 40))
            with open(HS_FILE, 'w') as file:
                file.write(str(high_score))
        else:
            self.draw_text("High Score: " + str(high_score), 22, WHITE,
                           Vec(WIDTH / 2, HEIGHT / 2 + 40))
        pg.display.flip()
        self.wait_for_key()
        pg.mixer.music.fadeout(500)
コード例 #26
0
class WarriorGame(arcade.Window):
    def __init__(self):
        super().__init__(BG_WIDTH, BG_HEIGHT, "WarriorGame")

        self.step_count = 0
        self.playlist = None
        self.gold_text_list = None
        self.health_list = None
        self.coin_list = None
        self.health_symbol_list = None
        self.damage_suffered = None
        self.health = 1
        self.health_2 = 1
        self.wall_list = None

    def on_draw(self):
        arcade.start_render()
        self.show_bg()
        self.gold_text_list.draw()
        self.show_gold_text()
        self.show_health_text()
        self.health_list.draw()
        self.coin_list.draw()
        self.enemy_list.draw()
        self.chest_list.draw()
        self.playlist.draw()
        self.health_symbol_list.draw()
        self.wall_list.draw()

    def start(self):
        self.graphics_init()
        self.health = 0
        for i in range(Player.health_start):
            self.new_life()
        self.gold = 12

        self.health2 = 0
        for i in range(Player.health_start):
            self.health2 += 1
        self.gold2 = 10
        arcade.run()

    def graphics_init(self):
        self.bg_position_x, self.bg_position_y = BG_WIDTH / 2, BG_HEIGHT / 2
        self.bg_picture = arcade.load_texture("img/forest_background.png")

        self.players_sprite_init()
        self.enemy_list_init()
        self.gold_text_sprite_init()
        self.health_sprite_init()
        self.gold_text_list_init()
        self.health_list_init()
        self.coin_list_init()
        self.chest_list_init()
        self.wall_list_init()

    def wall_list_init(self):
        self.wall_list = arcade.SpriteList()
        for w in range(0, 2):
            self.wall_list.append(Wall(8, w))

    def players_sprite_init(self):
        self.playlist = arcade.SpriteList()

        self.player1 = Player(3, 4, self.health)
        self.playlist.append(self.player1)

        self.player2 = Player(5, 3, self.health)
        self.playlist.append(self.player2)

    def enemy_list_init(self):
        self.enemy_list = arcade.SpriteList()
        self.enemy_list.append(Enemy(10, 3, 4, 2))
        self.enemy_list.append(Enemy(14, 2, 3, 1))

    def gold_text_sprite_init(self):
        self.gold_text_sprite = arcade.Sprite("img/Coin1.png")
        self.gold_text_sprite.center_x = FIELD_SIZE / 2
        self.gold_text_sprite.center_y = BG_HEIGHT - 1.5 * FIELD_SIZE

        # Second player gold_sprite:
        self.gold_text_sprite2 = arcade.Sprite("img/Coin1.png")
        self.gold_text_sprite2.center_x = BG_WIDTH - (FIELD_SIZE / 2)
        self.gold_text_sprite2.center_y = BG_HEIGHT - 1.5 * FIELD_SIZE

    def health_sprite_init(self):
        self.health_sprite = arcade.Sprite("img/Heart.png")
        self.health_sprite.center_x = FIELD_SIZE / 2
        self.health_sprite.center_y = BG_HEIGHT - 2.5 * FIELD_SIZE

        # Second player health_sprite:
        self.health_sprite2 = arcade.Sprite("img/Heart.png")
        self.health_sprite2.center_x = BG_WIDTH - (FIELD_SIZE / 2)
        self.health_sprite2.center_y = BG_HEIGHT - 2.5 * FIELD_SIZE

    def gold_text_list_init(self):
        self.gold_text_list = arcade.SpriteList()
        self.gold_text_list.append(self.gold_text_sprite)
        self.gold_text_list.append(self.gold_text_sprite2)

    def health_list_init(self):
        self.health_list = arcade.SpriteList()
        self.health_list.append(self.health_sprite)
        self.health_list.append(self.health_sprite2)

        self.health_symbol_list = arcade.SpriteList()

    def coin_list_init(self):
        self.coin_list = arcade.SpriteList()
        self.coin_list.append(Coin(8, 2, 6))
        self.coin_list.append(Coin(15, 2, 4))

    def show_bg(self):
        arcade.draw_texture_rectangle(self.bg_position_x, self.bg_position_y,
                                      self.bg_picture.width,
                                      self.bg_picture.height, self.bg_picture)

    def chest_list_init(self):
        self.chest_list = arcade.SpriteList()
        self.chest_list.append(Chest(10, 4, ["sword", "shield"], True))
        self.chest_list.append(Chest(19, 2, ["axe"], False))
        self.chest_list.append(Chest(15, 3, ["arrow"], True))
        self.chest_list.append(Chest(17, 1, [], True))

    def show_gold_text(self):
        arcade.draw_text(str(self.gold), FIELD_SIZE,
                         BG_HEIGHT - 2 * FIELD_SIZE, arcade.color.WHITE, 30)

        #Second player's gold_text:
        arcade.draw_text(str(self.gold2), BG_WIDTH - FIELD_SIZE * 2.5,
                         BG_HEIGHT - 2 * FIELD_SIZE, arcade.color.WHITE, 30)

    def show_health_text(self):
        arcade.draw_text(str(self.health), FIELD_SIZE,
                         BG_HEIGHT - 3 * FIELD_SIZE, arcade.color.YELLOW, 30)

        # Second player's health_text:
        arcade.draw_text(str(self.health2), BG_WIDTH - FIELD_SIZE * 2.5,
                         BG_HEIGHT - 3 * FIELD_SIZE, arcade.color.YELLOW, 30)

    def move_player_1(self, button):
        if button == arcade.key.LEFT:
            if self.player1.center_x > LEFT_CORRIDOR:
                self.player1.player_to_left(self.wall_list)

        elif button == arcade.key.RIGHT:
            if button == arcade.key.RIGHT:
                if self.player1.center_x < RIGHT_CORRIDOR:
                    self.player1.player_to_right(self.wall_list)

        elif button == arcade.key.UP:
            if self.player1.center_y < UPPER_CORRIDOR:
                self.player1.player_to_up(self.wall_list)

        elif button == arcade.key.DOWN:
            if self.player1.center_y > BOTTOM_CORRIDOR:
                self.player1.player_to_down(self.wall_list)


#Second player's movement:

    def move_player_2(self, button):
        if button == arcade.key.A:
            if self.player2.center_x > LEFT_CORRIDOR:
                self.player2.player_to_left(self.wall_list)

        elif button == arcade.key.D:
            if button == arcade.key.D:
                if self.player2.center_x < RIGHT_CORRIDOR:
                    self.player2.player_to_right(self.wall_list)

        elif button == arcade.key.W:
            if self.player2.center_y < UPPER_CORRIDOR:
                self.player2.player_to_up(self.wall_list)

        elif button == arcade.key.S:
            if self.player2.center_y > BOTTOM_CORRIDOR:
                self.player2.player_to_down(self.wall_list)

    def on_key_press(self, pushed_button, modifier):
        self.move_player_1(pushed_button)
        self.move_player_2(pushed_button)

    def on_mouse_press(self, x, y, button, modifier):
        print("You are in a freakin' forest :)")

    def update(self, delata_time):
        # Coin acquisition:
        acquired_coins = arcade.check_for_collision_with_list(
            self.player1, self.coin_list)
        for coin in acquired_coins:
            coin.kill()
            self.gold += coin.gold_value
            Coin.counter -= 1

        acquired_coins2 = arcade.check_for_collision_with_list(
            self.player2, self.coin_list)
        for coin in acquired_coins2:
            coin.kill()
            self.gold2 += coin.gold_value
            Coin.counter -= 1

        #Battle:
        enemy_in_battle = arcade.check_for_collision_with_list(
            self.player1, self.enemy_list)

        for enemy in enemy_in_battle:
            chance = randint(1, 2)
            if chance == 1:
                self.lost_life()
                self.player1.center_x -= FIELD_SIZE * 2
            else:
                self.new_life()
                enemy.kill()

        enemy_in_battle2 = arcade.check_for_collision_with_list(
            self.player2, self.enemy_list)
        for enemy in enemy_in_battle2:
            chance = randint(1, 2)
            if chance == 1:
                self.health2 -= 1
                self.player2.center_x -= FIELD_SIZE * 2
            else:
                self.health2 += 1
                enemy.kill()

        #Chest operations:
        chest_opened = arcade.check_for_collision_with_list(
            self.player1, self.chest_list)

        for chest in chest_opened:
            if chest.open_status == True:
                if bool(chest.objects) != False:
                    loot = ", ".join(chest.objects)
                    self.player1.loot += chest.loot_to_player()
                    print("Player 1 looted:", chest.objects)
                    chest.objects = []
            else:
                if chest.chest_message_player_1 == 0:
                    print("Player 1: Sorry, the chest is closed :(")
                    chest.chest_message_player_1 = 1
                else:
                    pass

        chest_opened2 = arcade.check_for_collision_with_list(
            self.player2, self.chest_list)

        for chest in chest_opened2:
            if chest.open_status == True:
                if bool(chest.objects) != False:
                    loot = ", ".join(chest.objects)
                    self.player2.loot += chest.loot_to_player()
                    print("Player 2 looted:", chest.objects)
                    chest.objects = []
            else:
                if chest.chest_message_player_2 == 0:
                    print("Player 2: Sorry, the chest is closed :(")
                    chest.chest_message_player_2 = 1
                else:
                    pass

        #Game Over:

        if self.player1.health <= 0 or self.player2.health <= 0 or Coin.counter == 0:
            print("GAME OVER")
            if bool(self.player1.loot) != False:
                print("Player 1 looted:", ", ".join(self.player1.loot) + ".")
            print("Player 1 gold:", self.gold)

            if bool(self.player2.loot) != False:
                print("Player 2 looted:", ", ".join(self.player2.loot) + ".")
            print("Player 2 gold:", self.gold2)
            self.close()

    def new_life(self):
        new_life_sprite = arcade.Sprite("img/Heart.png")
        new_life_sprite.center_x = self.health * FIELD_SIZE + FIELD_SIZE / 2
        new_life_sprite.center_y = BG_HEIGHT - FIELD_SIZE / 2
        self.health_symbol_list.append(new_life_sprite)
        self.health += 1

    def lost_life(self):
        lost_health = self.health_symbol_list[self.health - 1]
        lost_health.kill()
        self.health -= 1
コード例 #27
0
def main():
    """this function is called when the program starts.
       it initializes everything it needs, then runs in
       a loop until the function returns."""

    # Initialize Everything
    pg.mixer.init()
    pg.init()
    screen = pg.display.set_mode((screen_width, screen_height))
    pg.display.set_caption("Bullet Helln't")
    pg.mouse.set_visible(0)

    # Create The Background
    bg = pg.image.load("art/background/background.png")
    bg_offset = 0

    # Display The Background
    screen.blit(bg, (0, 0))
    # pg.display.flip()

    #
    pg.mixer.music.load('sound/music.wav')
    pg.mixer_music.play(-1)

    # Prepare Game Objects
    clock = pg.time.Clock()
    potion_list = []
    player = Player(screen_width, screen_height, potion_list)
    hud = HUD(player)
    inv = Inventory(player)

    invisible_top_wall = Wall(0, -35, screen_width, 10)
    invisible_bottom_wall = Wall(0, screen_height + 25, screen_width, 10)
    invisible_left_wall = Wall(-35, 0, 10, screen_height)
    invisible_right_wall = Wall(screen_width + 25, 0, 10, screen_height)
    top_wall = Wall(0, 0, screen_width, 10)
    bottom_wall = Wall(0, screen_height - 10, screen_width, 10)
    left_wall = Wall(0, 0, 10, screen_height)
    right_wall = Wall(screen_width - 10, 0, 10, screen_height)
    walls = pg.sprite.RenderPlain(top_wall, bottom_wall, left_wall, right_wall)
    collision_walls = pg.sprite.RenderPlain(invisible_top_wall,
                                            invisible_bottom_wall,
                                            invisible_left_wall,
                                            invisible_right_wall)
    allsprites = pg.sprite.RenderPlain(player, walls, collision_walls, hud,
                                       inv)
    player.walls = collision_walls.sprites()

    bullet_list = []

    enemy_list = []
    for enemy in enemy_list:
        allsprites.add(enemy)

    # Tracker
    item_count = defaultdict(lambda: 0)

    # Tracker specifically for special potion; and whether player holds it
    bomb_inuse = False
    bomb_counter = 0
    bomb_delay = 330

    # Shows the introduction screen
    story = "THE STORY SO FAR:"
    story2 = "In a world filled with swords, you are a superhero with a bow."
    story3 = "Swing your bow, kill enemies and eliminate swords."
    story4 = "Pick up health and a special potion along the way to make swords disappear!"
    story5 = "<TAB> to begin."

    start_game = False
    while not start_game:
        font = pygame.font.SysFont("Arial", 24)
        text = font.render(story, 1, (0, 0, 0))
        text2 = font.render(story2, 1, (0, 0, 0))
        text3 = font.render(story3, 1, (0, 0, 0))
        text4 = font.render(story4, 1, (0, 0, 0))
        text5 = font.render(story5, 1, (0, 0, 0))

        text_pos = text.get_rect(centerx=screen.get_width() / 2, centery=100)
        text_pos2 = text2.get_rect(centerx=screen.get_width() / 2, centery=200)
        text_pos3 = text3.get_rect(centerx=screen.get_width() / 2, centery=300)
        text_pos4 = text4.get_rect(centerx=screen.get_width() / 2, centery=400)
        text_pos5 = text5.get_rect(centerx=screen.get_width() / 2, centery=500)

        screen.blit(text, text_pos)
        screen.blit(text2, text_pos2)
        screen.blit(text3, text_pos3)
        screen.blit(text4, text_pos4)
        screen.blit(text5, text_pos5)

        pg.display.flip()

        for event in pg.event.get():
            if event.type == pg.QUIT:
                quit()
            if event.type == pg.KEYDOWN and event.key == pg.K_TAB:
                start_game = True
            else:
                continue

    # Main Loop
    going = True
    while going:
        # print(item_count[Enemy], item_count[Enemy2], item_count[Potion])

        # draw two backgrounds, slowly moving down
        screen.blit(bg, (0, bg_offset))
        screen.blit(bg, (0, bg_offset - screen_height))
        if bg_offset < screen_height:
            bg_offset += 1
        else:  # once offset goes off the screen, reset it
            bg_offset = 0

        for event in pg.event.get():
            if event.type == pg.QUIT:
                going = False

            # player attack
            if event.type == pg.KEYDOWN and event.key == pg.K_SPACE:
                player.start_attack()

            # player bomb
            if player.bomb_ready and event.type == pg.KEYDOWN and event.key == pg.K_c:
                pg.mixer.Sound('sound/tactical-nuke.wav').play()
                bomb_inuse = True
                player.bomb_ready = False

        if bomb_inuse:
            if bomb_counter < bomb_delay:
                bomb_counter += 1
            else:
                player.bomb_count = 0
                print("BOOM")
                bomb_inuse = False
                bomb_counter = 0

                # remove all bullets
                for bullet in bullet_list:
                    bullet.kill()
                bullet_list.clear()
                allsprites.remove(bullet_list)

                # remove all enemies?
                for enemy in enemy_list:
                    enemy.kill()
                enemy_list.clear()
                allsprites.remove(enemy_list)
                item_count[Enemy] = 0
                item_count[Enemy2] = 0

        if random.random() < chance_spawn(item_count[Potion]):
            potion = Potion(screen_width, screen_height)
            potion_list.append(potion)
            allsprites.add(potion)
            item_count[Potion] = item_count[Potion] + 1

        if random.random() < chance_spawn(item_count[Enemy]):
            enemy = Enemy(screen_width, screen_height)
            enemy_list.append(enemy)
            allsprites.add(enemy)
            item_count[Enemy] = item_count[Enemy] + 1

        if item_count[Enemy2] <= 5 and random.random() < chance_spawn(
                item_count[Enemy2]):
            enemy = Enemy2(screen_width, screen_height)
            enemy_list.append(enemy)
            allsprites.add(enemy)
            item_count[Enemy2] = item_count[Enemy2] + 1

        # a special potion; if you need to collect 4, may as well have them spawn randomly
        if random.random() < 0.003:
            potion = Potion2(screen_width, screen_height)
            potion_list.append(potion)
            allsprites.add(potion)

        # update player (movement, attack frame, health)
        if not player.update():
            end_screen(screen, bg, player)

        if clock.get_time() % 5:
            for enemy in enemy_list:
                if player.attack and player.attack_box.colliderect(
                        enemy.hurtbox):
                    enemy.kill_enemy(player)
                    enemy_list.remove(enemy)

                    if isinstance(enemy, Enemy):
                        item_count[Enemy] = item_count[Enemy] - 1
                    elif isinstance(enemy, Enemy2):
                        item_count[Enemy2] = item_count[Enemy2] - 1
                    allsprites.remove(
                        enemy
                    )  # TODO: Make enemies stay a while before being removed

                if player.hurtbox.colliderect(enemy.hurtbox):
                    if player.damage_cooldown == 0:
                        player.get_hurt()

                # remove if off screen; after calling 'implode' first on Enemy though
                if enemy.rect.y + 50 > screen_height:
                    if isinstance(enemy, Enemy):
                        bullets = enemy.implode(player.rect.x, screen_height)
                        for bullet in bullets:
                            bullet_list.append(bullet)
                            allsprites.add(bullet)

                    if isinstance(enemy, Enemy):
                        item_count[Enemy] = item_count[Enemy] - 1
                    elif isinstance(enemy, Enemy2):
                        item_count[Enemy2] = item_count[Enemy2] - 1

                    allsprites.remove(enemy)
                    enemy_list.remove(enemy)
                    enemy.kill()

                # get each enemy to go through a 'shoot' cycle; returns None if no bullet generated
                # bullet = None
                # if isinstance(enemy, Enemy):
                bullet = enemy.shoot(player.rect.x, player.rect.y)
                # elif isinstance(enemy, Enemy2):
                #     bullet = enemy.shoot(player.h)
                if bullet:
                    bullet_list.append(bullet)
                    allsprites.add(bullet)

            for bullet in bullet_list:
                remove = False
                # bigger hitbox collides with player attack
                if player.attack and player.attack_box.colliderect(
                        bullet.rect):
                    remove = True
                # smaller hitbox collides with player
                elif player.hurtbox.colliderect(bullet.hurtbox):
                    if player.damage_cooldown == 0:
                        player.get_hurt()
                    remove = True
                # off screen; add 20 to coordinates to centre it (knife is 40x40 px)
                elif bullet.rect.x + 20 < 10 or bullet.rect.x + 20 > screen_width - 10 \
                        or bullet.rect.y + 20 < 10 or bullet.rect.y + 20 > screen_height - 10:
                    remove = True

                # cheeky bodge: homing
                if isinstance(bullet, Knife2):
                    xdist = abs(player.rect.x - bullet.rect.x)
                    if bullet.rect.x + 40 < player.rect.x + 50 - 20:
                        bullet.true_x += bullet.xspeed * xdist
                    elif bullet.rect.x + 40 > player.rect.x + 50 + 20:
                        bullet.true_x -= bullet.xspeed * xdist

                if remove:
                    bullet_list.remove(bullet)
                    allsprites.remove(bullet)
                    bullet.kill()

            # remove potions going off screen
            for potion in potion_list:
                if potion.rect.y > screen_height - 30:
                    if isinstance(potion, Potion2):
                        potion2_present = False
                    allsprites.remove(potion)
                    item_count[Potion] = item_count[Potion] - 1
                    potion_list.remove(potion)
                    potion.kill()

        # draw
        allsprites.update()

        # Draw Everything
        allsprites.draw(screen)
        # text_surface = score_text.generate_surface('Health: ')
        # screen.blit(text_surface,
        #             (screen_width - text_surface.get_width() - 100, screen_height - text_surface.get_height() - 45))
        pg.display.flip()

        clock.tick(60)

    pg.quit()
コード例 #28
0
class Game:
    def __init__(self, display):
        self.display = display
        self.clock = pg.time.Clock()
        pg.display.set_caption(WINDOW_TITLE)

        self.joysticks = [
            pg.joystick.Joystick(x) for x in range(pg.joystick.get_count())
        ]
        self.joystick = None
        if len(self.joysticks) > 0:
            self.joystick = self.joysticks[0]
            self.joystick.init()

        # sprite groups
        self.all_sprites = None
        self.items_on_floor = None
        self.solid = None
        self.doors = None

        self.background_surface = None
        self.triggers = []
        self.collisions = []  # rectangles
        self.spritesheet = None
        self.map = None
        self.player = None
        self.camera = None
        self.playing = False
        self.dt = 0.0
        self.global_time = 0
        self.pressed_keys = {}
        self.keys_just_pressed = {}
        self.joystick_just_pressed = {}

        self.gui = Nanogui(display)
        self.visibility_data = None  # [x][y] -> True, False
        self.fov_data = None  # [x][y] -> True, False
        self.update_fov = True
        self.light_map = []

    def load(self):
        self.all_sprites = pg.sprite.Group()
        self.solid = pg.sprite.Group()
        self.items_on_floor = pg.sprite.Group()
        self.doors = pg.sprite.Group()

        assets_folder = path.join(getcwd(), 'assets')
        self.map = Map(path.join(assets_folder, 'maps/map1.json'))

        self.spritesheet = Spritesheet(
            path.join(assets_folder, 'spritesheet.png'), 32)
        wall_img = self.spritesheet.get_image_at_col_row(0, 0)
        apple_img = self.spritesheet.get_image_alpha_at_col_row(1, 0)
        keycard_img = self.spritesheet.get_image_alpha_at_col_row(0, 3)
        self.background_surface = pg.Surface(
            (self.map.width * TILE_SIZE, self.map.height * TILE_SIZE))

        self.visibility_data = [[True] * self.map.height
                                for i in range(self.map.width)]
        self.fov_data = [[True] * self.map.height
                         for i in range(self.map.width)]

        for node in self.map.objects:
            x, y = node['x'], node['y']
            if node["name"] == 'WALL':
                #self.collisions.append(pg.Rect(x, y, TILE_SIZE, TILE_SIZE))  # TODO big rectangles
                wall = Wall(self, x, y, wall_img)
                if not LIMIT_FOV_FOR_STATIC_SPRITES:
                    wall.remove(self.all_sprites)  # skip drawing
                    self.background_surface.blit(
                        wall_img, (x * TILE_SIZE, y * TILE_SIZE))
                self.visibility_data[x][y] = False
            elif node["name"] == 'PLAYER':
                self.player = Player(self, x, y)
            elif node["name"] == 'APPLE':
                item = Item(self, x, y, apple_img)
                item.pickable = Pickable(item, 'apple', False, 1, False)
            elif node["name"] == 'KEYCARD':  # key card
                item = Item(self, x, y, keycard_img)
                item.pickable = Pickable(item, 'keycard', False, 1, False)
            elif node["name"] == "DOOR":
                Door(self, x, y, node["dir"])
                self.visibility_data[x][
                    y] = False  # TODO opened doors visibility

        for trigger in self.map.triggers:
            TextTrigger(
                self,
                pg.Rect(trigger["x"], trigger["y"], trigger["width"],
                        trigger["height"]), trigger["text"])

        self.camera = Camera(self.map.width_screen, self.map.height_screen)

    def update(self):
        self.gui.pre(self.joystick)

        if not message.Message.messages:
            self.player.update(self.dt)
        message.update(self)

        camera_updated = self.camera.update(self.player)
        if self.update_fov:
            player_hit_rect = self.player.hit_rect
            player_tilex = math.floor(player_hit_rect.x / TILE_SIZE)
            player_tiley = math.floor(player_hit_rect.y / TILE_SIZE)

            self.fov_data = calc_fov(player_tilex, player_tiley, FOV_RADIUS,
                                     self.visibility_data, self.fov_data)
            self.update_light_map(self.player.x, self.player.y)
            self.update_fov = False

        self.gui.after()

    def draw(self):
        self.display.fill(BG_COLOR)

        bg_x, bg_y = self.camera.transform_xy(0, 0)
        self.display.blit(self.background_surface, (bg_x, bg_y))

        # TODO layering
        if not LIMIT_FOV_FOR_STATIC_SPRITES:
            for sprite in self.all_sprites:
                if sprite != self.player and not isinstance(sprite, Item):
                    self.display.blit(sprite.image,
                                      self.camera.transform(sprite))

        if LIMIT_FOV_FOR_STATIC_SPRITES:
            fov_group = self.all_sprites
        else:
            fov_group = self.items_on_floor
        for sprite in fov_group:
            tilex = math.floor(sprite.x)
            tiley = math.floor(sprite.y)
            if sprite != self.player:
                if self.fov_data[tilex][tiley]:
                    self.display.blit(sprite.image,
                                      self.camera.transform(sprite))

        # darken image
        self.display.fill(DARKEN_COLOR, special_flags=pg.BLEND_SUB)
        # draw light
        for light in self.light_map:
            self.display.fill(light[1], light[0], pg.BLEND_ADD)

        if DEBUG_FOV:
            self.draw_fov()

        self.display.blit(self.player.image,
                          self.camera.transform(self.player))
        if message.Message.messages:
            message.Message.messages[0].render(self.display)

            #self.__put_text_on_screen(str(messages))
            #if messages.has_picture():
            #    self.__put_picture_on_screen__(messages.get_picture())

        self.gui.draw()
        pg.display.flip()

    def __put_picture_on_screen(self, image):
        self.display.blit(image, (SCREEN_WIDTH // 2, SCREEN_HEIGHT // 2))

    def run(self):
        self.playing = True
        while self.playing:
            self.dt = self.clock.tick(FPS) / 1000
            self.global_time += self.dt
            self.events()
            self.update()
            self.draw()

    def quit(self):
        pg.quit()
        sys.exit()

    def events(self):
        self.keys_just_pressed.clear()
        self.joystick_just_pressed.clear()

        self.pressed_keys = pg.key.get_pressed()
        for event in pg.event.get():
            if event.type == pg.QUIT:
                self.quit()
            if event.type == pg.KEYDOWN:
                self.keys_just_pressed[event.key] = True
                if event.key == pg.K_ESCAPE:
                    self.quit()
                if event.key == pg.K_F11:
                    self.toggle_fullscreen()
            if event.type == pg.JOYBUTTONDOWN:
                self.joystick_just_pressed[event.button] = True

    def toggle_fullscreen(self):
        """Taken from http://pygame.org/wiki/toggle_fullscreen"""

        screen = pg.display.get_surface()
        tmp = screen.convert()
        caption = pg.display.get_caption()
        cursor = pg.mouse.get_cursor()

        w, h = screen.get_width(), screen.get_height()
        flags = screen.get_flags()
        bits = screen.get_bitsize()

        pg.display.quit()
        pg.display.init()

        self.display = pg.display.set_mode((w, h), flags ^ pg.FULLSCREEN, bits)
        self.display.blit(tmp, (0, 0))
        pg.display.set_caption(*caption)

        pg.key.set_mods(0)

        pg.mouse.set_cursor(*cursor)

        return screen

    def get_vbutton_down(self, name):
        if name in V_BUTTONS:
            for key in V_BUTTONS[name]:
                if self.pressed_keys[key]:
                    return True
        return False

    def get_vbutton_jp(self, name):
        if name in V_BUTTONS:
            for key in V_BUTTONS[name]:
                if key in self.keys_just_pressed:
                    return True
        return False

    def get_key_jp(self, key):
        # get key just pressed (clears on new frame)
        if key in self.keys_just_pressed:
            return True
        return False

    def get_joystick_jp(self, button):
        # get joystick button just pressed (clears on new frame)
        if button in self.joystick_just_pressed:
            return True
        return False

    def get_axis(self, number):
        if self.joystick is not None:
            return self.joystick.get_axis(number)
        return 0.0

    def set_visibility(self, tilex, tiley, value):
        self.visibility_data[tilex][tiley] = value
        self.update_fov = True

    def draw_fov(self):
        for x in range(len(self.fov_data)):
            for y in range(len(self.fov_data[0])):
                if self.fov_data[x][y]:
                    newx, newy = self.camera.transform_xy(
                        x * TILE_SIZE, y * TILE_SIZE)
                    pg.draw.rect(self.display, (200, 200, 200),
                                 pg.Rect(newx, newy, TILE_SIZE, TILE_SIZE), 1)

    def update_light_map(self, source_x, source_y):
        self.light_map.clear()
        radius_sqr = FOV_RADIUS * FOV_RADIUS
        tmp = 1.0 / (1.0 + radius_sqr)

        for x in range(len(self.fov_data)):
            for y in range(len(self.fov_data[0])):
                if self.fov_data[x][y]:
                    newx, newy = self.camera.transform_xy(
                        x * TILE_SIZE, y * TILE_SIZE)

                    dist_sqr = (source_x - x) * (source_x - x) + (
                        source_y - y) * (source_y - y)
                    intensity = 1.0 / (1.0 + dist_sqr / 20)
                    intensity = intensity - tmp
                    intensity = intensity / (1.0 - tmp)
                    color = tuple(intensity * v for v in LIGHT_COLOR)
                    self.light_map.append((pg.Rect(newx, newy, TILE_SIZE,
                                                   TILE_SIZE), color))