def __init__(self): self.text = Text() self.myPlayer = Player(self) self.myEnemy = Enemy(self) self.quests = Quests(self) self.zonemap = zonemap self.equipment_set = equipment_set
def initialize_player(self): """ (None) -> None Initialize the player character for use in the game loop. """ if not self.player: player_spritesheet = Spritesheet('player.png', 2, 4) self.player = Player(self.screen_w // 2, self.screen_h // 2, 7, *player_spritesheet[0:6]) self.player.set_aiming_image(player_spritesheet[6])
def test_randomize_initial_position(self): test_player = Player() test_player.randomize_initial_position(self.map_for_player_test) self.assertIn(test_player.player_x, range(0, self.map_for_player_test.map_size[0])) self.assertIn(test_player.player_y, range(0, self.map_for_player_test.map_size[1]))
def __init__(self): self.dungeon_map = DungeonMap() self.player_map = PlayerMap() self.player = Player() self.enemy = Enemy() self.is_game_ongoing = False self.time = time.clock() self.enemy_last_position = [] self.enemy_cell = '?'
def __init__(self, scene_manager): Scene.__init__(self, scene_manager) self.level = Level() self.bg = self.level.pre_render_map() self.allsprites = load_spritesheet_nested( 'assets/character_sprites.png') self.sprites = pygame.sprite.LayeredDirty() self.player = Player(self.level, self.allsprites[0], [self.sprites], (1, 1)) monster = MonsterNPC(self.level, self.allsprites[4], [self.sprites], (1, 2)) girl = WanderingNPC(self.level, self.allsprites[1], [self.sprites], (0, 0)) rock = RockNPC(self.level, self.allsprites[3], [self.sprites], (3, 3)) for char in [self.player, girl, rock, monster]: self.sprites.change_layer(char, 1)
def initialize(self): self.score = 0 self.time = 60 if self.bgm_on: pygame.mixer.music.play(-1) # characters self.man: Player = Player(300, self.height - 105, 64, 64) self.goblins: List[Enemy] = [] self.bullets: List[Projectile] = [] # round self.round = 1 self.pass_score = 50 # loops self.shoot_loop = 0 self.shoot_interval = 5 self.enemy_loop = 0 self.enemy_interval = 30 self.dead_loop = 0 self.dead_interval = 40 self.is_dead = False # limits self.bullets_limit = 5 self.enemies_limit = 3
def divide_cards(self): """ Divides cards (Room, Item and Guest): 1. Selects room, murder weapon and killer. 2. Shuffle remaining cards. 3. Splits some cards between Policemen. 4. Creates Players and splits remaining cards between them. """ cards = [] cards.extend(Room.rooms) cards.extend(Item.items) cards.extend(Guest.guests) sec = [randint(0, 8), randint(9, 14), randint(15, 20)] self._secret["room"] = cards[sec[0]] self._secret["item"] = cards[sec[1]] self._secret["guest"] = cards[sec[2]] del cards[sec[2]] del cards[sec[1]] del cards[sec[0]] division = { 3: [2, 2, 2, 6, 6], 4: [2, 1, 2, 4, 5, 4], 5: [2, 1, 1, 3, 4, 3, 4], 6: [1, 1, 1, 3, 3, 3, 3, 3] } shuffle(cards) shuffle(cards) index = 0 for i in range(division[self._players][0]): Police.polices[0].add_card(cards[index]) index += 1 for i in range(division[self._players][1]): Police.polices[1].add_card(cards[index]) index += 1 for i in range(division[self._players][2]): Police.polices[2].add_card(cards[index]) index += 1 for i in range(self._players - 1): p = Player("Player " + str(i + 1), "") for j in range(division[self._players][i + 3]): p.add_card(cards[index]) index += 1
def __init__(self): pygame.init() self.__screen = pygame.display.set_mode([screen_width, screen_height]) self.__clock = pygame.time.Clock() self.__player = Player(self.__screen, Vector(0, 0), 50, 50) self.__finish = Surface(self.__screen, Vector(2400, 200), platform_width, platform_height) self.__platform = (Surface(self.__screen, Vector(20, 240), platform_width, platform_height), Surface(self.__screen, Vector(640, 300), platform_width, platform_height), Surface(self.__screen, Vector(940, 240), platform_width, platform_height), Surface(self.__screen, Vector(1340, 300), platform_width, platform_height), Surface(self.__screen, Vector(1640, 460), platform_width, platform_height), Surface(self.__screen, Vector(2000, 300), platform_width, platform_height))
def __init__(self, game): """ Initialise game run """ self.game = game self.screen = self.game.screen self.settings = self.game.settings # create and draw grid self.grid = Grid(self) # create sprite groups self.characters_group = pygame.sprite.Group( ) # used for all characters (player and enemies) self.hp_counters_group = pygame.sprite.Group( ) # used for all HP counter (player and enemies) self.enemies_group = pygame.sprite.Group( ) # used for enemy characters only # create player self.player = Player(self, self.grid.tiles_dict["player_tile"][0]) self.characters_group.add(self.player)
def initialize(self): self.player = Player(self, batch=self.batch) self.gravitoids.append(self.player) self.sprites.append(self.player) # a countdown clock. Countdown to success. self.timer = Countdown(self, batch=self.batch) self.sprites.append(self.timer) # winning and losing ghosts. # will be a list of GhostOutcome tuples (ghost, win? True/False) self.ghosts_of_christmas_past = []
def start_game(self): self.mapmask = BitMask32(0x1) self.itemmask = BitMask32(0x2) self.map = Map("models/roem.bam") self.player = Player() self.load_sound() self.monsters = [] self.monsters.append(Monster()) self.text_a = OnscreenText(text="HENDRIK-JAN'S", fg=(0, 0, 0, 1), scale=0.06, font=self.font) self.text_a.set_pos(-0.3, 0, 0.3) self.set_text_style(self.text_a) self.text_b = OnscreenText(text="SYNDACTYLY", fg=(0, 0, 0, 1), scale=0.23, font=self.font) self.set_text_style(self.text_b) self.text_b.textNode.setShadow(0.02, 0.02) self.text_c = OnscreenText( text="listen closely (headphones essential)", fg=(1, 1, 1, 1), scale=0.04, font=self.font) self.text_c.set_pos(0, 0, 0. - 0.15) self.text_d = OnscreenText(text="hold left or right arrow to start", fg=(1, 1, 1, 1), scale=0.04, font=self.font) self.text_d.set_pos(0, 0, -0.1) self.text_shown = True self.taskMgr.add(self.update)
class WorldScene(Scene): def __init__(self, scene_manager): Scene.__init__(self, scene_manager) self.level = Level() self.bg = self.level.pre_render_map() self.allsprites = load_spritesheet_nested( 'assets/character_sprites.png') self.sprites = pygame.sprite.LayeredDirty() self.player = Player(self.level, self.allsprites[0], [self.sprites], (1, 1)) monster = MonsterNPC(self.level, self.allsprites[4], [self.sprites], (1, 2)) girl = WanderingNPC(self.level, self.allsprites[1], [self.sprites], (0, 0)) rock = RockNPC(self.level, self.allsprites[3], [self.sprites], (3, 3)) for char in [self.player, girl, rock, monster]: self.sprites.change_layer(char, 1) #self.resume() def resume(self): self._screen.fill((0, 0, 0)) self._screen.blit(self.bg, (0, 0)) pygame.display.flip() for char in self.sprites: char.dirty = 1 def process_input(self, action): """ Return the name of the scene to execute next. Return None if scene is unchanged. """ action_to_dir = { BTN_UP: DIR_N, BTN_DOWN: DIR_S, BTN_LEFT: DIR_W, BTN_RIGHT: DIR_E } if action not in action_to_dir.keys(): return None direction = action_to_dir[action] trigger_encounter = self.player.try_moving_towards(direction) if trigger_encounter: return SCN_ENCOUNTER def tick(self, fps): self.sprites.clear(self._screen, self.bg) self.sprites.update(fps) changed_rects = self.sprites.draw(self._screen) pygame.display.update(changed_rects)
def main(): pygame.init() BACKGROUND_COLOR = (144, 201, 120) WINDOW_SIZE = (400, 300) screen = pygame.display.set_mode(WINDOW_SIZE) pygame.display.set_caption('text') clock = pygame.time.Clock() FPS = 60 player = Player('hero', 50, 184, 1, 4, screen) moving_left = False moving_right = False run = True level = map.Map('test_scene.tmx', 'data/maps') level.convert_images() level.get_rect_tiles() while run: for event in pygame.event.get(): if event.type == QUIT: run = False if event.type == pygame.KEYDOWN: if event.key == K_a: moving_left = True if event.key == K_d: moving_right = True if event.key == K_w and not player.in_air: player.jump = True if event.type == pygame.KEYUP: if event.key == K_a: moving_left = False if event.key == K_d: moving_right = False if event.key == K_ESCAPE: run = False screen.fill(BACKGROUND_COLOR) player.move(moving_left, moving_right, level.dict_tiles) level.render(screen) player.draw() pygame.display.update() clock.tick(FPS) pygame.quit() sys.exit()
def test_valid_move(self): valid_moves = [('w', 'You have moved up'), ('a', 'You have moved left'), ('s', 'You have moved down'), ('d', 'You have moved right')] test_player = Player() test_player.randomize_initial_position(self.map_for_player_test) test_player.player_x = self.map_for_player_test.map_size[0] / 2 test_player.player_y = self.map_for_player_test.map_size[1] / 2 for move, move_message in valid_moves: with self.assertLogs(my_logger, level=logging.INFO) as log: result = test_player.make_move( move, *self.map_for_player_test.map_size) self.assertTrue(result) self.assertEqual(log.output[0], ''.join(["INFO:dungeon_logger:", move_message]))
def main(): choice = MainMenuPrompt() if choice == 'n': NewGame() elif choice == 'l': LoadGame() elif choice == 'e': Exit() else: print("Invalid Option!") hero = Player("John") newMap = Map(10, 10) for _ in range(3): newMap.addCharacter(Monster()) newMap.addCharacter(hero) while True: os.system("clear") print(newMap) newMap.update()
Primary Program Variables and initialization """ #intro = open('txt/intro.txt') #intro = intro.readlines() #t = 3.0 #for items in intro: # print items # time.sleep(t) # t -= 0.1 actions = ['ask', 'demand', 'give', 'hold', 'look', 'take', 'me'] movement = ['hop', 'skip', 'jump', 'retreat'] board = Board(3) player = Player('Mysterious Player', 'The Mysterious Player you control in a mysterious fashion') command = '' current_room = board.getRoom(player.location) """ initialize Twitter authorization and access """ consumer_key ='pHe4zVpJynRtg0QcuFng' consumer_secret = 'zOxKCbTKnL7NnDh64MB7jurQouR7Kr02d1WNhB0qc' access_token = '87458583-HxhtzCcc6Qcq3qfsXN9zJij5pukfvv8jo2Cgc2XlA' access_token_secret = '6mpCNqHdw98vdFeupb7oDEYIqlz35LVn1WdVixFnOUhZc' auth = tweepy.OAuthHandler(consumer_key, consumer_secret) auth.set_access_token(access_token, access_token_secret)
from character import Player from attack_kind import FireAttackKind, IceAttackKind from monsters import FireMonster, IceMonster, StoneMonster, KungfuMonster, ArrowMonster fm = FireMonster() im = IceMonster() sm = StoneMonster() kfm = KungfuMonster() monsters = [] monsters.extend((fm, im, sm, kfm)) # Dependency Injection : DI --> main.py 에서 player = Player('john', 120, 20, FireAttackKind(), IceAttackKind()) for mon in monsters: player.attack(mon, 'Fire') for mon in monsters: print(mon.get_attack_kind()) mon.attack(player, mon.get_attack_kind()) new_mon = ArrowMonster() print(player)
escape_call = Escape() while True: pygame.time.Clock().tick(40) pos = pygame.mouse.get_pos() if rect.collidepoint(pos): screen.blit(cont_go, rect) else: screen.blit(cont_no, rect) for event in pygame.event.get(): if event.type == QUIT: pygame.quit() sys.exit() elif event.type == pygame.KEYDOWN: if event.key == pygame.K_ESCAPE: escape_call.escape_menu(screen) break elif event.type == MOUSEBUTTONDOWN: if rect.collidepoint(pos): return pygame.display.update() if __name__ == '__main__': pygame.display.init() screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT)) player = Player() repair(screen, player, None)
def play(): player = Player('Bill') bad = Player('Baddy') bad.inventory('add', {u'description': 'GUN4', u'dmg': [1, 2, 3], u'load': 3, u'name': u'P3distol 4', u'reqs': u'Needs more fun', u'title': u'TITLE4', u'value': 6}) bad.inventory('add', {u'description': 'GUN4', u'dmg': [1, 2, 3], u'load': 3, u'name': u'3distol 4', u'reqs': u'Needs more fun', u'title': u'ITLE4', u'value': 67}) player.inventory('add', {u'description': 'GUNt4', u'dmg': [1, 2, 3], u'load': 3, u'name': u'tt3distol 4', u'reqs': u'Needs more fun', u'title': u'tITLEtt4', u'value': 666}) player.inventory('add', {u'description': 'GUaaasdasdNt4', u'dmg': [1, 2, 3], u'load': 3, u'name': u'tt3distol 4', u'reqs': u'Needs more fun', u'title': u'tITLEtt4', u'value': 6}) player.inventory('add', {u'description': 'wGUNt4', u'dmg': [1, 2, 3], u'load': 3, u'name': u't4t3distol 5', u'reqs': u'Needs more fun', u'title': u'tITLEtt4', u'value': 66}) player.inventory('add', {u'description': 'wGUNt4', u'dmg': [1, 2, 3], u'load': 3, u'name': u't4t3distol 5', u'reqs': u'Needs more fun', u'title': u'tITLEtt4', u'value': 66}) playermove = Do.roll() print playermove act = Fight(player,bad) return act.combat()
class Game: """ Main game class Contains other game classes: dungeon map, player map, player itself """ def __init__(self): self.dungeon_map = DungeonMap() self.player_map = PlayerMap() self.player = Player() @log_decorator def setup_game(self): """ Game startup method: user should choose between playing new game or loading save """ my_logger.debug("Game start choice") start_game_choice = input( 'Enter "y" if you want to play a new game or\n"load" if you want to load existing game:\n' ) my_logger.debug("Game start choice handling") if start_game_choice == "load": self.load_game() else: map_request = input( 'Enter preferable map size in format "width:height", or just press enter to play with default map:\n' ) my_logger.info("Generating map...") if not len(map_request): map_size = [20, 10] else: map_size = [int(token) for token in map_request.split(':')] self.dungeon_map.set_map_size(*map_size) self.dungeon_map.generate_map() my_logger.info("Map has been generated successfully!") self.player_map.set_map_size(*map_size) self.player_map.init_map() self.player.reset() self.player.randomize_initial_position(self.dungeon_map) self.player_map.update_map(self.dungeon_map, self.player.player_x, self.player.player_y) self.player_map.draw_map() @log_decorator def load_game(self): """ Game load (pickle!) """ my_logger.info("Loading game...") in_file = open('dungeon.sav', 'rb') data = pickle.load(in_file) [ self.dungeon_map.dungeon_map, self.dungeon_map.map_size, self.player_map.dungeon_map, self.player.player_x, self.player.player_y, self.player.health, self.player.treasures ] = data my_logger.info("Game has been loaded!") @log_decorator def save_game(self): """ Game save (pickle!) """ data = [ self.dungeon_map.dungeon_map, self.dungeon_map.map_size, self.player_map.dungeon_map, self.player.player_x, self.player.player_y, self.player.health, self.player.treasures ] out_file = open('dungeon.sav', 'wb') pickle.dump(data, out_file) @log_decorator def run_farame(self): """ Game frame. Returns true if game could be resumed and false otherwise """ ret_value = True move = input( '\nEnter your move, please (w - up, d - right, s - down, a - left), or "save" for save game:\n' ) if move == "save": self.save_game() ret_value = False self.player.make_move(move, *self.dungeon_map.map_size) self.player_map.update_map(self.dungeon_map, self.player.player_x, self.player.player_y) self.player_map.draw_map() if self.dungeon_map.get_cell_content(self.player.player_x, self.player.player_y) == 'T': self.dungeon_map.set_cell_content(self.player.player_x, self.player.player_y, '-') self.player.add_treasure() elif self.dungeon_map.get_cell_content(self.player.player_x, self.player.player_y) == 'X': self.dungeon_map.set_cell_content(self.player.player_x, self.player.player_y, '-') self.player.apply_damage() self.player.draw_character() if self.player.is_dead(): my_logger.info("\n}}}This is a trap! You loose!{{{\n") ret_value = False elif self.player.is_winner(): my_logger.info("\n>>>This is a treasure! You are victorious!<<<\n") ret_value = False return ret_value
class Game: """ Main game class Contains other game classes: dungeon map, player map, player itself """ def __init__(self): self.dungeon_map = DungeonMap() self.player_map = PlayerMap() self.player = Player() @log_decorator def setup_new_game(self): """ This function is used to generate new map of size, specified by user """ while True: map_request = input( 'Enter preferable map size in format "width:height", or just press enter to play with default map:\n' ) my_logger.info("Generating map...") if not len(map_request): map_size = [20, 10] break else: try: map_size = [int(token) for token in map_request.split(':')] break except ValueError as val_error: my_logger.exception(val_error) my_logger.error("Try to enter map size once again!") self.dungeon_map.set_map_size(*map_size) self.dungeon_map.generate_map() my_logger.info("Map has been generated successfully!") self.player_map.set_map_size(*map_size) self.player_map.init_map() self.player.reset() self.player.randomize_initial_position(self.dungeon_map) @log_decorator def setup_game(self): """ Game startup method: user should choose between playing new game or loading save """ my_logger.debug("Game start choice") start_game_choice = input( 'Enter "y" if you want to play a new game or\n"load" if you want to load existing game:\n' ) my_logger.debug("Game start choice handling") if start_game_choice == "load": try: self.load_game() except (FileNotFoundError, pickle.UnpicklingError) as file_error: my_logger.exception(file_error) if isinstance(file_error, FileNotFoundError): my_logger.error( "There is no dungeon.sav file! Start a new game instead!" ) elif isinstance(file_error, pickle.UnpicklingError): my_logger.error( "dungeon.sav file is corrupted! Start a new game instead!" ) self.setup_new_game() else: self.setup_new_game() self.player_map.update_map(self.dungeon_map, self.player.player_x, self.player.player_y) self.player_map.draw_map() @log_decorator def load_game(self): """ Game load (pickle!) """ my_logger.info("Loading game...") in_file = open('dungeon.sav', 'rb') data = pickle.load(in_file) [ self.dungeon_map.dungeon_map, self.dungeon_map.map_size, self.player_map.dungeon_map, self.player.player_x, self.player.player_y, self.player.health, self.player.treasures ] = data my_logger.info("Game has been loaded!") @log_decorator def save_game(self): """ Game save (pickle!) """ data = [ self.dungeon_map.dungeon_map, self.dungeon_map.map_size, self.player_map.dungeon_map, self.player.player_x, self.player.player_y, self.player.health, self.player.treasures ] try: out_file = open('dungeon.sav', 'wb') except PermissionError as premission_error: my_logger.exception(premission_error) my_logger.error( "Unable to save game! So sorry! But you can play again!") pickle.dump(data, out_file) @log_decorator def run_farame(self): """ Game frame. Returns true if game could be resumed and false otherwise """ ret_value = True move = input( '\nEnter your move, please (w - up, d - right, s - down, a - left), or "save" for save game:\n' ) if move == "save": self.save_game() ret_value = False self.player.make_move(move, *self.dungeon_map.map_size) self.player_map.update_map(self.dungeon_map, self.player.player_x, self.player.player_y) self.player_map.draw_map() if self.dungeon_map.get_cell_content(self.player.player_x, self.player.player_y) == 'T': self.dungeon_map.set_cell_content(self.player.player_x, self.player.player_y, '-') self.player.add_treasure() elif self.dungeon_map.get_cell_content(self.player.player_x, self.player.player_y) == 'X': self.dungeon_map.set_cell_content(self.player.player_x, self.player.player_y, '-') self.player.apply_damage() self.player.draw_character() if self.player.is_dead(): my_logger.info("\n}}}This is a trap! You loose!{{{\n") ret_value = False elif self.player.is_winner(): my_logger.info("\n>>>This is a treasure! You are victorious!<<<\n") ret_value = False return ret_value
i, len1 = 0,len(mazeRender) while i < len1: j, len2 = 0,len(mazeRender[i]) while j < len2: if mazeRender[i][j][0] == 0 or mazeRender[i][j][0] == 1 or mazeRender[i][j][0] == 2 or mazeRender[i][j][0] == 3 or mazeRender[i][j][0] == 4: #Represents walking paths, white snow block pygame.draw.rect(window,(255,250,250),((i)*blocksW,(j)*blocksH,blocksW,blocksH)) if mazeRender[i][j][1] == 1: #Represents Bomb, Black pygame.draw.rect(window, (0,0,0),((i)*blocksW,(j)*blocksH,blocksW,blocksH)) if mazeRender[i][j][1] == 2: #Represents explosion, orange pygame.draw.rect(window,(255,165,0),((i)*blocksW,(j)*blocksH,blocksW,blocksH)) if mazeRender[i][j][0] == 1: #Represents player 1. blue Bomberman = Player(i,j,blocksW-10,blocksH-10) playerPos = [i,j] values = Bomberman.renderValues() pygame.draw.rect(window,(0,0,255),(((values[0])*blocksW)+4,((values[1])*blocksH)+4,values[2],values[3])) if mazeRender[i][j][0] == 2: #Represents player 2. Red NumNPC -=1 NPCs.append(NPC(i,j,blocksW-10,blocksH-10,1,playerPos)) values = NPCs[0].renderValues() pygame.draw.rect(window,(255,0,0),(((values[0])*blocksW)+4,((values[1])*blocksH)+4,values[2],values[3])) if mazeRender[i][j][0] == 3: #Represents player 3. Green NumNPC -=1 NPCs.append(NPC(i,j,blocksW-10,blocksH-10,2,playerPos)) values = NPCs[1].renderValues() pygame.draw.rect(window,(0,200,0),(((values[0])*blocksW)+4,((values[1])*blocksH)+4,values[2],values[3]))
def __init__(self, config=None): """Create a game world using the supplied configuration details. If no config specified, then use default_config world configuration. The game world has: title, rooms, characters, items, messages, and the success criteria. """ # use default_config is none supplied if config == None: config = default_config # instance variables for a world self.title = config['title'] self.rooms = {} self.items = {} self.characters = {} self.player = None self.messages = config['messages'] self.success = config['success'] # populate the world using the configuration details try: # configure rooms doing = "rooms" # room config has: (name, description, key_item, used_msg)* keyitems = [] # list of key items to config later for conf in config['rooms']: self.rooms[conf[0]] = Room(conf[0], conf[1]) if conf[3] != None: # key items to be set when have items keyitems.append( (conf[0], conf[2], conf[3])) # (room, item, msg) # configure links between rooms doing = "links" # links config has: (room1, direction1, room2, direction2)* for conf in config['links']: self.rooms[conf[0]].link_room(self.rooms[conf[2]], conf[1], conf[3]) # configure items doing = "items" # items config has: (name, description, location) player_items = [] # list of player items to config later for conf in config['items']: self.items[conf[0]] = Item(conf[0], conf[1]) if conf[2] in self.rooms: # place item in room self.rooms[conf[2]].leave(self.items[conf[0]]) else: # item on character to add later player_items.append((conf[0], conf[2])) # now configure key_items in rooms - has (room, item, msg) doing = "key_items" for conf in keyitems: self.rooms[conf[0]].set_key_item(self.items[conf[1]], conf[2]) # configure characters (enemies, friends, player) doing = "enemies" # links config has: (name, description, conversation, location, weakness, defeat_msg)* for conf in config['enemies']: self.characters[conf[0]] = Enemy(conf[0], conf[1]) self.characters[conf[0]].set_conversation(conf[2]) self.characters[conf[0]].move_to(self.rooms[conf[3]]) if conf[4] != None: self.characters[conf[0]].set_weakness( self.items[conf[4]], conf[5]) doing = "friends" # friends config has: (name, description, conversation, location, desire, thank_msg)* for conf in config['friends']: self.characters[conf[0]] = Friend(conf[0], conf[1]) self.characters[conf[0]].set_conversation(conf[2]) self.characters[conf[0]].move_to(self.rooms[conf[3]]) if conf[4] != None: self.characters[conf[0]].set_desires( self.items[conf[4]], conf[5]) doing = "players" # players config has: (name, description, location)* num_players = 0 for conf in config['players']: self.characters[conf[0]] = Player(conf[0], conf[1]) self.characters[conf[0]].move_to(self.rooms[conf[2]]) self.player = self.characters[conf[0]] num_players += 1 if num_players != 1: print("You can only have 1 player character in the game!") # now configure player_items on characters - has (item, character) doing = "player_items" for conf in player_items: self.characters[conf[1]].add(self.items[conf[0]]) except (IndexError, KeyError, ValueError) as msg: print("### Error: Incorrect format or values in " + doing + " config: " + str(conf)) print(str(msg)) raise
class Level(event.EventDispatcher): def __init__(self, p_window): self.p_window = p_window winx, winy = self.p_window.get_size() self.camera = camera.Camera(0,0, winx, winy, 50) self.over = False # Setup background, draw batch, spritelist, player self.background = load(fp('background.png')) self.batch = graphics.Batch() self.sprites = [] self.player = None self.surface_y = 195 self.gravitoids = [] self.enemies = [] self.initialize() # Setup the level def initialize(self): self.player = Player(self, batch=self.batch) self.gravitoids.append(self.player) self.sprites.append(self.player) # a countdown clock. Countdown to success. self.timer = Countdown(self, batch=self.batch) self.sprites.append(self.timer) # winning and losing ghosts. # will be a list of GhostOutcome tuples (ghost, win? True/False) self.ghosts_of_christmas_past = [] # Connect the level's handlers, to the window's dispatchers def connect(self): self.p_window.push_handlers( self.on_update, self.on_draw ) # Pop the window's newest added handlers, hopefully this level's! def disconnect(self): self.p_window.pop_handlers() # Gets called once per tick by the game_window def on_update(self, dt): player_box = self.player.get_collision_box() for e in self.enemies: if e.get_collision_box().isCollide(*player_box.get_values()): try: self.handle_the_dead(e) except ValueError: # lost the game! self.batch = graphics.Batch() self.sprites[:] = [] self.background = load(fp('loser.png')) self.over = True self.do_gravity(dt) if not self.over: self.dispatch_event('on_level_update', dt, self.camera) self.game_strategy(dt) def game_strategy(self, dt): """ Game strategising comes into play here. A countdown is created and then once the time is up, a new ghost appears and countdown clock begins ticking again. """ if self.timer.alarm: if self.enemies and self.enemies[-1].x == 700: return self.timer.reset(random.randint(2, 5)) enemy = Enemy(self, batch=self.batch) self.sprites.append(enemy) self.enemies.append(enemy) def do_gravity(self, dt): for g in self.gravitoids: if g.y <= self.surface_y: g.velocity_y = 0 g.y = self.surface_y g.touch_ground = True else: g.velocity_y -= settings.GRAVITY * dt def char_punch(self, attack_box): """ If a character punches an enemy, the enemy dies and goes to the naughty corner. """ if not self.player.orientation_right: return for e in self.enemies: if attack_box.isCollide(*e.get_collision_box().get_values()): try: self.player_is_victorious_with_punch(e) except TypeError: self.batch = graphics.Batch() self.sprites[:] = [] self.over = True self.background = load(fp('winner.png')) # Gets called once per tick by the game loop def on_draw(self): self.p_window.clear() self.background.blit(0,0) self.batch.draw() # Called by dispatcher on game_window, when required def on_key_press(self, symbol, modifiers): """ Look for left and right arrows. """ handlers = { key.ESCAPE: self.handle_quit, pyglet.window.key.UP: self.handle_up_down, pyglet.window.key.LEFT: self.handle_left_down, pyglet.window.key.RIGHT: self.handle_right_down} try: handler = handlers[symbol] except KeyError: pass else: handler() def handle_up_down(self): """ Make character jump. """ if self.player: if not self.player.movement: self.player.jump() def handle_left_down(self): """ Move character left. """ if self.player: if not self.player.movement: self.player.step_left() def handle_right_down(self): """ Move character right. """ if self.player: if not self.player.movement: self.player.step_right() def handle_quit(self): self.p_window.reset() def player_is_victorious_with_punch(self, ghost): """ The player has successfully punched the ghost! """ ghost.set_dead() punched_ghosts = filter(lambda x: not x.won, self.ghosts_of_christmas_past) if len(punched_ghosts) >= 3: raise TypeError try: maxx = punched_ghosts[-1].ghost.x except IndexError: maxx = 0 newx = maxx + ghost.width + 10 ghost.x, ghost.y = newx, 50 self.ghosts_of_christmas_past.append( GhostOutcome(ghost, False)) def handle_the_dead(self, ghost): """ The ghost has hit our player! thats a bad thing. Put the ghost up on a victory tally somewhere.. If there has been three dead already. Exit the game. """ ghost.set_dead() victorious_ghosts = filter(lambda x: x.won, self.ghosts_of_christmas_past) if len(victorious_ghosts) >= 3: raise ValueError try: minx = victorious_ghosts[-1].ghost.x except IndexError: minx = settings.RESOLUTION[0] newx = minx - ghost.width - 10 ghost.x, ghost.y = newx, 50 self.ghosts_of_christmas_past.append( GhostOutcome(ghost, True))
class Level(object): """ Level class that keeps track of all level objects and visuals. """ def __init__(self, path_img, wall_img): """ (str, str) -> Level Instantiate a blank level. """ # ----- Parameter-based properties ----- self.path_image = load_image(path_img) self.wall_image = load_image(wall_img) # ----- Intersections, rooms, paths ----- self.directions = [] # List of integers for intersection directions self.paths = [] # List of path Rect objects self.rooms = [] # List of room Rect objects self.path_width = 260 # Width of each path self.wall_width = 35 # Thickness of each wall self.wall_surfaces = [] # List of wall (outer) Surfaces for rooms and paths self.floor_surfaces = [] # List of floor (inner) Surfaces # ----- Level objects ----- self.items = [] self.ammo = 15 self.key = None self.blood = [] # ----- Characters ----- self.player = None self.enemies = [] # ----- I/O ----- self.keys = None self.mouse_buttons = [0] * 3 # ----- Other ----- self.bullets = [] # List of active bullets self.endpoint = [] # [x, y] co-ordinates of the end of the level self.screen_w = None # Screen width and height self.screen_h = None # This data will be obtained later self.level_num = 1 # Current level number @staticmethod def get_opposite_dir(direction): """ (int) -> int Returns an integer index representing the opposite direction. """ return (2 + direction) % 4 def populate_directions(self, numdirections): """ (int) -> None Determine path directions (directions are integers from 0 to 3). """ self.directions = [] while len(self.directions) < numdirections: try: possible_dirs = [] for i in range(4): prev_dir = self.directions[-1] if prev_dir != i and prev_dir != self.get_opposite_dir(i): possible_dirs.append(i) self.directions.append(choice(possible_dirs)) self.populate_paths() collision = self.paths[-1].collidelist(self.rooms) != -1 or\ self.paths[-1].collidelist(self.paths[:-1]) != -1 while collision and len(possible_dirs) > 1: possible_dirs.remove(self.directions[-1]) del self.directions[-1] self.directions.append(choice(possible_dirs)) self.populate_paths() collision = self.paths[-1].collidelist(self.rooms) != -1 or \ self.paths[-1].collidelist(self.paths[:-1]) != -1 if collision: return except IndexError: self.directions.append(randint(0, 3)) def increment(self): """ (None) -> None Resets all relevant level objects and increments the level number by 1. """ self.level_num += 1 self.generate() def populate_paths(self): """ (None) -> None Using the generated directions, create physical path Rects. """ self.paths = [] x = self.rooms[0].centerx y = self.rooms[0].centery if self.directions[0] == 0: x += self.rooms[0].width // 2 elif self.directions[0] == 2: x -= self.rooms[0].width // 2 elif self.directions[0] == 1: y -= self.rooms[0].height // 2 else: y += self.rooms[0].height // 2 for direction in self.directions: path_length = randint(3 * self.path_width, 7 * self.path_width) if direction == 0: self.paths.append(pygame.Rect(x, y, path_length, self.path_width)) x += (path_length - self.path_width) elif direction == 2: self.paths.append(pygame.Rect(x - path_length, y, path_length, self.path_width)) x -= path_length elif direction == 1: self.paths.append(pygame.Rect(x, y - path_length, self.path_width, path_length)) y -= path_length else: self.paths.append(pygame.Rect(x, y, self.path_width, path_length)) y += (path_length - self.path_width) # Determine the level endpoint sample_lock = Lock(x, y, 'lock_blue.png') lock_rect = sample_lock.rect.inflate(10, 10).clamp(self.paths[-1]) self.endpoint = list(lock_rect.topleft) def populate_output_surfaces(self): """ (None) -> None Caches each level object as a list of Surfaces to accelerate and facilitate blitting. """ self.wall_surfaces = [] self.floor_surfaces = [] for rect in self.paths + self.rooms: # Create a blank surface to use for the "floor" of each room and hallway. floor_surface = pygame.Surface(rect.size).convert() # Tile the floor tiles all over the newly created Surface, starting from the origin (0, 0). self.tile(self.path_image, floor_surface, pygame.Rect((0, 0), rect.size)) # Add the floor surface to the internal list of all floor surfaces. self.floor_surfaces.append(floor_surface) # Calculate an enlarged Rect to use for the outer wall. wall_rect = rect.inflate(2 * self.wall_width, 2 * self.wall_width) # Perform the same steps as above, except for the wall tiles instead of the floor tiles. wall_surface = pygame.Surface(wall_rect.size).convert() self.tile(self.wall_image, wall_surface, pygame.Rect((0, 0), wall_rect.size)) self.wall_surfaces.append(wall_surface) def add_pass_through_rooms(self, x=5): """ (None, [int]) -> None Attempt to add 'x' number of rooms such that the paths go through the rooms. """ if len(self.rooms) > 1: self.rooms = [self.rooms[0]] descending_paths = self.paths[:] descending_paths.sort(key=lambda r: max(r.width, r.height)) descending_paths.reverse() for i in range(x): try: height = width = max(descending_paths[i].width, descending_paths[i].height) // 5 top = descending_paths[i].centery - height // 2 left = descending_paths[i].centerx - width // 2 if width - self.path_width > 40: self.rooms.append(pygame.Rect(left, top, width, height)) except IndexError: print('WARNING: Attempted to add pass-through room to nonexistent path!') def add_item(self, image, type='food'): room = choice(self.rooms + self.paths) x = randint(room.left, room.right - image.get_width()) y = randint(room.top, room.bottom - image.get_height()) self.items.append(Item(image, x, y, type)) def generate(self, game=None): """ (None, Game) -> None Generate a pseudorandom world with the given Game instance. """ # Generate the central room. self.rooms = [] if game is not None: self.screen_w = w = game.screen_w self.screen_h = h = game.screen_h else: w = self.screen_w h = self.screen_h room_size = 3 * self.path_width // 2 self.rooms.append(pygame.Rect(w // 2 - room_size, h // 2 - room_size, 2 * room_size, 2 * room_size)) # Determine path directions (Directions are integers from 0-3). self.populate_directions(2 * self.level_num + 3) # Convert the directions to paths. self.populate_paths() # Add pass-through room areas. self.add_pass_through_rooms(abs(len(self.paths) - 2)) # Cache level object Surfaces self.populate_output_surfaces() # Prepare game objects. self.initialize_player() enemy_sheet = Spritesheet('zombiebasic.png', 4, 3) regular_zombie_images = list(enemy_sheet[0:3]) + list(enemy_sheet[4:7]) weak_zombie_images = [load_image('zombie.png')] num_enemies = len(self.rooms) * 2 self.enemies = [] for x, y in self.get_multiple_enemy_locations(num_enemies): if randint(0, 1): self.enemies.append(Enemy(x, y, 4, *regular_zombie_images)) self.enemies[-1].health = randint(2, 3) * 50 else: self.enemies.append(Enemy(x, y, 5, *weak_zombie_images)) self.enemies[-1].health = 50 self.lock = Lock(self.endpoint[0], self.endpoint[1], 'lock_blue.png') # Add food and pickups self.items = [] num_foods, num_health_packs, num_ammo_packs = 3 * len(self.rooms) // 2, \ len(self.rooms) // 2, len(self.rooms) // 3 + 1 food_images = Spritesheet('food.png', 14, 8) # Spritesheet object for food items food_images *= 1.4 # Enlarge the spritesheet icon_images = Spritesheet('icons.png', 3, 2) # Spritesheet object for icons icon_images *= 1.5 health_pack_image = icon_images[0] # Extract the health pack image ammo_pack_image = load_image('ammo.png') for i in range(num_foods): image = choice(food_images[:]) self.add_item(image) for i in range(num_health_packs): self.add_item(health_pack_image, 'health') for i in range(num_ammo_packs): self.add_item(ammo_pack_image, 'ammo') self.blood = [] self.blood_images = enemy_sheet[10], enemy_sheet[9] # Large and small blood splatter # Add a key image = load_image('keyblue.png') room = choice(self.rooms) x = randint(room.left, room.right - image.get_width()) y = randint(room.top, room.bottom - image.get_height()) self.key = Key(x, y, image) def shift(self, dx, dy): """ (int, int) -> None Shift the entire level by the given increments (+x, +y is right and down). """ for rect in self.paths + self.rooms: rect.move_ip(dx, dy) for thing in self.blood + self.enemies + self.items + self.bullets + [self.lock] + [self.key]: thing.shift(dx, dy) def get_multiple_enemy_locations(self, x): """ (int) -> list Return a list with size "x" of [x, y] position lists that represent appropriate enemy spawn locations. """ enemy_locations = [] rooms = self.rooms[1:] + self.paths[1:] for i in range(x): rect = rooms[i % len(rooms)] offset_x = randint(-rect.width // 4, rect.width // 4) offset_y = randint(-rect.height // 4, rect.height // 4) enemy_locations.append([rect.centerx + offset_x, rect.centery + offset_y]) return enemy_locations def is_collision(self, point): """ (Rect) -> bool Return True if the given point collides with any wall, False otherwise. """ for rect in self.paths + self.rooms: if rect.collidepoint(point): return False return True def initialize_player(self): """ (None) -> None Initialize the player character for use in the game loop. """ if not self.player: player_spritesheet = Spritesheet('player.png', 2, 4) self.player = Player(self.screen_w // 2, self.screen_h // 2, 7, *player_spritesheet[0:6]) self.player.set_aiming_image(player_spritesheet[6]) def update_player(self): """ (None) -> None Update the player object based on user inputs. """ # Gather info should_shoot = pygame.mouse.get_pressed()[0] and not self.mouse_buttons[0] self.keys = pygame.key.get_pressed() self.mouse_buttons = pygame.mouse.get_pressed() up, down, left, right = self.keys[K_w], self.keys[K_s], self.keys[K_a], self.keys[K_d] self.player.aiming = pygame.mouse.get_pressed()[-1] # Set the player's direction if left: self.player.set_direction(LEFT) elif up: self.player.set_direction(UP) elif right: self.player.set_direction(RIGHT) elif down: self.player.set_direction(DOWN) else: self.player.set_direction() # Override the player's direction if they're aiming if self.player.aiming: self.player.rotate(pygame.mouse.get_pos()[0], pygame.mouse.get_pos()[1]) self.player.set_speed() # Shoot a bullet if the player presses the left mouse button - decrease ammo and food as well if self.player.aiming and should_shoot and self.ammo > 0: self.bullets.append(Bullet(BLACK, self.player.x, self.player.y, 16, self.player.angle)) self.player.hunger += 0.05 self.ammo = max(0, self.ammo - 1) # Update the player and obtain the new speed to shift the level self.player.update() vx, vy = self.player.get_speed() vx, vy = -vx, -vy self.shift(vx, vy) # Start reducing health when hunger gets high if self.player.hunger >= HUNGER_LIMIT and randint(0, 75) == 0: self.player.health -= 5 def rebound_character(self, character, stopdir=LEFT): """ (Character, [int]) -> None Handle wall collisions that require the character to no longer go in the given stop direction. """ if stopdir == LEFT: vx = character.top_speed vy = 0 elif stopdir == RIGHT: vx = -character.top_speed vy = 0 elif stopdir == DOWN: vx = 0 vy = -character.top_speed else: vx = 0 vy = character.top_speed character.image_counter = 0 if not isinstance(character, Player): character.shift(vx, vy) else: self.shift(-vx, -vy) def handle_wall_collision(self, character): """ (Character) -> None Check and react to collisions between the given Character and all walls. """ character.possible_directions = [i for i in xrange(4)] e = self.is_collision(character.get_east()) ne = self.is_collision(character.get_north_east()) n = self.is_collision(character.get_north()) nw = self.is_collision(character.get_north_west()) w = self.is_collision(character.get_west()) sw = self.is_collision(character.get_south_west()) s = self.is_collision(character.get_south()) se = self.is_collision(character.get_south_east()) if w or sw or nw: self.rebound_character(character, LEFT) if n or ne or nw: self.rebound_character(character, UP) if ne or e or se: self.rebound_character(character, RIGHT) if s or sw or se: self.rebound_character(character, DOWN) def handle_pickups(self): """ (None) -> None Check for and react to collisions with items """ for item in self.items: if not item.is_alive() or not self.player.collides_with(item): continue item.destroy() if item.type == 'food': self.player.hunger -= 3 self.player.hunger = max(self.player.hunger, 0) elif item.type == 'health': self.player.health += 10 elif item.type == 'ammo': self.ammo += randint(4, 16) def collide_with_player(self, character): """ (Character) -> None Check for and handle collisions between the given Character and the player. """ if character.collides_with(self.player): self.player.health -= character.damage self.shift(self.player.vx, self.player.vy) character.shift(-2 * character.vx, -2 * character.vy) self.blood.append(Splatter(self.player.x, self.player.y, self.blood_images[1])) if len(self.blood) > 25: self.blood.pop(0) def update(self): """ (None) -> None Update the state of the Level. """ self.update_player() self.handle_wall_collision(self.player) if self.player.get_speed() != (0, 0): self.player.hunger += 0.005 new_enemies = [] for enemy in self.enemies: enemy.update() everything = self.paths + self.rooms if self.player.rect.collidelist(everything) == enemy.rect.collidelist(everything): enemy.move_to_target(self.player.x, self.player.y) self.handle_wall_collision(enemy) self.collide_with_player(enemy) if enemy.health > 0: new_enemies.append(enemy) else: self.blood.append(Splatter(enemy.x, enemy.y, self.blood_images[0])) self.enemies = new_enemies self.handle_pickups() for item in self.items + [self.key]: item.update() if self.key and self.player.collides_with(self.key): self.key.visible = False self.lock.unlock() if not self.lock.locked and self.player.collides_with(self.lock): pygame.time.delay(1000) self.increment() enemy_rects = [enemy.rect for enemy in self.enemies] bullets = [] for bullet in self.bullets: index = bullet.rect.collidelist(enemy_rects) if index > -1: self.enemies[index].health -= bullet.damage continue if not (0 <= bullet.x <= self.screen_w and 0 <= bullet.y <= self.screen_h) or \ self.is_collision((bullet.x, bullet.y)): continue bullet.update() bullets.append(bullet) self.bullets = bullets @staticmethod def tile(source, dest, rect): """ (Surface, Surface, Rect) -> None Completely tile the given destination surface with tiles of the source surface, within the bounds specified by the rect argument. """ for x in xrange(rect.left, rect.right, source.get_width()): for y in xrange(rect.top, rect.bottom, source.get_height()): dest.blit(source, (x, y), (0, 0, rect.right - x, rect.bottom - y)) def draw(self, surface): """ (Surface) -> None Draw all level objects onto the given Surface. """ # Get a list of every Rect that represents a room or hallway. rects = self.paths + self.rooms # Iterate through all of the cached wall surfaces and blit them. for i in range(len(rects)): surface.blit(self.wall_surfaces[i], rects[i].inflate([2 * self.wall_width] * 2)) # Iterate through all of the cached floor surfaces and blit them - smaller than the wall surfaces # due to the lack of a border. for i in range(len(rects)): surface.blit(self.floor_surfaces[i], rects[i]) # Draw enemies, items, and bullets for item in self.blood + [self.lock] + self.items + [self.key] + self.enemies + self.bullets: item.draw(surface) # Draw player self.player.draw(surface)
# update the display every iteration of this loop pygame.display.update() player.credits += loot salvage(screen, board, player, assets) player.drain_shields() return True if __name__ == "__main__": # Run battle.py directly to test battle functionality pygame.init() pygame.display.init() screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT)) # declare the size of the map assets = GameAssets() escape_call = Escape() player = Player() player.move(0, SCREEN_HEIGHT / 3) basics = assets.all_cards['basic'] for _ in range(4): player.all_cards.append(basics[0].copy()) player.all_cards.append(basics[1].copy()) for _ in range(2): player.all_cards.append(assets.all_cards['fighter'][0].copy()) ret = True while ret: ret = battle(screen, player, assets, escape_call) game_over(screen) pygame.display.quit()
# main.py from world import Spot from character import Player, Enemy alkirasc = Spot('Alkira Secondary College', 'A lot of kids spend their lives here.') daveshome = Spot("Dave's Home", "It is a dark house and a bad smell comes out from it.") alkirasc.connect(daveshome, 'south') daveshome.connect(alkirasc, 'north') #player_name = input('Name of the Great Adventure please: ') player_name = 'Jeremy' player = Player(player_name, alkirasc) dave = Enemy('Dave', 'A smelly zombie.', 'garlic') dave.conversation = 'I like to eat humans.' steve = Enemy('Steve', 'A shifty ghost.', 'cake') steve.conversation = "This doesn't look good, dude." daveshome.add_characters(dave) daveshome.add_characters(steve) def who(command): commands = command.split() if len(commands) == 1: return player.current_spot.characters[0] elif len(commands) == 2: for character in player.current_spot.characters: if character.name.lower() == commands[1].lower(): return character
pygame.draw.rect(window, (255, 250, 250), ((i) * blocksW, (j) * blocksH, blocksW, blocksH)) if mazeRender[i][j][1] == 1: #Represents Bomb, Black pygame.draw.rect(window, (0, 0, 0), ((i) * blocksW, (j) * blocksH, blocksW, blocksH)) if mazeRender[i][j][1] == 2: #Represents explosion, orange pygame.draw.rect(window, (255, 165, 0), ((i) * blocksW, (j) * blocksH, blocksW, blocksH)) if mazeRender[i][j][0] == 1: #Represents player 1. blue Bomberman = Player(i, j, blocksW - 10, blocksH - 10) playerPos = Bomberman.getPos() values = Bomberman.renderValues() pygame.draw.rect(window, (0, 0, 255), (((values[0]) * blocksW) + 4, ((values[1]) * blocksH) + 4, values[2], values[3])) if mazeRender[i][j][0] == 2: #Represents player 2. Red NumNPC -= 1 newNPC = NPC(i, j, blocksW - 10, blocksH - 10, 1, playerPos, menu, 0) NPCs.append(newNPC) values = NPCs[0].renderValues()
def main(): screen = settings.SCREEN clock = settings.CLOCK fps = settings.FPS tile_map = TileMap() add_points(tile_map) player = Player(position=settings.SPAWNS["pacman"]) ghosts = pygame.sprite.Group( Ghost(position=settings.SPAWNS[name]) for name in ["blinky", "inky", "pinky", "clyde"]) single_text = pygame.sprite.GroupSingle() setting_text = pygame.sprite.GroupSingle() setting_text_pos = (screen.get_width() // 2 - 9, 12) font = pygame.font.SysFont(None, 32) # Starting with scatter and alternating in following interval (in secs): # Level 1: 7, 20, 7, 20, 5, 20, 5, inf; # Level 2-4: 7, 20, 7, 20, 5, 1033, 1 / 60, inf; # Level 5+: 5, 20, 5, 20, 5, 1037, 1 / 60, inf; normal_mode = Mode(["scatter", "chase"], [7, 20, 7, 20, 5, 20, 5, math.inf]) frighten_mode = Mode(["frightened", "unfrightened"], [5, 3], 1) mode = "scatter" score = 0 speed_factor = 1.2 # How fast to run the game. time = 0 start_timer = 2 paused = False started = False music = False grid = False see_target = False while 1: dt = (clock.tick(fps) / 1000 ) # "dt" is the time between each loop in seconds. time += dt if started and not paused and not player.dead else 0 dt *= speed_factor # "time" shouldn't be affected, the rest should. for event in pygame.event.get(): if event.type == pygame.KEYDOWN: if event.key == pygame.K_ESCAPE: quit() elif event.key == pygame.K_f: fps = (fps % 120) + 20 setting_text.add( text.FadingText("FPS: {}".format(fps), fade_out=1, pos=setting_text_pos, origin="midtop", font=font, color=(255, 255, 255))) elif event.key == pygame.K_r or event.key == pygame.K_SPACE: for tile in tile_map.tile.values(): for ghost in ghosts: if ghost in tile.content: tile.remove_content(ghost) Ghost.ID = 0 player = Player(position=settings.SPAWNS["pacman"]) ghosts = pygame.sprite.Group( Ghost(position=settings.SPAWNS[name]) for name in ["blinky", "inky", "pinky", "clyde"]) start_timer = 2 started = False elif event.key == pygame.K_p: pygame.mixer.music.unpause( ) if paused else pygame.mixer.music.pause() paused = not paused temp = "Paused" if paused else "Unpaused" setting_text.add( text.FadingText(temp, fade_out=1, pos=setting_text_pos, origin="midtop", font=font, color=(255, 255, 255))) elif event.key == pygame.K_1: change_music(track=0) setting_text.add( text.FadingText(settings.MUSIC[0][29:46], fade_out=1, pos=setting_text_pos, origin="midtop", font=font, color=(255, 255, 255))) elif event.key == pygame.K_2: change_music(track=1) setting_text.add( text.FadingText(settings.MUSIC[1][29:48], fade_out=1, pos=setting_text_pos, origin="midtop", font=font, color=(255, 255, 255))) elif event.key == pygame.K_3: pygame.mixer.music.stop() setting_text.add( text.FadingText("Paused music", fade_out=1, pos=setting_text_pos, origin="midtop", font=font, color=(255, 255, 255))) elif event.key == pygame.K_g: grid = not grid setting_text.add( text.FadingText("Grid", fade_out=1, pos=setting_text_pos, origin="midtop", font=font, color=(255, 255, 255))) elif event.key == pygame.K_t: see_target = not see_target setting_text.add( text.FadingText("Target", fade_out=1, pos=setting_text_pos, origin="midtop", font=font, color=(255, 255, 255))) elif event.key == pygame.K_x: speed_factor = (speed_factor + 0.1) % 2.05 if 2 > speed_factor >= 1 else 1 setting_text.add( text.FadingText("Speed: {0:.1f}".format(speed_factor), fade_out=1, pos=setting_text_pos, origin="midtop", font=font, color=(255, 255, 255))) elif event.type == pygame.QUIT: quit() if not paused and started and not player.dead: # Do game updates and logic checks if score >= 60 and not Ghost.SPAWN[3]: # 60 Ghost.SPAWN[3] = True print("Clyde's coming out!") if score >= 30 and not Ghost.SPAWN[1]: # 30 Ghost.SPAWN[1] = True print("Inky's coming out!") if mode in ("frightened", "unfrightened"): mode = frighten_mode.update(dt) if mode is not None: Ghost.MODE = Ghost.MODES[mode] else: frighten_mode = Mode(["frightened", "unfrightened"], [5, 3], 1) change_unfrightened(ghosts) else: mode = normal_mode.update(dt) Ghost.MODE = Ghost.MODES[mode] player.update(tile_map, dt) ghosts.update(tile_map, dt, player, ghosts) Point.instances.update(dt) mode, score = collision(player, ghosts, tile_map, single_text, mode, score, clock) single_text.update(dt) elif player.dead: player.animate(dt) tile_map.draw(screen) text.put_text(screen, "Score: {0}".format(score), pos=(-128, 36), origin="bottomleft") text.put_text(screen, "Time: {0:.1f}".format(time), pos=(16, 36), origin="bottomleft") setting_text.update(dt) setting_text.draw(screen) Point.instances.draw(screen) if grid: draw_grid(screen, tile_map) if see_target: show(ghosts, target=True, house=True) if not player.dead: ghosts.draw(screen) single_text.draw(screen) screen.blit(player.image, player.rect) if not started: start_timer -= dt text.put_text(screen, "READY!", (224, 328), color=(255, 255, 0), font=pygame.font.SysFont(None, 32, 1, 1)) if not music: change_music(track=0) music = True if start_timer <= 0: start_timer = 2 started = True if len(Point.instances) <= 0: text.put_text(screen, "WON!", settings.SPAWNS["pacman"]) pygame.display.update() # delay(2, clock) # Will delay every update. pygame.display.update()
def main(): """ Main function for the game. """ pygame.init() # Set the width and height of the screen [width,height] screen = pygame.display.set_mode( [constants.screenWidth, constants.screenHeight]) pygame.display.set_caption("Donkey Kong Country") # Create the player player = Player() # Create Sprite Group allSpritesList = pygame.sprite.Group() # Add player sprite to list of all sprites allSpritesList.add(player) player.rect.x = 350 player.rect.y = 450 # Loop until the user clicks the close button. done = False # Used to manage how fast the screen updates clock = pygame.time.Clock() # -------- Main Program Loop ----------- while not done: # ALL EVENT PROCESSING SHOULD GO BELOW THIS COMMENT for event in pygame.event.get(): if event.type == pygame.QUIT: done = True # If user presses a key down elif event.type == pygame.KEYDOWN: # Figure what key it was, adjust change_x if event.key == pygame.K_d: player.goRight() if event.key == pygame.K_a: player.goLeft() if event.key == pygame.K_w: player.goUp() if event.key == pygame.K_s: player.goDown() elif event.type == pygame.MOUSEBUTTONDOWN: mousePressed = pygame.mouse.get_pressed() if mousePressed[0]: player.punch() elif mousePressed[2]: player.spin() # If user lets up a key elif event.type == pygame.KEYUP: # If an arrow key, reset vector if event.key == pygame.K_d or event.key == pygame.K_a or event.key == pygame.K_w or event.key == pygame.K_s: player.stop() # ALL EVENT PROCESSING SHOULD GO ABOVE THIS COMMENT # ALL GAME LOGIC SHOULD GO BELOW THIS COMMENT if player.rect.x >= 740: player.rect.x = 740 elif player.rect.x <= 20: player.rect.x = 20 allSpritesList.update() # ALL GAME LOGIC SHOULD GO ABOVE THIS COMMENT # ALL CODE TO DRAW SHOULD GO BELOW THIS COMMENT # First, clear the screen to white. Don't put other drawing commands # above this, or they will be erased with this command. screen.fill(constants.WHITE) allSpritesList.draw(screen) # ALL CODE TO DRAW SHOULD GO ABOVE THIS COMMENT # Go ahead and update the screen with what we've drawn. pygame.display.flip() # Limit to 60 frames per second clock.tick(60) # Close the window and quit. # If you forget this line, the program will 'hang' # on exit if running from IDLE. pygame.quit()
class TestPlayer(unittest.TestCase): def setUp(self): self.default_effect = Effect(Damage(5,5), Damage(5,5), Stats(5,5,5,5)) self.default_weapon = Item("Rusty Sword", self.default_effect, "WEAPON", 2) self.default_armor = Item("Leather Armor", self.default_effect, "ARMOR", 2) self.test_player = Player("Alice", Stats(1,1,1,1), 10, "female", 1, Race("Human"), self.default_weapon, self.default_armor) def tearDown(self): self.test_player.__del__() self.default_effect.__del__() self.default_armor.__del__() self.default_weapon.__del__() # test default init def test_init(self): self.assertEqual(self.test_player.name, 'Alice') def test_total_defense(self): # magic = weapon: 5 + armor: 5 + total_int: 13 + race: 25 # physical = weapon: 5 + armor: 5 + total_strength: 13 + race: 25 self.assertEqual(self.test_player.total_defense(), (48,48)) def test_total_attack(self): # magic = weapon: 5 + armor: 5 + total_int: 13 # physical = weapon: 5 + armor: 5 + total_str: 13 self.assertEqual(self.test_player.total_attack(), (23,23)) def test_total_strength(self): # base: 1 + race: 2 + weapon: 5 + armor: 5 self.assertEqual(self.test_player.total_strength(), 13) def test_total_hp(self): # base: 1 + race: 0 + armor: 5 + weapon: 5 self.assertEqual(self.test_player.total_hp(), 11) def test_total_intelligence(self): # base: 1 + race: 2 + armor: 5 + weapon: 5 self.assertEqual(self.test_player.total_intelligence(), 13) def test_total_agility(self): # base: 1 + race: 1 + armor: 5 + weapon: 5 self.assertEqual(self.test_player.total_agility(), 12) def test_dodge_chance(self): # total_agility / 100 self.assertEqual(self.test_player.dodge_chance(), .12) def test_critical_chance(self): # total_agility / 100 self.assertEqual(self.test_player.critical_chance(), .12) def test_critical_damage(self): # total_damage + round(total_damage*critical_chance) self.assertEqual(self.test_player.critical_damage(), (25,25)) def test_level_up_valid(self): self.test_player.level_up((1,0,0)) self.assertEqual(self.test_player.get_stats().strength, 2) def test_level_up_invalid(self): self.test_player.level_up((1,1,1)) expected_stats = Stats(1,1,1,1) self.assertEqual(self.test_player.get_stats(), expected_stats) def test_add_gold(self): self.test_player.add_gold(1) self.assertEqual(11, self.test_player.get_gold()) def test_new_weapon(self): new_weapon = Item("Axe", self.default_effect, 'WEAPON', 5) self.test_player.replace_weapon(new_weapon) self.assertEqual(new_weapon, self.test_player.weapon) def test_new_armor(self): new_armor = Item("Iron Armor", self.default_effect, 'ARMOR', 5) self.test_player.replace_armor(new_armor) self.assertEqual(new_armor, self.test_player.armor) def test_str(self): armor_string = str(self.test_player.armor) weapon_string = str(self.test_player.weapon) stats_string = str(self.test_player.stats) summary_string = 'Alice - 1...10g' expected = '{}\t{}\n\t{}\n\t{}'.format(summary_string, stats_string, weapon_string, armor_string) self.assertEqual(self.test_player.__str__(), expected)
def __init__(self): self.dungeon_map = DungeonMap() self.player_map = PlayerMap() self.player = Player()
def next_scene(new_scene): global current_scene frame_timer.frame_timer_del_all() print("Moving to scene {}".format(new_scene)) if new_scene >= len(scenes): # Game over exit() player.start_scene(scenes[new_scene]) scenes[current_scene].add_player(None) scenes[new_scene].reset() scenes[new_scene].add_player(player) current_scene = new_scene # Create the player player = Player() player_group = pygame.sprite.Group() player_group.add(player) # Associate the player and the first scene player.start_scene(scenes[current_scene]) scenes[current_scene].add_player(player) # Game loop running = True while running: log.debug("Main game loop") # Keep loop running at the right speed clock.tick(config.FPS) # Check whether we have any exit events and deal with them first
def setUp(self): self.default_effect = Effect(Damage(5,5), Damage(5,5), Stats(5,5,5,5)) self.default_weapon = Item("Rusty Sword", self.default_effect, "WEAPON", 2) self.default_armor = Item("Leather Armor", self.default_effect, "ARMOR", 2) self.test_player = Player("Alice", Stats(1,1,1,1), 10, "female", 1, Race("Human"), self.default_weapon, self.default_armor)
from catacomb_setup import commandsHelp from character import Player # Make a new player object that is currently in the 'outside' room. global player player = Player(room['outside']) gameRunning = True def quitGame(): print('Quitting Game') global gameRunning gameRunning = False #################### # Command functions ################### def parseInput(*args): args = args[0] command1 = args[0].lower() if command1 in "nesw": move(player, command1) elif command1 in {"look", "l"}: look(player, args) elif command1 in { "score", }: player.getScore() elif command1 in {"pickup", "p"}: player.pickupItem(args) elif command1 in {"drop", "d"}: player.dropItem(args)
def test_invalid_move(self): test_player = Player() test_player.randomize_initial_position(self.map_for_player_test) self.assertFalse(result)
def loadPlayer(ID): rs = DB.getInstance().query("SELECT * FROM Players WHERE ID = %s",ID) if rs.next(): player = Player() player.ID = rs.getInt('ID') player.name = rs.getString('name') player.speed = rs.getInt('speed') player.defense = rs.getInt('defense') player.force = rs.getInt('force') player.maxHp = rs.getInt('maxHp') player.hp = rs.getInt('hp') player.level = rs.getInt('level') player.x = rs.getInt('x') player.y = rs.getInt('y') player.exp = rs.getInt('exp') player.model = rs.getInt('model') player.heading = rs.getInt('heading') return player