def _setup(self): self.SCREEN_WIDTH = 80 self.SCREEN_HEIGHT = 50 self.LIMIT_FPS = 20 tdl.set_font('arial10x10.png', greyscale=True, altLayout=True) self.root = tdl.init(self.SCREEN_WIDTH, self.SCREEN_HEIGHT, title='AsciiRPG', fullscreen=False) tdl.setFPS(self.LIMIT_FPS) # Create an offscreen console self.console = tdl.Console(self.SCREEN_WIDTH, self.SCREEN_HEIGHT) # Map self.map = Map() self.map.create(self.SCREEN_HEIGHT, self.SCREEN_WIDTH) try: player_y = 1 player_x = 1 while self.map.tiles[player_y][player_x].blocked: player_y = randint(0, self.map.WIDTH - 1) player_x = randint(0, self.map.HEIGHT - 1) except: print("out of range") # Spawn player, first specify Y (which of the top tiles to start at), then X (which of the horizontal tiles to start at) self.player = Player(player_y, player_x, (255,255,255)) #self.cat = Cat(self.SCREEN_WIDTH + 4, self.SCREEN_HEIGHT, (255,255,255)) self.entities = [self.player]
def play(self): if self.player is None: self.score = 0 self.player = Player(self.sprites) self.sprites.add(self.player) self.draw_score() self.sound_service.play_soundtrack('game_soundtrack.ogg') self.window_service.load_background('space.jpg') return GameStatus.GAME_START
def __init__(self, playerName="Player"): """ Constructor that initializes instance variables :param PlayerName: name of the player """ self._player = Player(name=playerName) self._player.add_observer(self) self._playerLoc = (0, 0) self._neighborhood = Neighborhood() self._isPlaying = True
def spawn_player(self): """ Spawns player onto the map """ # Add Sprites to group # Place player where spawn tile is, searching from bottom left first self.player = None spawned_player = False for i in range(0, GameMap.map_data.width): for j in range(GameMap.map_data.height - 1, -1, -1): tile_property = GameMap.get_tile_properties(i, j) if tile_property and tile_property.get(MapInfo.SPAWN.value): spawned_player = True print('in: ' + str((i, j))) spawn_point_x = i * GameMap.map_data.tilewidth + ( GameMap.map_data.tilewidth / 2) spawn_point_y = j * GameMap.map_data.tileheight print('spawn: ' + str((spawn_point_x, spawn_point_y))) self.player = Player(position=(spawn_point_x, spawn_point_y)) print('body: ' + str(self.player.rect)) if spawned_player: break if spawned_player: break self.group.add(self.player)
def parse_players(self): try: dict_list = self.gen_dict["Data"]["Player"] for dict_item in dict_list: new_object = Player(dict_item, world_id=self.world_id) self.data["player"][new_object.id] = new_object except KeyError: pass
def create_player(self): player_number = len(self.app.game_controller.players) player = Player(name=f"Player {player_number + 1}") self.app.game_controller.players.append(player) player_button = Button(self.frame, text=player.name, bg="#303030", fg="#ffffff", command=lambda player_number=player_number: self .switch_player(player_number)) self.player_buttons.append(player_button) player_button.grid(column=player_number + 2, row=0)
def init_entities(self, entities): for key in entities.keys(): if key == "players": for player in entities[key]: column = player['x'] row = player['y'] pos = (self.world[row][column], player['width'], player['height']) player = Player(*pos, 255, player['id'], self.tile_size) self.entities.append(player) elif key == 'balls': for ball in entities[key]: column = ball['x'] row = ball['y'] pos = (self.world[row][column], ball['width'], ball['height']) ball = Ball(*pos, 100, self.tile_size) self.entities.append(ball)
def _get_alliance_ids(self): player_id = self.account.header_info['playerID'] for player in self.account.login_result["Data"]["Player"]: if player["id"] == player_id: player_dict = player break else: self.logger.warning(self.account, "get_alliance_ids", "Player is not in the info with players, consider loading by request") return [] player = Player(player_dict, "202") if not player.alliance: self.logger.warning(self.account, "get_alliance_ids", "Player has not alliance") return [] for alliance in self.account.login_result["Data"]["Alliance"]: if alliance["id"] == player.alliance: this_player_alliance = Alliance(alliance, "202") break this_player_alliance.extract_diplomacy(self.account.login_result["Data"]["Diplomacy"]) return this_player_alliance.get_diplomacy_by_color("orange") + [this_player_alliance.id]
from Entities.Entity import Entity from Entities.Player import Player A = Player(1, 100, "Player", (50, 50), [], 5, None, None, [], 0) B = Entity(1, 50, "Undead", (50, 51), [], 5, None, None, [(None, 100)], 1000)
class Game: def __init__(self): self._setup() self._gameloop() def _setup(self): self.SCREEN_WIDTH = 80 self.SCREEN_HEIGHT = 50 self.LIMIT_FPS = 20 tdl.set_font('arial10x10.png', greyscale=True, altLayout=True) self.root = tdl.init(self.SCREEN_WIDTH, self.SCREEN_HEIGHT, title='AsciiRPG', fullscreen=False) tdl.setFPS(self.LIMIT_FPS) # Create an offscreen console self.console = tdl.Console(self.SCREEN_WIDTH, self.SCREEN_HEIGHT) # Map self.map = Map() self.map.create(self.SCREEN_HEIGHT, self.SCREEN_WIDTH) try: player_y = 1 player_x = 1 while self.map.tiles[player_y][player_x].blocked: player_y = randint(0, self.map.WIDTH - 1) player_x = randint(0, self.map.HEIGHT - 1) except: print("out of range") # Spawn player, first specify Y (which of the top tiles to start at), then X (which of the horizontal tiles to start at) self.player = Player(player_y, player_x, (255,255,255)) #self.cat = Cat(self.SCREEN_WIDTH + 4, self.SCREEN_HEIGHT, (255,255,255)) self.entities = [self.player] def _render(self): self.map.render(self.console) for entity in self.entities: entity.render(self.console) def _gameloop(self): while not tdl.event.isWindowClosed(): self._render() self.root.blit(self.console, 0, 0, self.SCREEN_WIDTH, self.SCREEN_HEIGHT, 0, 0) tdl.flush() # present changes to the screen for entity in self.entities: entity.clear(self.console) #handle keys and exit game if needed exit = self._handle_keys() if exit: break def _handle_keys(self): user_input = tdl.event.key_wait() if user_input.key == 'ENTER' and user_input.alt: # Alt+Enter: toggle fullscreen tdl.set_fullscreen(not tdl.get_fullscreen()) elif user_input.key == '0': return True # exit game if user_input.key == 'KP8': if self._is_legal_move(0, -1): self.player.move(0, -1) elif user_input.key == 'KP9': if self._is_legal_move(1, -1): self.player.move(1, -1) elif user_input.key == 'KP6': if self._is_legal_move(1, 0): self.player.move(1, 0) elif user_input.key == 'KP3': if self._is_legal_move(1, 1): self.player.move(1, 1) elif user_input.key == 'KP2': if self._is_legal_move(0, 1): self.player.move(0, 1) elif user_input.key == 'KP1': if self._is_legal_move(-1, 1): self.player.move(-1, 1) elif user_input.key == 'KP4': if self._is_legal_move(-1, 0): self.player.move(-1, 0) elif user_input.key == 'KP7': if self._is_legal_move(-1, -1): self.player.move(-1, -1) elif user_input.key == 'KP5': print(str(self.player.x) + ', ' + str(self.player.y)) def _is_legal_move(self, x, y): return False if self.map.tiles[add(self.player.x, x)][add(self.player.y, y)].blocked else True
def init_ui(self): self.init_window() self.init_aliens() self.init_shield() if self.player_spacecraft == "SILVER_X 177p": self.player1 = Player(self, 'images/silver.png', cfg.PLAYER_START_X, cfg.PLAYER_START_Y, cfg.SPACESHIP_WIDTH, cfg.SPACESHIP_HEIGHT, self.player_id, 3) elif self.player_spacecraft == "purpleZ AAx9": self.player1 = Player(self, 'images/purple.png', cfg.PLAYER_START_X, cfg.PLAYER_START_Y, cfg.SPACESHIP_WIDTH, cfg.SPACESHIP_HEIGHT, self.player_id, 3) elif self.player_spacecraft == "military-aircraft-POWER": self.player1 = Player(self, 'images/military.png', cfg.PLAYER_START_X, cfg.PLAYER_START_Y, cfg.SPACESHIP_WIDTH, cfg.SPACESHIP_HEIGHT, self.player_id, 3) else: self.player1 = Player(self, 'images/spacex.png', cfg.PLAYER_START_X, cfg.PLAYER_START_Y, cfg.SPACESHIP_WIDTH, cfg.SPACESHIP_HEIGHT, self.player_id, 3) if self.multiplayer_mode: if self.player2_spacecraft == "SILVER_X 177p": self.player2 = Player(self, 'images/silver.png', cfg.PLAYER2_START_X, cfg.PLAYER_START_Y, cfg.SPACESHIP_WIDTH, cfg.SPACESHIP_HEIGHT, self.player2_id, 3) elif self.player2_spacecraft == "purpleZ AAx9": self.player2 = Player(self, 'images/purple.png', cfg.PLAYER2_START_X, cfg.PLAYER_START_Y, cfg.SPACESHIP_WIDTH, cfg.SPACESHIP_HEIGHT, self.player2_id, 3) elif self.player2_spacecraft == "military-aircraft-POWER": self.player2 = Player(self, 'images/military.png', cfg.PLAYER2_START_X, cfg.PLAYER_START_Y, cfg.SPACESHIP_WIDTH, cfg.SPACESHIP_HEIGHT, self.player2_id, 3) elif self.player2_spacecraft == "SpaceX-air4p66": self.player2 = Player(self, 'images/spacex.png', cfg.PLAYER2_START_X, cfg.PLAYER_START_Y, cfg.SPACESHIP_WIDTH, cfg.SPACESHIP_HEIGHT, self.player2_id, 3) else: self.winner = self.player1 self.players.append(self.player1) self.deus_ex.add_player(self.player1.avatar) self.shield_destruct.add_player(self.player1.avatar) if self.multiplayer_mode: self.players.append(self.player2) self.deus_ex.add_player(self.player2.avatar) self.shield_destruct.add_player(self.player2.avatar) self.labels()
class Game(Observer): """ A simple class that hold the player and the Neighborhood and provides functionality to interact with them """ def __init__(self, playerName="Player"): """ Constructor that initializes instance variables :param PlayerName: name of the player """ self._player = Player(name=playerName) self._player.add_observer(self) self._playerLoc = (0, 0) self._neighborhood = Neighborhood() self._isPlaying = True def receiveUpdate(self, info=None): """ override abstract method from Observer. when an update is recieved the player has died so end the game :param info: info to process """ self._isPlaying = False def getStatus(self): """ :return: if the game is still going """ return self._isPlaying def getPlayer(self): """ :return: the player of the game """ return self._player def getNeighborhood(self): """ :return: the neighborhood of the game """ return self._neighborhood def getPlayerLoc(self): """ :return: the players location in (x, y) """ return self._playerLoc def move(self, dir): """ move the player. must be a valid move(1 square away including diagonals) :param dir: direction to move in a tuple of length 2 with values of -1 to 1 :return: True if move was successful or False if it was not. """ # if the game is over return if not self._isPlaying: return False # valid values for moves valid = [-1, 0, 1] # if the direction is in the valid range calculat the new location if dir[0] in valid and dir[1] in valid: newLoc = (self._playerLoc[0] + dir[0], self._playerLoc[1] + dir[1]) # if the new location is in bounds move player and return true if self._neighborhood.inBounds(newLoc): self._playerLoc = newLoc return True # otherwise return false return False def attackHouse(self, loc, weaponNum): """ helper function that tells the player to attack all the monsters in a house :param loc: houses position in tuple :param weaponNum: weapon id to use """ # if game is over return if not self._isPlaying: return # give the player the monsters from the house to attack self._player.attackAll(self._neighborhood.getHouse(loc), weaponNum) # tell the monsters in the house to attack the player back self._neighborhood.getHouse(loc).dealDamage(self._player) if self.getNeighborhood().isClear(): self._isPlaying = False
class Game(QMainWindow): def __init__(self, player_id: str, player_spacecraft: str, player2_id: str = "", player2_spacecraft: str = ""): super().__init__() self.player_id = player_id self.player_spacecraft = player_spacecraft self.player2_id = player2_id self.player2_spacecraft = player2_spacecraft self.players = [] self.winner = 0 self.multiplayer_mode = False self.tournament_mode = False if not self.player2_id == "": self.multiplayer_mode = True self.total_point = 0 self.total_point2 = 0 self.current_level = 0 self.current_lives = 0 self.max_player_score = 0 self.max_hiscore = [] self.player = "" self.broj = 0 self.queue1 = Queue() self.deus_ex_proc = CalculateDeusExX(self.queue1) self.deus_ex_proc.start() # arch self.mynumbers = [] self.powers = [] self.bullets = [] self.bullets_enemy = [] self.aliens = [] self.remove_aliens = [] self.shields = [] self.shootingThread = ShootBullet() self.alien_movement_thread = AlienMovement() self.alien_attack_thread = AlienAttack() self.alien_shoot_bullet_thread = BulletMove() self.collision_bullet_alien = CollisionPlayerBullet() self.key_notifier = KeyNotifier() self.shield_destruct = CollisionAlienBullet() self.deus_ex = DeusEx() self.level_handle = NextLevel() self.deus_ex_worker = Worker(self.queue1) self.status_bar = StatusBar() self.player_explosion = PlayerExplosion() self.threads_connect() self.start_threads() self.init_ui() # logika za citanje najboljeg rezultata file = open("players.txt", "r") lines = file.readlines() for line in lines: self.mynumbers.append(str(n) for n in line.strip().split(" ")) for a, b in self.mynumbers: self.max_hiscore.append(int(b)) for i in range(len(self.max_hiscore)): if self.broj < self.max_hiscore[i]: self.broj = self.max_hiscore[i] print("Najbolji rezultat ima : " + str(self.broj)) self.hi_score = QLabel(self) self.hi_score.setText(str(self.broj)) self.hi_score.setGeometry(QRect(510, 5, 111, 20)) self.hi_score.setStyleSheet("color: rgb(255, 255, 255);\n" "font: 75 13pt \"Rockwell\";") def hide_explosion(self): self.explode.hide() def clear_status(self): self._status.setText('') def init_ui(self): self.init_window() self.init_aliens() self.init_shield() if self.player_spacecraft == "SILVER_X 177p": self.player1 = Player(self, 'images/silver.png', cfg.PLAYER_START_X, cfg.PLAYER_START_Y, cfg.SPACESHIP_WIDTH, cfg.SPACESHIP_HEIGHT, self.player_id, 3) elif self.player_spacecraft == "purpleZ AAx9": self.player1 = Player(self, 'images/purple.png', cfg.PLAYER_START_X, cfg.PLAYER_START_Y, cfg.SPACESHIP_WIDTH, cfg.SPACESHIP_HEIGHT, self.player_id, 3) elif self.player_spacecraft == "military-aircraft-POWER": self.player1 = Player(self, 'images/military.png', cfg.PLAYER_START_X, cfg.PLAYER_START_Y, cfg.SPACESHIP_WIDTH, cfg.SPACESHIP_HEIGHT, self.player_id, 3) else: self.player1 = Player(self, 'images/spacex.png', cfg.PLAYER_START_X, cfg.PLAYER_START_Y, cfg.SPACESHIP_WIDTH, cfg.SPACESHIP_HEIGHT, self.player_id, 3) if self.multiplayer_mode: if self.player2_spacecraft == "SILVER_X 177p": self.player2 = Player(self, 'images/silver.png', cfg.PLAYER2_START_X, cfg.PLAYER_START_Y, cfg.SPACESHIP_WIDTH, cfg.SPACESHIP_HEIGHT, self.player2_id, 3) elif self.player2_spacecraft == "purpleZ AAx9": self.player2 = Player(self, 'images/purple.png', cfg.PLAYER2_START_X, cfg.PLAYER_START_Y, cfg.SPACESHIP_WIDTH, cfg.SPACESHIP_HEIGHT, self.player2_id, 3) elif self.player2_spacecraft == "military-aircraft-POWER": self.player2 = Player(self, 'images/military.png', cfg.PLAYER2_START_X, cfg.PLAYER_START_Y, cfg.SPACESHIP_WIDTH, cfg.SPACESHIP_HEIGHT, self.player2_id, 3) elif self.player2_spacecraft == "SpaceX-air4p66": self.player2 = Player(self, 'images/spacex.png', cfg.PLAYER2_START_X, cfg.PLAYER_START_Y, cfg.SPACESHIP_WIDTH, cfg.SPACESHIP_HEIGHT, self.player2_id, 3) else: self.winner = self.player1 self.players.append(self.player1) self.deus_ex.add_player(self.player1.avatar) self.shield_destruct.add_player(self.player1.avatar) if self.multiplayer_mode: self.players.append(self.player2) self.deus_ex.add_player(self.player2.avatar) self.shield_destruct.add_player(self.player2.avatar) self.labels() def init_window(self): self.setFixedSize(cfg.PLAY_WINDOW_WIDTH, cfg.PLAY_WINDOW_HEIGHT) self.setWindowIcon(QIcon('images/icon.png')) self.setWindowTitle('Space Invaders [singleplayer mode] v1.0') self.bgLabel = QLabel(self) self.background = QPixmap('images/game_background.png') self.bgLabel.setPixmap(self.background) self.bgLabel.setGeometry(0, 0, cfg.PLAY_WINDOW_WIDTH, cfg.PLAY_WINDOW_HEIGHT) def init_aliens(self): for i in range(11): self.aliens.append( Alien(self, 'images/alien_mother.png', cfg.ALIEN_START_X - 8 + cfg.ALIEN_OFFSET_X * i, cfg.ALIEN_START_Y, cfg.FIRST_ROW_ALIEN_WIDTH, cfg.FIRST_ROW_ALIEN_HEIGHT, 500)) self.aliens.append( Alien(self, 'images/alien_child.png', cfg.ALIEN_START_X + cfg.ALIEN_OFFSET_X * i, cfg.ALIEN_START_Y + cfg.ALIEN_OFFSET_Y, cfg.SECOND_ROW_ALIEN_WIDTH, cfg.SECOND_ROW_ALIEN_HEIGHT, 200)) self.aliens.append( Alien(self, 'images/alien_grandchild.png', cfg.ALIEN_START_X + cfg.ALIEN_OFFSET_X * i, cfg.ALIEN_START_Y + cfg.ALIEN_OFFSET_Y + 60, cfg.THIRD_ROW_ALIEN_WIDTH, cfg.THIRD_ROW_ALIEN_HEIGHT, 100)) self.aliens.append( Alien(self, 'images/alien_middle.png', cfg.ALIEN_START_X + cfg.ALIEN_OFFSET_X * i, cfg.ALIEN_START_Y + cfg.ALIEN_OFFSET_Y + 120, cfg.FOURTH_ROW_ALIEN_WIDTH, cfg.FOURTH_ROW_ALIEN_HEIGHT, 50)) self.aliens.append( Alien(self, 'images/alien111.png', cfg.ALIEN_START_X + cfg.ALIEN_OFFSET_X * i, cfg.ALIEN_START_Y + cfg.ALIEN_OFFSET_Y + 180, cfg.FIFTH_ROW_ALIEN_WIDTH, cfg.FIFTH_ROW_ALIEN_HEIGHT, 10)) self.level_handle.alien_number = len(self.aliens) for i in range(55): self.alien_movement_thread.add_alien(self.aliens[i].avatar) self.alien_attack_thread.add_alien(self.aliens[i].avatar) self.shootingThread.add_alien((self.aliens[i]).avatar) self.collision_bullet_alien.add_alien(self.aliens[i].avatar) def init_shield(self): for i in range(4): self.shields.append( Shield(self, 'images/shield.png', cfg.SHIELD_START_X + cfg.SHIELD_OFFSET_X * i, cfg.SHIELD_START_Y, cfg.SHIELD_WIDTH, cfg.SHIELD_HEIGHT)) for i in range(4): self.shield_destruct.add_shield(self.shields[i].avatar) def start_threads(self): self.shootingThread.start() self.alien_movement_thread.start() self.alien_attack_thread.start() self.alien_shoot_bullet_thread.start() self.collision_bullet_alien.start() self.key_notifier.start() self.shield_destruct.start() self.deus_ex.start() self.level_handle.start() self.deus_ex_worker.start() self.status_bar.start() self.player_explosion.start() def threads_connect(self): self.shootingThread.updated_position.connect(self.update_bullet) self.alien_movement_thread.updated.connect(self.alien_movement) self.alien_attack_thread.init_bullet.connect(self.alien_attack) self.alien_shoot_bullet_thread.update_position.connect( self.shoot_bullet) self.collision_bullet_alien.collision_occured.connect( self.destroy_enemy_collision) self.key_notifier.key_signal.connect(self.__update_position__) self.shield_destruct.collision_with_shield_occured.connect( self.update_shield) self.shield_destruct.collision_with_player.connect(self.remove_life) self.shield_destruct.game_over.connect(self.game_over) self.shield_destruct.armour_broke.connect(self.remove_armour) self.shield_destruct.player_dead.connect(self.kill_player) self.shield_destruct.player_dead_bullet.connect( self.kill_player_bullet) self.deus_ex.empower.connect(self.remove_power_object) self.deus_ex.collision_occured.connect(self.apply_power) self.level_handle.next_level.connect(self.update_level) self.deus_ex_worker.calc_done.connect(self.show_power) self.status_bar.status_updated.connect(self.clear_status) self.player_explosion.explosion_detected.connect(self.hide_explosion) def start_new_threads(self): self.shootingThread = ShootBullet() self.shootingThread.updated_position.connect(self.update_bullet) self.shootingThread.start() self.alien_movement_thread = AlienMovement() self.alien_movement_thread.updated.connect(self.alien_movement) self.alien_movement_thread.start() self.alien_attack_thread = AlienAttack() self.alien_attack_thread.init_bullet.connect(self.alien_attack) self.alien_attack_thread.start() self.alien_shoot_bullet_thread = BulletMove() self.alien_shoot_bullet_thread.update_position.connect( self.shoot_bullet) self.alien_shoot_bullet_thread.start() self.collision_bullet_alien = CollisionPlayerBullet() self.collision_bullet_alien.collision_occured.connect( self.destroy_enemy_collision) self.collision_bullet_alien.start() # self.key_notifier = KeyNotifier() # self.key_notifier.key_signal.connect(self.__update_position__) # self.key_notifier.start() self.shield_destruct = CollisionAlienBullet() self.shield_destruct.collision_with_shield_occured.connect( self.update_shield) self.shield_destruct.collision_with_player.connect(self.remove_life) self.shield_destruct.game_over.connect(self.game_over) self.shield_destruct.player_dead.connect(self.kill_player) self.shield_destruct.player_dead_bullet.connect( self.kill_player_bullet) self.shield_destruct.armour_broke.connect(self.remove_armour) self.shield_destruct.start() self.deus_ex = DeusEx() self.deus_ex.empower.connect(self.remove_power_object) self.deus_ex.collision_occured.connect(self.apply_power) self.deus_ex.start() self.level_handle = NextLevel() self.level_handle.current_level = int(self.current_level_value.text()) self.level_handle.next_level.connect(self.update_level) self.level_handle.start() self.queue1 = Queue() self.deus_ex_proc = CalculateDeusExX(self.queue1) self.deus_ex_proc.start() self.deus_ex_worker = Worker(self.queue1) self.deus_ex_worker.calc_done.connect(self.show_power) self.deus_ex_worker.start() self.status_bar = StatusBar() self.status_bar.status_updated.connect(self.clear_status) self.status_bar.start() self.player_explosion = PlayerExplosion() self.player_explosion.explosion_detected.connect(self.hide_explosion) self.player_explosion.start() if self.multiplayer_mode: if not self.player1.is_dead: self.player1.lives = 3 self.player1.username = self.player_id if self.player1.armour: self.player1.armour = False self.player1.armour_label.hide() self.deus_ex.add_player(self.player1.avatar) self.shield_destruct.add_player(self.player1.avatar) if not self.player2.is_dead: self.player2.lives = 3 self.player2.username = self.player2_id if self.player2.armour: self.player2.armour = False self.player2.armour_label.hide() self.deus_ex.add_player(self.player2.avatar) self.shield_destruct.add_player(self.player2.avatar) if not self.player1.is_dead: self.player1.add_life_label(self.lives1_label) self.player1.add_life_label(self.lives2_label) self.player1.add_life_label(self.lives3_label) for life in self.player1.lives_labels: life.show() if not self.player2.is_dead: self.player2.add_life_label(self.lives1_label_p2) self.player2.add_life_label(self.lives2_label_p2) self.player2.add_life_label(self.lives3_label_p2) for life in self.player2.lives_labels: life.show() else: # ADD PLAYER self.deus_ex.add_player(self.player1.avatar) self.shield_destruct.add_player(self.player1.avatar) self.player1.lives = 3 if self.player1.armour: self.player1.armour_label.hide() self.player1.armour = False self.player1.add_life_label(self.lives1_label) self.player1.add_life_label(self.lives2_label) self.player1.add_life_label(self.lives3_label) for life in self.player1.lives_labels: life.show() def update_level(self, level: int): self.current_level_value.setText(str(level)) if cfg.ALIEN_X_VELOCITY + 1 < 15: cfg.ALIEN_X_VELOCITY += 1 if cfg.ALIEN_SHOOT_INTERVAL - 0.3 > 0: cfg.ALIEN_SHOOT_INTERVAL -= 0.3 if cfg.ALIEN_BULLET_VELOCITY + 1 < 15: cfg.ALIEN_BULLET_VELOCITY += 1 if cfg.SPACESHIP_VELOCITY + 1 < 25: cfg.SPACESHIP_VELOCITY += 1 self.kill_threads() self.deus_ex_proc.terminate() self.free_resources() self.start_new_threads() self.init_aliens() self.init_shield() def free_resources(self): self.aliens = [] for life in self.player1.lives_labels: life.hide() self.player1.lives_labels.clear() if self.multiplayer_mode: for life in self.player2.lives_labels: life.hide() self.player2.lives_labels.clear() for bullet in self.bullets: bullet.hide() self.bullets.clear() for shield in self.shields: shield.avatar.hide() self.shields.clear() for shield in self.shield_destruct.shields: shield.hide() self.shield_destruct.shields.clear() for bullet in self.shootingThread.bullets: bullet.hide() self.shootingThread.bullets.clear() for bullet in self.collision_bullet_alien.bullets: bullet.hide() self.collision_bullet_alien.bullets.clear() self.alien_movement_thread.aliens = [] self.alien_attack_thread.aliens = [] self.shootingThread.aliens = [] self.collision_bullet_alien.aliens = [] for bullet in self.alien_attack_thread.bullets: bullet.hide() self.alien_attack_thread.bullets.clear() for bullet in self.alien_shoot_bullet_thread.bullets: bullet.hide() self.alien_shoot_bullet_thread.bullets.clear() for bullet in self.shield_destruct.alien_bullets: bullet.hide() self.shield_destruct.alien_bullets.clear() for power in self.powers: power.hide() self.powers.clear() for power in self.deus_ex.powers: power.hide() self.deus_ex.powers.clear() self._status.setText('') def kill_threads(self): self.shootingThread.terminate() self.alien_movement_thread.terminate() self.alien_attack_thread.terminate() self.alien_shoot_bullet_thread.terminate() self.collision_bullet_alien.terminate() # self.key_notifier.die() self.shield_destruct.terminate() self.deus_ex.terminate() self.level_handle.terminate() self.deus_ex_worker.terminate() self.status_bar.terminate() self.player_explosion.terminate() @pyqtSlot(QLabel) def kill_player(self, player: QLabel): player.hide() for p in self.players: if p.avatar == player: p.is_dead = True p.lives_labels[0].hide() self.players.remove(p) self.deus_ex.rem_player(player) if self.multiplayer_mode: if len(self.players) == 1: self.winner = self.players[0] @pyqtSlot(QLabel, QLabel) def kill_player_bullet(self, player: QLabel, bullet: QLabel): player.hide() bullet.hide() for p in self.players: if p.avatar == player: self._status.setText(f'player {p.username} died') self.status_bar.update_status('go') p.is_dead = True p.lives_labels[0].hide() self.explode = QLabel(self) self.explode.setGeometry(player.geometry().x(), player.geometry().y() - 20, 100, 100) movie = QMovie('images/resized-expl.gif') self.explode.setMovie(movie) movie.start() self.explode.show() self.player_explosion.add_effect('die') self.players.remove(p) self.deus_ex.rem_player(player) if self.multiplayer_mode: if len(self.players) == 1: self.winner = self.players[0] @pyqtSlot(int, int) def alien_attack(self, bullet_x, bullet_y): bullet = Bullet(self, 'images/final_bullet.png', bullet_x, bullet_y, 12, 50).avatar self.alien_attack_thread.add_bullet(bullet) self.alien_shoot_bullet_thread.add_bullet(bullet) self.shield_destruct.add_bullet(bullet) @pyqtSlot(QLabel, int, int) def alien_movement(self, alien: QLabel, new_x, new_y): alien.move(new_x, new_y) @pyqtSlot(QLabel, QLabel) def remove_armour(self, player: QLabel, bullet: QLabel): bullet.hide() for p in self.players: if p.avatar == player: player_index = self.players.index(p) p.armour = False self.shield_destruct.player_armour[player_index] = False p.armour_label.hide() self._status.setText(f'player {p.username} lost armour') self.status_bar.update_status('go') @pyqtSlot(QLabel, QLabel, int) def apply_power(self, player: QLabel, power: QLabel, index: int): power.hide() for p in self.players: if p.avatar == player: player_index = self.players.index(p) if index == 0: # REMOVE 1 LIFE if not p.armour: self.shield_destruct.counter_lives[player_index] += 1 p.remove_life() p.rem_life_label() self._status.setText( f'player {p.username} lost a life') self.status_bar.update_status('go') else: p.armour_label.hide() p.armour = False self.shield_destruct.player_armour[ player_index] = False self._status.setText( f'player {p.username} lost armour') self.status_bar.update_status('go') elif index == 1: # ADD 1 LIFE if p.lives == 1: p.add_life() self.shield_destruct.counter_lives[player_index] -= 1 if p.username == self.player_id: p.add_life_label(self.lives2_label) elif p.username == self.player2_id: p.add_life_label(self.lives2_label_p2) self._status.setText( f'extra life - player {p.username}') self.status_bar.update_status('go') elif p.lives == 2: p.add_life() self.shield_destruct.counter_lives[player_index] -= 1 if p.username == self.player_id: p.add_life_label(self.lives3_label) elif p.username == self.player2_id: p.add_life_label(self.lives3_label_p2) self._status.setText( f'extra life - player {p.username}') self.status_bar.update_status('go') p.lives_labels[len(p.lives_labels) - 1].show() elif index == 2: # ADD ARMOUR if not p.armour: p.armour = True p.armour_label = QLabel(self) p.armour_label.setPixmap(QPixmap('images/armour.png')) p.armour_label.setGeometry( p.avatar.geometry().x() - 10, p.avatar.geometry().y() - 10, 100, 100) p.armour_label.show() self.shield_destruct.player_armour[player_index] = True self._status.setText( f'extra armour - player {p.username}') self.status_bar.update_status('go') @pyqtSlot(QLabel) def remove_power_object(self, power: QLabel): if power in self.powers: self.powers.remove(power) power.hide() @pyqtSlot(int) def show_power(self, x_axis: int): rand_power_index = randint(0, 2) self.empower = QLabel(self) if rand_power_index == 0: movie = QMovie("images/skull-resized.gif") self.empower.setMovie(movie) movie.start() elif rand_power_index == 1: self.empower.setPixmap(QPixmap('images/lives.png')) elif rand_power_index == 2: movie = QMovie("images/armor-resized.gif") self.empower.setMovie(movie) movie.start() self.empower.setGeometry(x_axis, 660, 45, 45) self.empower.show() self.powers.append(self.empower) self.deus_ex.add_power(self.empower, rand_power_index) @pyqtSlot(QLabel, QLabel, int) def remove_life(self, player: QLabel, bullet: QLabel, counter: int): bullet.hide() for p in self.players: if p.avatar == player: self.explode = QLabel(self) self.explode.setGeometry(player.geometry().x() + 20, player.geometry().y() - 20, 35, 35) movie = QMovie('images/bullet-hit.gif') self.explode.setMovie(movie) movie.start() self.explode.show() self.player_explosion.add_effect('hit') p.remove_life() if p.lives == 2: p.rem_life_label() elif p.lives == 1: p.rem_life_label() def __update_position__(self, key): player_position = self.player1.avatar.geometry() if not self.player1.is_dead: if key == Qt.Key_D: if self.player1.armour: if not player_position.x() + player_position.width( ) + 10 > 950: self.player1.avatar.setGeometry( player_position.x() + cfg.SPACESHIP_VELOCITY, player_position.y(), player_position.width(), player_position.height()) self.player1.armour_label.setGeometry( self.player1.avatar.geometry().x() - 13, self.player1.avatar.geometry().y() - 10, 100, 100) else: if not player_position.x() + player_position.width( ) + 10 > 950: self.player1.avatar.setGeometry( player_position.x() + cfg.SPACESHIP_VELOCITY, player_position.y(), player_position.width(), player_position.height()) if key == Qt.Key_A: if self.player1.armour: if not player_position.x() - 10 < 0: self.player1.avatar.setGeometry( player_position.x() - cfg.SPACESHIP_VELOCITY, player_position.y(), player_position.width(), player_position.height()) self.player1.armour_label.setGeometry( self.player1.avatar.geometry().x() - 13, self.player1.avatar.geometry().y() - 10, 100, 100) else: if not player_position.x() - 10 < 0: self.player1.avatar.setGeometry( player_position.x() - cfg.SPACESHIP_VELOCITY, player_position.y(), player_position.width(), player_position.height()) if key == Qt.Key_Space: bullet = Bullet( self, 'images/blue-fire.png', player_position.x() + player_position.width() / 2 - 5, player_position.y() - 22, 12, 55).avatar self.shootingThread.add_bullet(bullet) d = {'space': bullet} self.collision_bullet_alien.dict_list.append(d) if self.multiplayer_mode: player2_position = self.player2.avatar.geometry() if not self.player2.is_dead: if key == Qt.Key_Right: if self.player2.armour: if not player2_position.x() + player2_position.width( ) + 10 > 950: self.player2.avatar.setGeometry( player2_position.x() + cfg.SPACESHIP_VELOCITY, player2_position.y(), player2_position.width(), player2_position.height()) self.player2.armour_label.setGeometry( self.player2.avatar.geometry().x() - 13, self.player2.avatar.geometry().y() - 10, 100, 100) else: if not player2_position.x() + player2_position.width( ) + 10 > 950: self.player2.avatar.setGeometry( player2_position.x() + cfg.SPACESHIP_VELOCITY, player2_position.y(), player2_position.width(), player2_position.height()) if key == Qt.Key_Left: if self.player2.armour: if not player2_position.x() - 10 < 0: self.player2.avatar.setGeometry( player2_position.x() - cfg.SPACESHIP_VELOCITY, player2_position.y(), player2_position.width(), player2_position.height()) self.player2.armour_label.setGeometry( self.player2.avatar.geometry().x() - 13, self.player2.avatar.geometry().y() - 10, 100, 100) else: if not player2_position.x() - 10 < 0: self.player2.avatar.setGeometry( player2_position.x() - cfg.SPACESHIP_VELOCITY, player2_position.y(), player2_position.width(), player2_position.height()) if key == Qt.Key_K: bullet = Bullet( self, 'images/blue-fire.png', player2_position.x() + player2_position.width() / 2 - 5, player2_position.y() - 22, 12, 55).avatar self.shootingThread.add_bullet(bullet) d = {'k': bullet} self.collision_bullet_alien.dict_list.append(d) def destroy_enemy_collision(self, alien: QLabel, bullet: QLabel, key: str): bullet.hide() for a in self.aliens: if a.avatar == alien: alien.hide() self.aliens.remove(a) self.alien_movement_thread.remove_alien(alien) self.alien_attack_thread.remove_alien(alien) self.level_handle.alien_number -= 1 if key == 'space': self.total_point += a.worth self.player1.score = self.total_point self.score.setText(str(self.total_point)) elif key == 'k': self.total_point2 += a.worth self.player2.score = self.total_point2 self.score2.setText(str(self.total_point2)) @pyqtSlot(QLabel, QLabel, int) def update_shield(self, shield: QLabel, bullet: QLabel, counter: int): if counter == 1: shield.setPixmap(QPixmap("images/shield2")) elif counter == 2: shield.setPixmap(QPixmap("images/shield3")) elif counter == 3: shield.setPixmap(QPixmap("images/shield4")) elif counter == 4: shield.hide() if shield in self.shields: self.shields.remove(shield) self.shield_destruct.rem_shield(shield) bullet.hide() @pyqtSlot(QLabel, int, int) def shoot_bullet(self, bullet: QLabel, bullet_x, bullet_y): bullet.move(bullet_x, bullet_y) @pyqtSlot(QLabel, int, int) def update_bullet(self, bullet: QLabel, new_x, new_y): if new_y > 0: bullet.move(new_x, new_y) else: bullet.hide() self.shootingThread.remove_bullet(bullet) def keyPressEvent(self, event): self.key_notifier.add_key(event.key()) def keyReleaseEvent(self, event): self.key_notifier.rem_key(event.key()) def labels(self): font = QtGui.QFont() font.setFamily("Rockwell") font.setPointSize(15) self.player1_name = QLabel(self) self.player1_name.setText(self.player_id) self.player1_name.setGeometry(5, 10, 75, 30) self.player1_name.setStyleSheet("color: blue") self.player1_name.setFont(font) self.lives1_label = QLabel(self) self.lives1_label.setPixmap(QPixmap('images/lives-blue.png')) self.lives1_label.setGeometry(QRect(80, 10, 31, 31)) self.lives2_label = QLabel(self) self.lives2_label.setPixmap(QPixmap('images/lives-blue.png')) self.lives2_label.setGeometry(QRect(110, 10, 31, 31)) self.lives3_label = QLabel(self) self.lives3_label.setPixmap(QPixmap('images/lives-blue.png')) self.lives3_label.setGeometry(QRect(140, 10, 31, 31)) self.player1.add_life_label(self.lives1_label) self.player1.add_life_label(self.lives2_label) self.player1.add_life_label(self.lives3_label) if self.multiplayer_mode: self.player2_name = QLabel(self) self.player2_name.setText(self.player2_id) self.player2_name.setGeometry(780, 10, 75, 30) self.player2_name.setStyleSheet("color: red") self.player2_name.setFont(font) self.lives1_label_p2 = QLabel(self) self.lives1_label_p2.setPixmap(QPixmap('images/lives.png')) self.lives1_label_p2.setGeometry(QRect(855, 10, 31, 31)) self.lives2_label_p2 = QLabel(self) self.lives2_label_p2.setPixmap(QPixmap('images/lives.png')) self.lives2_label_p2.setGeometry(QRect(885, 10, 31, 31)) self.lives3_label_p2 = QLabel(self) self.lives3_label_p2.setPixmap(QPixmap('images/lives.png')) self.lives3_label_p2.setGeometry(QRect(915, 10, 31, 31)) self.player2.add_life_label(self.lives1_label_p2) self.player2.add_life_label(self.lives2_label_p2) self.player2.add_life_label(self.lives3_label_p2) self.score_label2 = QLabel(self) self.score_label2.setText("score: ") self.score_label2.setGeometry(QRect(780, 35, 61, 16)) self.score_label2.setStyleSheet("color: red;\n" "font: 75 13pt \"Rockwell\";") self.score2 = QLabel(self) self.score2.setText(str(self.total_point2)) self.score2.setGeometry(QRect(830, 35, 111, 16)) self.score2.setStyleSheet("color: red;\n" "font: 75 13pt \"Rockwell\";") font.setPointSize(13) self.score_label = QLabel(self) self.score_label.setText("score: ") self.score_label.setGeometry(QRect(5, 35, 61, 16)) self.score_label.setStyleSheet("color: blue") self.score_label.setFont(font) self.score = QLabel(self) self.score.setText(str(self.total_point)) self.score.setGeometry(QRect(55, 35, 111, 16)) self.score.setStyleSheet("color: blue") self.score.setFont(font) self.hiscore_label = QLabel(self) self.hiscore_label.setText("highscore: ") self.hiscore_label.setGeometry(QRect(-20, 5, cfg.PLAY_WINDOW_WIDTH, 20)) self.hiscore_label.setStyleSheet("color: rgb(255, 255, 255)") self.hiscore_label.setFont(font) self.hiscore_label.setAlignment(Qt.AlignCenter) self.current_level = QLabel(self) self.current_level.setText("current level: ") self.current_level.setGeometry(QRect(0, 30, cfg.PLAY_WINDOW_WIDTH, 20)) self.current_level.setStyleSheet("color: rgb(255, 255, 255)") self.current_level.setFont(font) self.current_level.setAlignment(Qt.AlignCenter) self.current_level_value = QLabel(self) self.current_level_value.setText("1") self.current_level_value.setGeometry(QRect(540, 30, 111, 20)) self.current_level_value.setStyleSheet("color: rgb(255, 255, 255)") self.current_level_value.setFont(font) self._status = QLabel(self) self._status.setGeometry(QRect(0, 745, cfg.PLAY_WINDOW_WIDTH, 16)) self._status.setStyleSheet("color: rgb(255, 255, 255)") self._status.setFont(font) self._status.setAlignment(Qt.AlignCenter) def game_over(self): print("GAME OVER") # print("SCORE: ", self.winner.score) self.kill_threads() self.deus_ex_proc.terminate() self.key_notifier.terminate() font = QtGui.QFont() font.setFamily("Rockwell") font.setPointSize(60) self.game_over_label = QLabel(self) self.bg = QPixmap('images/bg-resized.jpg') self.game_over_label.setPixmap(self.bg) self.game_over_label.setGeometry(0, 0, cfg.PLAY_WINDOW_WIDTH, cfg.PLAY_WINDOW_HEIGHT) self.game_over_label.show() self.end_label = QLabel(self) self.end_label.setText('GAME OVER') self.end_label.setFont(font) self.end_label.setStyleSheet("color: rgb(255, 255, 255);") self.end_label.setGeometry(0, 100, 950, 100) self.end_label.setAlignment(Qt.AlignCenter) self.end_label.show() font.setPointSize(20) self.winner_label = QLabel(self) self.winner_label.setFont(font) self.winner_label.setText('winner: ' + self.winner.username) self.winner_label.setStyleSheet("color: rgb(255, 255, 255);") self.winner_label.setGeometry(0, 300, 950, 30) self.winner_label.setAlignment(Qt.AlignCenter) self.winner_label.show() self.end_score = QLabel(self) self.end_score.setFont(font) self.end_score.setText('total score: ' + str(self.winner.score)) self.end_score.setStyleSheet("color: rgb(255, 255, 255);") self.end_score.setGeometry(0, 340, 950, 30) self.end_score.setAlignment(Qt.AlignCenter) self.end_score.show() self.free_resources() self.write_in_base() def write_in_base(self): self.file = open("players.txt", "a") self.file.write( str(self.winner.username) + " " + str(self.winner.score) + "\n") self.file.close() def closeEvent(self, event): self.kill_threads() self.deus_ex_proc.terminate() self.key_notifier.terminate() exit()
def insert_new_player(player: Player.Player): player_serialized = player.serialize() return EichState.EichState.player_col.insert_one(player_serialized)
def __init__(self, main): self.main = main self.current_frame = long(0) self.paused = False self.grid = Grid(main, (1,1)) self.transition = None self.silent_transitions = False self.fade = FadeFromBlack(self.main) self.fade.pre_delay = 30 self.fade.fade_length = 30 self.earthquake_amount = 0 self.earthquake_sound = pygame.mixer.Sound("snds/sfx/earthquake.wav") self.earthquake_sound_channel = pygame.mixer.Channel(0) self.visible_grid = VisibleGrid(main) self.player = Player(main, [(self.grid.gridsize[0]*TILE_SIZE)/2, (self.grid.gridsize[1]*TILE_SIZE)/2], [28,28]) self.player_is_alive = True self.npcs = [] self.particles = [] self.drops = [] self.preferred_offset = (-((self.grid.gridsize[0]*TILE_SIZE*0.5) - (self.main.screen_size[0]/2)), -((self.grid.gridsize[1]*TILE_SIZE*0.5) - (self.main.screen_size[1]/2))) self.current_offset = list(self.preferred_offset) self.disable_update_offset = False #new_offset = ((0) - (self.main.screen_size[0]/2), (0) - (self.main.screen_size[1]/2)) self.visible_grid.set_offset(self.preferred_offset) self.sounds = {} self.sounds["enemy_death"] = pygame.mixer.Sound("snds/sfx/enemy_death.wav") self.sounds["enemy_hurt"] = pygame.mixer.Sound("snds/sfx/enemy_hurt.wav") self.sounds["falling"] = pygame.mixer.Sound("snds/sfx/falling.wav") self.sounds["player_hurt"] = pygame.mixer.Sound("snds/sfx/player_hurt.wav") self.sounds["player_death"] = pygame.mixer.Sound("snds/sfx/player_death.wav") self.sounds["gained_health"] = pygame.mixer.Sound("snds/sfx/gained_health.wav") self.sounds["sword_swing"] = pygame.mixer.Sound("snds/sfx/sword_swing.wav") self.sounds["cut_bush"] = pygame.mixer.Sound("snds/sfx/cut_bush.wav") self.sounds["tile_change"] = pygame.mixer.Sound("snds/sfx/tile_change.wav") self.sounds["tile_change_color"] = pygame.mixer.Sound("snds/sfx/tile_change_color.wav") self.sounds["death_music"] = pygame.mixer.Sound("snds/songs/death_music.ogg") self.sounds["pause_sound"] = pygame.mixer.Sound("snds/misc/pause_sound.wav") self.sounds["room1"] = pygame.mixer.Sound("snds/vo/room1.ogg") self.sounds["room2"] = pygame.mixer.Sound("snds/vo/room2.ogg") self.sounds["room3"] = pygame.mixer.Sound("snds/vo/room3.ogg") self.sounds["room4"] = pygame.mixer.Sound("snds/vo/room4.ogg") self.sounds["room5"] = pygame.mixer.Sound("snds/vo/room5.ogg") self.sounds["roomlaugh1"] = pygame.mixer.Sound("snds/vo/roomlaugh1.ogg") self.sounds["roomlonglaugh"] = pygame.mixer.Sound("snds/vo/roomlonglaugh.ogg") self.sounds["roomgrowl1"] = pygame.mixer.Sound("snds/vo/roomgrowl1.ogg") self.sounds["roomgrowl2"] = pygame.mixer.Sound("snds/vo/roomgrowl2.ogg") self.sounds["roompain1"] = pygame.mixer.Sound("snds/vo/roompain1.ogg") self.sounds["roompain2"] = pygame.mixer.Sound("snds/vo/roompain2.ogg") self.scripts = [] self.load_startup_script()
class World(object): """ This is the World! It contains all entities, sprites, particles, tiles, and many other things. """ def __init__(self, main): self.main = main self.current_frame = long(0) self.paused = False self.grid = Grid(main, (1,1)) self.transition = None self.silent_transitions = False self.fade = FadeFromBlack(self.main) self.fade.pre_delay = 30 self.fade.fade_length = 30 self.earthquake_amount = 0 self.earthquake_sound = pygame.mixer.Sound("snds/sfx/earthquake.wav") self.earthquake_sound_channel = pygame.mixer.Channel(0) self.visible_grid = VisibleGrid(main) self.player = Player(main, [(self.grid.gridsize[0]*TILE_SIZE)/2, (self.grid.gridsize[1]*TILE_SIZE)/2], [28,28]) self.player_is_alive = True self.npcs = [] self.particles = [] self.drops = [] self.preferred_offset = (-((self.grid.gridsize[0]*TILE_SIZE*0.5) - (self.main.screen_size[0]/2)), -((self.grid.gridsize[1]*TILE_SIZE*0.5) - (self.main.screen_size[1]/2))) self.current_offset = list(self.preferred_offset) self.disable_update_offset = False #new_offset = ((0) - (self.main.screen_size[0]/2), (0) - (self.main.screen_size[1]/2)) self.visible_grid.set_offset(self.preferred_offset) self.sounds = {} self.sounds["enemy_death"] = pygame.mixer.Sound("snds/sfx/enemy_death.wav") self.sounds["enemy_hurt"] = pygame.mixer.Sound("snds/sfx/enemy_hurt.wav") self.sounds["falling"] = pygame.mixer.Sound("snds/sfx/falling.wav") self.sounds["player_hurt"] = pygame.mixer.Sound("snds/sfx/player_hurt.wav") self.sounds["player_death"] = pygame.mixer.Sound("snds/sfx/player_death.wav") self.sounds["gained_health"] = pygame.mixer.Sound("snds/sfx/gained_health.wav") self.sounds["sword_swing"] = pygame.mixer.Sound("snds/sfx/sword_swing.wav") self.sounds["cut_bush"] = pygame.mixer.Sound("snds/sfx/cut_bush.wav") self.sounds["tile_change"] = pygame.mixer.Sound("snds/sfx/tile_change.wav") self.sounds["tile_change_color"] = pygame.mixer.Sound("snds/sfx/tile_change_color.wav") self.sounds["death_music"] = pygame.mixer.Sound("snds/songs/death_music.ogg") self.sounds["pause_sound"] = pygame.mixer.Sound("snds/misc/pause_sound.wav") self.sounds["room1"] = pygame.mixer.Sound("snds/vo/room1.ogg") self.sounds["room2"] = pygame.mixer.Sound("snds/vo/room2.ogg") self.sounds["room3"] = pygame.mixer.Sound("snds/vo/room3.ogg") self.sounds["room4"] = pygame.mixer.Sound("snds/vo/room4.ogg") self.sounds["room5"] = pygame.mixer.Sound("snds/vo/room5.ogg") self.sounds["roomlaugh1"] = pygame.mixer.Sound("snds/vo/roomlaugh1.ogg") self.sounds["roomlonglaugh"] = pygame.mixer.Sound("snds/vo/roomlonglaugh.ogg") self.sounds["roomgrowl1"] = pygame.mixer.Sound("snds/vo/roomgrowl1.ogg") self.sounds["roomgrowl2"] = pygame.mixer.Sound("snds/vo/roomgrowl2.ogg") self.sounds["roompain1"] = pygame.mixer.Sound("snds/vo/roompain1.ogg") self.sounds["roompain2"] = pygame.mixer.Sound("snds/vo/roompain2.ogg") self.scripts = [] self.load_startup_script() def autosave(self): f = open("save.dat", 'w') data = [self.scripts[0].filename] if self.main.music.songname != None and self.main.music.current != None: data.append(self.main.music.songname) data.append(str(self.main.music.current)) data = string.join(data,"\n") #print "AUTOSAVE: " #print data f.write(data) f.close() def check_for_save(self): return os.path.exists("save.dat") def load_startup_script(self): #This is the script that's loaded when the program is started. if self.check_for_save(): self.scripts.insert(0, Script(self, "startscreen/continue_screen")) else: self.scripts.insert(0, Script(self, "startscreen/newgame_screen")) def start_new_game(self): self.scripts.insert(0, Script(self, "level1/main_script")) def continue_saved_game(self): f = open("save.dat") data = f.read().split("\n") f.close() self.scripts = [Script(self, data[0])] if len(data) > 1: self.main.music.load_music(data[1]) self.main.music.begin() self.main.music.cue(int(data[2]), True) self.main.music.play_next() def play_sound(self, soundname, offset = None, volume = 1.0): #first we check if the sound exists if soundname in self.sounds: sound = self.sounds[soundname] if offset: x_pos = self.visible_grid.offset[0]+offset[0] x_pos = min(max(x_pos,0), self.main.screen_size[0]) p = x_pos/float(self.main.screen_size[0]) L_vol = max(min((1-p)*2,1.0),0.0) R_vol = max(min(p*2,1.0),0.0) else: L_vol = 1.0 R_vol = 1.0 L_vol *= volume R_vol *= volume channel = sound.play() if channel: channel.set_volume(L_vol, R_vol) else: print "That sound doesn't exist: ", soundname def load_grid(self, filename): f = open("data/grids/"+filename+".txt") data = f.read().split("\n") f.close() line = data.pop(0) parts = line.split(",") size = (int(parts[0]), int(parts[1])) grid = Grid(self.main) grid.gridsize = size grid.tiles = [] for y in xrange(size[1]): row = [] line = list(data.pop(0)) for s in line: if s in "_-wpef": row.append(Tile(self.main)) if s == "-": row[-1].color = lerp_colors(TILE_FLATTENED_COLOR, TILE_FLOOR_COLOR, TILE_HINT_COLOR_STRENGTH) elif s == "w": row[-1].color = lerp_colors(TILE_FLATTENED_COLOR, TILE_WALLTILE_COLOR, TILE_HINT_COLOR_STRENGTH) elif s == "p": row[-1].color = lerp_colors(TILE_FLATTENED_COLOR, TILE_PIT_COLOR, TILE_HINT_COLOR_STRENGTH) elif s == "e": row[-1].color = lerp_colors(TILE_FLATTENED_COLOR, TILE_SPAWNER1TILE_COLOR, TILE_HINT_COLOR_STRENGTH) elif s == "f": row[-1].color = lerp_colors(TILE_FLATTENED_COLOR, TILE_SPAWNER2TILE_COLOR, TILE_HINT_COLOR_STRENGTH) elif s in "123456789": row.append(TriggerTile(self.main)) row[-1].id = s elif s == "g": row.append(GrassTile(self.main)) elif s == "d": row.append(DirtFloorTile(self.main)) elif s == "D": row.append(DirtWallTile(self.main)) elif s == "W": row.append(WallTile(self.main)) elif s == "P": row.append(PitTile(self.main)) elif s == "E": row.append(Spawner1Tile(self.main)) elif s == "F": row.append(Spawner2Tile(self.main)) elif s == "%": row.append(CrackedTile(self.main)) elif s == "#": row.append(CrackedWallTile(self.main)) elif s == "b": row.append(BushTile(self.main)) grid.tiles.append(row) return grid def update(self): """ World.update - Called by Main. Updates all entities and handles/performs events. Dead entities are pruned in this function. """ for e in self.main.events: if not self.player.dead and not self.player.controls_disabled: if e.type == KEYDOWN and e.key == K_ESCAPE: self.paused = not self.paused self.play_sound("pause_sound", volume=0.5) if self.paused: self.main.music.set_volume(0.025) else: self.main.music.set_volume() if not self.paused or self.player.dead: #Updates the fade if self.fade != None: self.fade.update() if self.fade.dead: if self.player.dead: self.main.reset() else: self.fade = None else: #Death-screen fade-away. if self.player.dead: self.fade = FadeToBlackOnDeath(self.main) if not self.player.dead: #Updates the script i = 0 while i < len(self.scripts): self.scripts[i].parse_script() if self.scripts[i].dead: del self.scripts[i] else: i += 1 #Manage Transitions if self.transition != None: self.transition.update() #Checks out the changed tiles. changes = [] for change in self.transition.changed_tiles: if change[1].solid != change[2].solid or change[1].is_a_pit != change[2].is_a_pit: #we play a rumble sound for this tile. match = False for ch in changes: if ch[0] == change[0][0] and ch[1] == "tile_change": match = True break if not match: changes.append((change[0][0], "tile_change")) elif change[1].color != change[2].color: #we play a magical sound for this tile. match = False for ch in changes: if ch[0] == change[0][0] and ch[1] == "tile_change_color": match = True break if not match: changes.append((change[0][0], "tile_change_color")) t = type(change[2]) if t in (Spawner1Tile, Spawner2Tile): pos = ((change[0][0]+0.5)*TILE_SIZE, (change[0][1]+0.5)*TILE_SIZE) if t == Spawner1Tile: self.npcs.append(Baddie1(self.main, pos)) elif t == Spawner2Tile: self.npcs.append(Baddie2(self.main, pos)) if len(changes) > 0: volume = 1.0 / len(changes) for ch in changes: pos = ((ch[0]+0.5)*TILE_SIZE, 0) #the y doesn't matter. self.play_sound(ch[1], pos, volume) #Finally, we check if the transition has finished. if self.transition.done_transitioning: self.transition = None """ if not self.transition.done_transitioning: if self.transition.stage == 2 and self.transition.delay == 0: for x in xrange(5): pos = ((random.randint(0,self.grid.gridsize[0])*0.5)*TILE_SIZE, (random.randint(0,self.grid.gridsize[1])*0.5)*TILE_SIZE) self.npcs.append(Baddie1(self.main, pos)) self.player.is_hurt = True self.player.hurt = self.player.hurt_length if self.transition.stage >= 2 or self.transition.stage == 0: if len(self.npcs) == 0: if self.main.music.current == 2: self.main.music.cue(3) else: if self.main.music.current == 3: self.main.music.cue(2) else: next_grid = self.prep_next_grid() self.transition = HintedTransition(self.main, self.grid, next_grid, self.visible_grid, flat_delay=400) else: if self.main.music.current == 1 and self.main.music.sound_pos >= self.main.music.intro_trans_beats-1: next_grid = self.prep_next_grid() self.transition = HintedTransition(self.main, self.grid, next_grid, self.visible_grid, flat_delay=0, flat_len=1) """ #Updates the player. self.player.update() if not self.player.dead: #Then updates/prunes NPCs. i = len(self.npcs) - 1 while i >= 0: self.npcs[i].update() npc = self.npcs[i] if npc.dead and not (npc.is_dying or npc.falling): if npc.is_bad and npc.fall == 0: if self.player.health < self.player.max_health: self.drops.append(Heart(self.main, list(npc.pos))) del self.npcs[i] i -= 1 #Then updates/prunes particles. i = len(self.particles) - 1 while i >= 0: self.particles[i].update() if self.particles[i].dead: del self.particles[i] i -= 1 #Then updates/prunes drops. i = len(self.drops) - 1 while i >= 0: self.drops[i].update() if self.drops[i].dead: del self.drops[i] i -= 1 else: if self.player_is_alive: self.player_is_alive = False self.visible_grid.apply_filter((255,0,0), BLEND_RGB_MIN) self.main.music.stop() self.main.world.play_sound("player_death", self.player.pos) def move(self): """ World.move - Called by Main. Calls 'move' on all entities. """ if not self.paused or self.player.dead: self.player.move() if not self.player.dead: for npc in self.npcs: npc.move() for particle in self.particles: particle.move() for drop in self.drops: drop.move() # === MOVES THE 'CAMERA' === #first we center it. new_offset = [float(self.preferred_offset[0]), float(self.preferred_offset[1])] if not self.disable_update_offset: #then we check if the player is almost going off of the screen. pl = self.player offset = [0,0] inset = 200 rect = pygame.Rect([-new_offset[0]+inset, -new_offset[1]+inset, self.main.screen_size[0]-inset-inset, self.main.screen_size[1]-inset-inset]) left = pl.rect.left - rect.right top = pl.rect.top - rect.bottom right = rect.left - pl.rect.right bottom = rect.top - pl.rect.bottom m = max(left,top,right,bottom) if m > 0: if abs(offset[0]) < left: offset[0] = left if abs(offset[1]) < top: offset[1] = top if abs(offset[0]) < right: offset[0] = -right if abs(offset[1]) < bottom: offset[1] = -bottom new_offset = [new_offset[0]-offset[0], new_offset[1]-offset[1]] #finally, we apply the new offset. new_offset = lerp_pos(self.current_offset, new_offset, 0.1) self.current_offset = new_offset if self.earthquake_amount > 0: new_offset = [new_offset[0] + random.randint(-1,1) * self.earthquake_amount, new_offset[1] + random.randint(-1,1) * self.earthquake_amount] self.visible_grid.set_offset(new_offset) def render(self): """ World.render - Called by Main. Renders the world and it's contents to the screen. """ if self.fade == None or not self.fade.is_covering_screen: #first we render the background. self.visible_grid.render() for npc in self.npcs: npc.render() for particle in self.particles: particle.render() self.player.render() for drop in self.drops: drop.render() offset = self.visible_grid.offset """ for npc in self.npcs: #Draws it's path if len(npc.path) > 2: new_path = [] for pos in npc.path: new_path.append((pos[0]+offset[0], pos[1]+offset[1])) pygame.draw.lines(self.main.screen, (255,255,0), False, new_path, 2) #Draws it's current target position if npc.target_pos != None: pos = (npc.target_pos[0]+offset[0], npc.target_pos[1]+offset[1]) pygame.draw.circle(self.main.screen, (255,255,0), pos, 4) #Draws it's coordinates if npc.target_pos != None: pos = (int((npc.coords[0]+0.5)*TILE_SIZE+offset[0]), int((npc.coords[1]+0.5)*TILE_SIZE+offset[1])) pygame.draw.circle(self.main.screen, (255,255,255), pos, 4) #Draws players's coordinates pos = (int(self.player.pos[0]+offset[0]), int(self.player.pos[1]+offset[1])) pygame.draw.circle(self.main.screen, (255,255,255), pos, 4) """ #we do letter-boxes for when the player doesn't have control. if self.player.controls_disabled: size = 75 color = (160,160,160) self.main.screen.fill(color, (0,0,self.main.screen_size[0],size), special_flags=BLEND_RGB_MULT) self.main.screen.fill(color, (0,self.main.screen_size[1]-size,self.main.screen_size[0],size), special_flags=BLEND_RGB_MULT) if self.fade != None: self.fade.render() #We increment the current frame number. if not self.paused: self.current_frame += 1
class GamePhaseService: def __init__(self): pygame.font.init() self.score = 0 self.window_service = None self.sprites = pygame.sprite.Group() self.player = None self.ufo = None self.rocks = pygame.sprite.Group() self.rocks_bullets_colision = None self.laser_player_colision = None self.ufo_bullets_colision = None self.sound_service = SoundService() def init_window(self, width, height): self.window_service = WindowService(width, height) def main_menu(self): if self.player is not None: self.player.delete() self.sound_service.play_soundtrack('menu_soundtrack.ogg') self.window_service.load_background('menu.jpg') return GameStatus.MAIN_MENU def pause(self): self.sound_service.play_soundtrack('menu_soundtrack.ogg') self.window_service.load_background('pause.jpg') return GameStatus.PAUSE def play(self): if self.player is None: self.score = 0 self.player = Player(self.sprites) self.sprites.add(self.player) self.draw_score() self.sound_service.play_soundtrack('game_soundtrack.ogg') self.window_service.load_background('space.jpg') return GameStatus.GAME_START def game(self): self.generate_rocks() self.generate_ufo() self.rocks_player_colision = pygame.sprite.spritecollide( self.player, self.rocks, True, pygame.sprite.collide_circle) self.rocks_bullets_colision = pygame.sprite.groupcollide( self.rocks, self.player.bullets(), True, True) self.player_rocks_events() self.rocks_players_bullets_events() if self.ufo is not None: self.ufo_bullets_colision = pygame.sprite.spritecollide( self.ufo, self.player.bullets(), True, pygame.sprite.collide_circle) self.laser_player_colision = pygame.sprite.spritecollide( self.player, self.ufo.laser_group(), True) self.ufo_bullets_events() self.player_ufo_lasers_events() def generate_rocks(self): if self.rocks.__len__() < 10: for i in range(2): self.new_rock() def generate_ufo(self): if self.ufo is None and self.score % 20 == 0: self.ufo = UFO(self.sprites) self.sprites.add(self.ufo) def player_rocks_events(self): for hit in self.rocks_player_colision: self.player_hit() def rocks_players_bullets_events(self): for hit in self.rocks_bullets_colision.items(): self.sound_service.play_sound('expl6.wav') self.score += 1 self.new_rock() def player_ufo_lasers_events(self): for hit in self.laser_player_colision: self.player_hit() def player_hit(self): if self.player.lives >= 1: self.sound_service.play_sound('expl3.wav') self.player.hit() def ufo_bullets_events(self): for hit in self.ufo_bullets_colision: self.sound_service.play_sound('expl6.wav') self.score += 4 self.ufo.kill() self.ufo = None def game_over(self): if self.ufo is not None: self.ufo.kill() self.ufo = None ScoreService().save_best_result(self.score) self.sound_service.play_soundtrack('menu_soundtrack.ogg') self.window_service.load_background('game_over.jpg') return GameStatus.PLAYER_DOWN def draw_sprites(self): self.sprites.update() self.sprites.draw(self.window_service.get__window()) self.draw_score() def new_rock(self): rock = Rock() self.sprites.add(rock) self.rocks.add(rock) def life(self): if self.player is not None: return self.player.lives def draw_score(self): self.window_service.draw(self.score, (255, 255, 255), (450, 10), 40) def draw_lives(self): self.window_service.draw("Life:" + str(self.player.lives), (255, 0, 0), (50, 10), 40) def draw_best_results(self, results): self.window_service.draw("Best result:", (255, 2, 2), (350, 300)) self.window_service.draw(results, (255, 2, 2), (450, 330)) def draw_end_results(self, results): self.window_service.draw(results, (255, 2, 2), (450, 330))
def __init__(self, human_name, stone_amount, human_turn): self.human_player = Player(human_name, BoardPositions.Player, stone_amount) self.ai_player = Player("AI", BoardPositions.Computer, stone_amount) self.human_turn = human_turn
def __init__(self, main): self.main = main self.current_frame = long(0) self.paused = False self.grid = Grid(main, (1, 1)) self.transition = None self.silent_transitions = False self.fade = FadeFromBlack(self.main) self.fade.pre_delay = 30 self.fade.fade_length = 30 self.earthquake_amount = 0 self.earthquake_sound = pygame.mixer.Sound("snds/sfx/earthquake.wav") self.earthquake_sound_channel = pygame.mixer.Channel(0) self.visible_grid = VisibleGrid(main) self.player = Player(main, [(self.grid.gridsize[0] * TILE_SIZE) / 2, (self.grid.gridsize[1] * TILE_SIZE) / 2], [28, 28]) self.player_is_alive = True self.npcs = [] self.particles = [] self.drops = [] self.preferred_offset = (-((self.grid.gridsize[0] * TILE_SIZE * 0.5) - (self.main.screen_size[0] / 2)), -((self.grid.gridsize[1] * TILE_SIZE * 0.5) - (self.main.screen_size[1] / 2))) self.current_offset = list(self.preferred_offset) self.disable_update_offset = False #new_offset = ((0) - (self.main.screen_size[0]/2), (0) - (self.main.screen_size[1]/2)) self.visible_grid.set_offset(self.preferred_offset) self.sounds = {} self.sounds["enemy_death"] = pygame.mixer.Sound( "snds/sfx/enemy_death.wav") self.sounds["enemy_hurt"] = pygame.mixer.Sound( "snds/sfx/enemy_hurt.wav") self.sounds["falling"] = pygame.mixer.Sound("snds/sfx/falling.wav") self.sounds["player_hurt"] = pygame.mixer.Sound( "snds/sfx/player_hurt.wav") self.sounds["player_death"] = pygame.mixer.Sound( "snds/sfx/player_death.wav") self.sounds["gained_health"] = pygame.mixer.Sound( "snds/sfx/gained_health.wav") self.sounds["sword_swing"] = pygame.mixer.Sound( "snds/sfx/sword_swing.wav") self.sounds["cut_bush"] = pygame.mixer.Sound("snds/sfx/cut_bush.wav") self.sounds["tile_change"] = pygame.mixer.Sound( "snds/sfx/tile_change.wav") self.sounds["tile_change_color"] = pygame.mixer.Sound( "snds/sfx/tile_change_color.wav") self.sounds["death_music"] = pygame.mixer.Sound( "snds/songs/death_music.ogg") self.sounds["pause_sound"] = pygame.mixer.Sound( "snds/misc/pause_sound.wav") self.sounds["room1"] = pygame.mixer.Sound("snds/vo/room1.ogg") self.sounds["room2"] = pygame.mixer.Sound("snds/vo/room2.ogg") self.sounds["room3"] = pygame.mixer.Sound("snds/vo/room3.ogg") self.sounds["room4"] = pygame.mixer.Sound("snds/vo/room4.ogg") self.sounds["room5"] = pygame.mixer.Sound("snds/vo/room5.ogg") self.sounds["roomlaugh1"] = pygame.mixer.Sound( "snds/vo/roomlaugh1.ogg") self.sounds["roomlonglaugh"] = pygame.mixer.Sound( "snds/vo/roomlonglaugh.ogg") self.sounds["roomgrowl1"] = pygame.mixer.Sound( "snds/vo/roomgrowl1.ogg") self.sounds["roomgrowl2"] = pygame.mixer.Sound( "snds/vo/roomgrowl2.ogg") self.sounds["roompain1"] = pygame.mixer.Sound("snds/vo/roompain1.ogg") self.sounds["roompain2"] = pygame.mixer.Sound("snds/vo/roompain2.ogg") self.scripts = [] self.load_startup_script()
class World(object): """ This is the World! It contains all entities, sprites, particles, tiles, and many other things. """ def __init__(self, main): self.main = main self.current_frame = long(0) self.paused = False self.grid = Grid(main, (1, 1)) self.transition = None self.silent_transitions = False self.fade = FadeFromBlack(self.main) self.fade.pre_delay = 30 self.fade.fade_length = 30 self.earthquake_amount = 0 self.earthquake_sound = pygame.mixer.Sound("snds/sfx/earthquake.wav") self.earthquake_sound_channel = pygame.mixer.Channel(0) self.visible_grid = VisibleGrid(main) self.player = Player(main, [(self.grid.gridsize[0] * TILE_SIZE) / 2, (self.grid.gridsize[1] * TILE_SIZE) / 2], [28, 28]) self.player_is_alive = True self.npcs = [] self.particles = [] self.drops = [] self.preferred_offset = (-((self.grid.gridsize[0] * TILE_SIZE * 0.5) - (self.main.screen_size[0] / 2)), -((self.grid.gridsize[1] * TILE_SIZE * 0.5) - (self.main.screen_size[1] / 2))) self.current_offset = list(self.preferred_offset) self.disable_update_offset = False #new_offset = ((0) - (self.main.screen_size[0]/2), (0) - (self.main.screen_size[1]/2)) self.visible_grid.set_offset(self.preferred_offset) self.sounds = {} self.sounds["enemy_death"] = pygame.mixer.Sound( "snds/sfx/enemy_death.wav") self.sounds["enemy_hurt"] = pygame.mixer.Sound( "snds/sfx/enemy_hurt.wav") self.sounds["falling"] = pygame.mixer.Sound("snds/sfx/falling.wav") self.sounds["player_hurt"] = pygame.mixer.Sound( "snds/sfx/player_hurt.wav") self.sounds["player_death"] = pygame.mixer.Sound( "snds/sfx/player_death.wav") self.sounds["gained_health"] = pygame.mixer.Sound( "snds/sfx/gained_health.wav") self.sounds["sword_swing"] = pygame.mixer.Sound( "snds/sfx/sword_swing.wav") self.sounds["cut_bush"] = pygame.mixer.Sound("snds/sfx/cut_bush.wav") self.sounds["tile_change"] = pygame.mixer.Sound( "snds/sfx/tile_change.wav") self.sounds["tile_change_color"] = pygame.mixer.Sound( "snds/sfx/tile_change_color.wav") self.sounds["death_music"] = pygame.mixer.Sound( "snds/songs/death_music.ogg") self.sounds["pause_sound"] = pygame.mixer.Sound( "snds/misc/pause_sound.wav") self.sounds["room1"] = pygame.mixer.Sound("snds/vo/room1.ogg") self.sounds["room2"] = pygame.mixer.Sound("snds/vo/room2.ogg") self.sounds["room3"] = pygame.mixer.Sound("snds/vo/room3.ogg") self.sounds["room4"] = pygame.mixer.Sound("snds/vo/room4.ogg") self.sounds["room5"] = pygame.mixer.Sound("snds/vo/room5.ogg") self.sounds["roomlaugh1"] = pygame.mixer.Sound( "snds/vo/roomlaugh1.ogg") self.sounds["roomlonglaugh"] = pygame.mixer.Sound( "snds/vo/roomlonglaugh.ogg") self.sounds["roomgrowl1"] = pygame.mixer.Sound( "snds/vo/roomgrowl1.ogg") self.sounds["roomgrowl2"] = pygame.mixer.Sound( "snds/vo/roomgrowl2.ogg") self.sounds["roompain1"] = pygame.mixer.Sound("snds/vo/roompain1.ogg") self.sounds["roompain2"] = pygame.mixer.Sound("snds/vo/roompain2.ogg") self.scripts = [] self.load_startup_script() def autosave(self): f = open("save.dat", 'w') data = [self.scripts[0].filename] if self.main.music.songname != None and self.main.music.current != None: data.append(self.main.music.songname) data.append(str(self.main.music.current)) data = string.join(data, "\n") #print "AUTOSAVE: " #print data f.write(data) f.close() def check_for_save(self): return os.path.exists("save.dat") def load_startup_script(self): #This is the script that's loaded when the program is started. if self.check_for_save(): self.scripts.insert(0, Script(self, "startscreen/continue_screen")) else: self.scripts.insert(0, Script(self, "startscreen/newgame_screen")) def start_new_game(self): self.scripts.insert(0, Script(self, "level1/main_script")) def continue_saved_game(self): f = open("save.dat") data = f.read().split("\n") f.close() self.scripts = [Script(self, data[0])] if len(data) > 1: self.main.music.load_music(data[1]) self.main.music.begin() self.main.music.cue(int(data[2]), True) self.main.music.play_next() def play_sound(self, soundname, offset=None, volume=1.0): #first we check if the sound exists if soundname in self.sounds: sound = self.sounds[soundname] if offset: x_pos = self.visible_grid.offset[0] + offset[0] x_pos = min(max(x_pos, 0), self.main.screen_size[0]) p = x_pos / float(self.main.screen_size[0]) L_vol = max(min((1 - p) * 2, 1.0), 0.0) R_vol = max(min(p * 2, 1.0), 0.0) else: L_vol = 1.0 R_vol = 1.0 L_vol *= volume R_vol *= volume channel = sound.play() if channel: channel.set_volume(L_vol, R_vol) else: print "That sound doesn't exist: ", soundname def load_grid(self, filename): f = open("data/grids/" + filename + ".txt") data = f.read().split("\n") f.close() line = data.pop(0) parts = line.split(",") size = (int(parts[0]), int(parts[1])) grid = Grid(self.main) grid.gridsize = size grid.tiles = [] for y in xrange(size[1]): row = [] line = list(data.pop(0)) for s in line: if s in "_-wpef": row.append(Tile(self.main)) if s == "-": row[-1].color = lerp_colors(TILE_FLATTENED_COLOR, TILE_FLOOR_COLOR, TILE_HINT_COLOR_STRENGTH) elif s == "w": row[-1].color = lerp_colors(TILE_FLATTENED_COLOR, TILE_WALLTILE_COLOR, TILE_HINT_COLOR_STRENGTH) elif s == "p": row[-1].color = lerp_colors(TILE_FLATTENED_COLOR, TILE_PIT_COLOR, TILE_HINT_COLOR_STRENGTH) elif s == "e": row[-1].color = lerp_colors(TILE_FLATTENED_COLOR, TILE_SPAWNER1TILE_COLOR, TILE_HINT_COLOR_STRENGTH) elif s == "f": row[-1].color = lerp_colors(TILE_FLATTENED_COLOR, TILE_SPAWNER2TILE_COLOR, TILE_HINT_COLOR_STRENGTH) elif s in "123456789": row.append(TriggerTile(self.main)) row[-1].id = s elif s == "g": row.append(GrassTile(self.main)) elif s == "d": row.append(DirtFloorTile(self.main)) elif s == "D": row.append(DirtWallTile(self.main)) elif s == "W": row.append(WallTile(self.main)) elif s == "P": row.append(PitTile(self.main)) elif s == "E": row.append(Spawner1Tile(self.main)) elif s == "F": row.append(Spawner2Tile(self.main)) elif s == "%": row.append(CrackedTile(self.main)) elif s == "#": row.append(CrackedWallTile(self.main)) elif s == "b": row.append(BushTile(self.main)) grid.tiles.append(row) return grid def update(self): """ World.update - Called by Main. Updates all entities and handles/performs events. Dead entities are pruned in this function. """ for e in self.main.events: if not self.player.dead and not self.player.controls_disabled: if e.type == KEYDOWN and e.key == K_ESCAPE: self.paused = not self.paused self.play_sound("pause_sound", volume=0.5) if self.paused: self.main.music.set_volume(0.025) else: self.main.music.set_volume() if not self.paused or self.player.dead: #Updates the fade if self.fade != None: self.fade.update() if self.fade.dead: if self.player.dead: self.main.reset() else: self.fade = None else: #Death-screen fade-away. if self.player.dead: self.fade = FadeToBlackOnDeath(self.main) if not self.player.dead: #Updates the script i = 0 while i < len(self.scripts): self.scripts[i].parse_script() if self.scripts[i].dead: del self.scripts[i] else: i += 1 #Manage Transitions if self.transition != None: self.transition.update() #Checks out the changed tiles. changes = [] for change in self.transition.changed_tiles: if change[1].solid != change[2].solid or change[ 1].is_a_pit != change[2].is_a_pit: #we play a rumble sound for this tile. match = False for ch in changes: if ch[0] == change[0][0] and ch[ 1] == "tile_change": match = True break if not match: changes.append((change[0][0], "tile_change")) elif change[1].color != change[2].color: #we play a magical sound for this tile. match = False for ch in changes: if ch[0] == change[0][0] and ch[ 1] == "tile_change_color": match = True break if not match: changes.append( (change[0][0], "tile_change_color")) t = type(change[2]) if t in (Spawner1Tile, Spawner2Tile): pos = ((change[0][0] + 0.5) * TILE_SIZE, (change[0][1] + 0.5) * TILE_SIZE) if t == Spawner1Tile: self.npcs.append(Baddie1(self.main, pos)) elif t == Spawner2Tile: self.npcs.append(Baddie2(self.main, pos)) if len(changes) > 0: volume = 1.0 / len(changes) for ch in changes: pos = ((ch[0] + 0.5) * TILE_SIZE, 0 ) #the y doesn't matter. self.play_sound(ch[1], pos, volume) #Finally, we check if the transition has finished. if self.transition.done_transitioning: self.transition = None """ if not self.transition.done_transitioning: if self.transition.stage == 2 and self.transition.delay == 0: for x in xrange(5): pos = ((random.randint(0,self.grid.gridsize[0])*0.5)*TILE_SIZE, (random.randint(0,self.grid.gridsize[1])*0.5)*TILE_SIZE) self.npcs.append(Baddie1(self.main, pos)) self.player.is_hurt = True self.player.hurt = self.player.hurt_length if self.transition.stage >= 2 or self.transition.stage == 0: if len(self.npcs) == 0: if self.main.music.current == 2: self.main.music.cue(3) else: if self.main.music.current == 3: self.main.music.cue(2) else: next_grid = self.prep_next_grid() self.transition = HintedTransition(self.main, self.grid, next_grid, self.visible_grid, flat_delay=400) else: if self.main.music.current == 1 and self.main.music.sound_pos >= self.main.music.intro_trans_beats-1: next_grid = self.prep_next_grid() self.transition = HintedTransition(self.main, self.grid, next_grid, self.visible_grid, flat_delay=0, flat_len=1) """ #Updates the player. self.player.update() if not self.player.dead: #Then updates/prunes NPCs. i = len(self.npcs) - 1 while i >= 0: self.npcs[i].update() npc = self.npcs[i] if npc.dead and not (npc.is_dying or npc.falling): if npc.is_bad and npc.fall == 0: if self.player.health < self.player.max_health: self.drops.append( Heart(self.main, list(npc.pos))) del self.npcs[i] i -= 1 #Then updates/prunes particles. i = len(self.particles) - 1 while i >= 0: self.particles[i].update() if self.particles[i].dead: del self.particles[i] i -= 1 #Then updates/prunes drops. i = len(self.drops) - 1 while i >= 0: self.drops[i].update() if self.drops[i].dead: del self.drops[i] i -= 1 else: if self.player_is_alive: self.player_is_alive = False self.visible_grid.apply_filter((255, 0, 0), BLEND_RGB_MIN) self.main.music.stop() self.main.world.play_sound("player_death", self.player.pos) def move(self): """ World.move - Called by Main. Calls 'move' on all entities. """ if not self.paused or self.player.dead: self.player.move() if not self.player.dead: for npc in self.npcs: npc.move() for particle in self.particles: particle.move() for drop in self.drops: drop.move() # === MOVES THE 'CAMERA' === #first we center it. new_offset = [ float(self.preferred_offset[0]), float(self.preferred_offset[1]) ] if not self.disable_update_offset: #then we check if the player is almost going off of the screen. pl = self.player offset = [0, 0] inset = 200 rect = pygame.Rect([ -new_offset[0] + inset, -new_offset[1] + inset, self.main.screen_size[0] - inset - inset, self.main.screen_size[1] - inset - inset ]) left = pl.rect.left - rect.right top = pl.rect.top - rect.bottom right = rect.left - pl.rect.right bottom = rect.top - pl.rect.bottom m = max(left, top, right, bottom) if m > 0: if abs(offset[0]) < left: offset[0] = left if abs(offset[1]) < top: offset[1] = top if abs(offset[0]) < right: offset[0] = -right if abs(offset[1]) < bottom: offset[1] = -bottom new_offset = [ new_offset[0] - offset[0], new_offset[1] - offset[1] ] #finally, we apply the new offset. new_offset = lerp_pos(self.current_offset, new_offset, 0.1) self.current_offset = new_offset if self.earthquake_amount > 0: new_offset = [ new_offset[0] + random.randint(-1, 1) * self.earthquake_amount, new_offset[1] + random.randint(-1, 1) * self.earthquake_amount ] self.visible_grid.set_offset(new_offset) def render(self): """ World.render - Called by Main. Renders the world and it's contents to the screen. """ if self.fade == None or not self.fade.is_covering_screen: #first we render the background. self.visible_grid.render() for npc in self.npcs: npc.render() for particle in self.particles: particle.render() self.player.render() for drop in self.drops: drop.render() offset = self.visible_grid.offset """ for npc in self.npcs: #Draws it's path if len(npc.path) > 2: new_path = [] for pos in npc.path: new_path.append((pos[0]+offset[0], pos[1]+offset[1])) pygame.draw.lines(self.main.screen, (255,255,0), False, new_path, 2) #Draws it's current target position if npc.target_pos != None: pos = (npc.target_pos[0]+offset[0], npc.target_pos[1]+offset[1]) pygame.draw.circle(self.main.screen, (255,255,0), pos, 4) #Draws it's coordinates if npc.target_pos != None: pos = (int((npc.coords[0]+0.5)*TILE_SIZE+offset[0]), int((npc.coords[1]+0.5)*TILE_SIZE+offset[1])) pygame.draw.circle(self.main.screen, (255,255,255), pos, 4) #Draws players's coordinates pos = (int(self.player.pos[0]+offset[0]), int(self.player.pos[1]+offset[1])) pygame.draw.circle(self.main.screen, (255,255,255), pos, 4) """ #we do letter-boxes for when the player doesn't have control. if self.player.controls_disabled: size = 75 color = (160, 160, 160) self.main.screen.fill(color, (0, 0, self.main.screen_size[0], size), special_flags=BLEND_RGB_MULT) self.main.screen.fill(color, (0, self.main.screen_size[1] - size, self.main.screen_size[0], size), special_flags=BLEND_RGB_MULT) if self.fade != None: self.fade.render() #We increment the current frame number. if not self.paused: self.current_frame += 1