class SpaceHogs(pyglet.window.Window): def __init__(self): super(SpaceHogs, self).__init__(caption='Space Hogs', width=settings.WINDOW_WIDTH, height=settings.WINDOW_HEIGHT) pyglet.resource.path.append('data') pyglet.resource.reindex() self.batch = pyglet.graphics.Batch() self.player = Player(batch=self.batch) self.push_handlers(self.player) pyglet.clock.schedule_interval(self.update, float(1)/60) def run(self): pyglet.app.run() def update(self, dt): self.player.update(dt) for bullet in BULLETS[:]: bullet.update(dt) def on_draw(self): self.clear() self.batch.draw()
def __init__(self, view): self.clock = pg.time.Clock() self.view = view glEnable(GL_DEPTH_TEST) self.ADDENEMY = pg.USEREVENT + 1 # pylint: disable=no-member pg.time.set_timer(self.ADDENEMY, randint(500, 750)) self.NEWTORNADO = pg.USEREVENT + 2 # pylint: disable=no-member pg.time.set_timer(self.NEWTORNADO, randint(5000, 20000)) self.enemies = [] self.splats = [] self.splats_collect = [] self.bullets = [] self.tornados = [] self.all_sprites = [] self.player = Player() self.splat_count = [0] self.background = Background(desert_road_png) self.loot_button = Hud_Button(treasure_png, (-.85, -.8)) self.loot = ui.Window('Loot', self.splat_count, self.view, self.player) self.loot.paint_select[0].active = True self.loot.paint_select[0].owned = True self.isRunning = True
def new(self): # initialize all variables and do all the setup for a new game self.all_sprites = pg.sprite.Group() self.walls = pg.sprite.Group() self.player = Player(self, 10, 10) for x in range(10,20): Wall(self,x,5)
def __init__(self): pg.init() # initialize pygame module pg.font.init() print( "Tic-tac-toe Mini-max algorithm project @ weronikaolejniczak.github.com \n" ) self.font = pg.font.Font("resources/fonts/{}".format(settings.FONT), 50) self.WIDTH = settings.WIDTH self.HEIGHT = settings.HEIGHT self.size = (self.WIDTH, self.HEIGHT) self.TILEMAP = [[0 for x in range(3)] for y in range(3)] self.screen = pg.display.set_mode( self.size) # create an instance of the pygame.Surface class pg.display.set_icon(favicon) pg.display.set_caption("Tic-tac-toe") # set the caption of our window self.clock = pg.time.Clock() # create an instance of Clock class self.FPS = settings.FPS self.start_time = 0 self.end_time = 0 self.all_sprites = pg.sprite.Group() self.playing = True self.dt = 0 self.turn = "AI" self.human = Player(self, "human") self.AI = Player(self, "AI") self.is_human_turn = False self.winner = "" self.start = None self.end = None self.orientation = ""
def start_game(self): self.all_sprites = pygame.sprite.Group() self.fruits = pygame.sprite.Group() self.player = Player(self, 10, 10) self.fruit = Fruit(self) self.score = 0 self.run()
def new(self): """Start a new game. """ # keeping track of missions self.vaccines_collected = 0 self.enemies_killed = 0 self.n_bullets = 20 # initial number of bullets for the player self.failed = False # used for checking if player completed game self.platforms_crossed = 0 # initialize sprite groups self.all_sprites = pygame.sprite.LayeredUpdates() self.platforms = pygame.sprite.Group() self.powerups = pygame.sprite.Group() self.enemies = pygame.sprite.Group() self.viruses = pygame.sprite.Group() self.bullets = pygame.sprite.Group() self.clouds = pygame.sprite.Group() # load bg image self.bg_image = BackGround(self) if self.level > 1: # needed for scrolling background self.bg_image_2 = BackGround(self) self.bg_image_2.rect.left = self.bg_image.rect.right # create new instance of player self.player = Player(self) # timer for spawning enemies self.slime_timer = 0 self.bat_timer = 0 # creating base self.bases = [] base = Base(self, 0) self.bases.append(base) while base.rect.right < s.WIDTH: base = Base(self, base.rect.right) self.bases.append(base) # creating starting platforms for plat in s.PLATFORM_START_LIST: Platform(self, *plat) # create clouds/other images if self.level == 1: for i in range(5): c = Cloud(self) c.rect.x -= random.randrange(200, 400, 50) # load music pygame.mixer.music.load(os.path.join(self.sound_dir, "background.ogg")) self.run()
def __init__(self): pygame.init() pygame.display.set_caption(GAME_TITLE) self.screen = pygame.display.set_mode([WIDTH, HEIGHT]) self.clock = pygame.time.Clock() self.playing = False self.load_data() self.player = Player(self, self.map.player_entry_point)
def load_data(self): self.all_sprites = pygame.sprite.Group() self.walls = pygame.sprite.Group() self.map = Map() self.map.load_from_file('map.txt') self.map.create_sprites_from_map_data(self) self.player = Player(self, self.map.player_entry_point)
def create_sprites(self): self.entities = pygame.sprite.Group() self.bg = pygame.image.load(self.bg_path).convert() self.bg = pygame.transform.smoothscale(self.bg, self.MAP_SIZE) self.bg_rect = self.bg.get_rect() self.player = Player(self) self.entities.add(self.player)
def init_round(): events.players.append(Player('p1', 400, 100, 10)) events.players.append(Player('p2', 430, 300, 10)) events.p1_group.add(events.players[0]) events.p2_group.add(events.players[1]) all_sprites.add(events.players) events.running = True events.bars.append(HPBar(200, 886)) events.bars.append(HPBar(570, 886)) all_sprites.add(events.bars)
def new(self): self.all_sprites = pg.sprite.Group() self.platforms = pg.sprite.Group() self.player = Player(self) self.all_sprites.add(self.player) for plat in PLATFORM_LIST: p = Platform(*plat) self.all_sprites.add(p) self.platforms.add(p) self.run()
def new(self): # Initialisieren und/oder Zurücksetzen self.all_sprites = pg.sprite.Group() self.blocks = pg.sprite.Group() self.player = Player(w) self.all_sprites.add(self.player) for block in s.BLOCKS_LIST: b = Block(*block) self.all_sprites.add(b) self.blocks.add(b) self.run()
class GameScene: def __init__(self): self.player1 = Player(color=(255, 255, 255), x=random.randint(0, cfg.board_size), y=random.randint(0, cfg.board_size)) self.player2 = Player(color=(0, 0, 0), x=random.randint(0, cfg.board_size), y=random.randint(0, cfg.board_size)) self.tiles = {} for x, y in itertools.product(range(0, cfg.board_size), range(0, cfg.board_size)): self.tiles[x, y] = Tile(x=x, y=y, color=random.choice(cfg.themes)) self.keyboard_inputs = { K_ESCAPE: (pygame.quit,), K_UP: (self.player1.move, 0, -1), K_DOWN: (self.player1.move, 0, 1), K_LEFT: (self.player1.move, -1, 0), K_RIGHT: (self.player1.move, 1, 0), K_RSHIFT: (self.player1.bomb, self.tiles, self.player2), K_w: (self.player2.move, 0, -1), K_s: (self.player2.move, 0, 1), K_a: (self.player2.move, -1, 0), K_d: (self.player2.move, 1, 0), K_LSHIFT: (self.player2.bomb, self.tiles, self.player1), } def draw(self, screen): # Draw the player to the screen screen.fill((0, 200, 0)) for tile in self.tiles.values(): tile.draw(screen) self.player1.draw(screen) self.player2.draw(screen) pygame.display.flip() def run(self, screen): while True: # for loop through the event queue for event in pygame.event.get(): if event.type == KEYDOWN: try: action, *args = self.keyboard_inputs[event.key] action(*args) except KeyError: pass elif event.type == QUIT: pygame.quit() for num, player in enumerate([self.player1, self.player2]): if player.check_if_won(): return self.draw(screen)
def __init__(self, title, splat_count, view, player): self.clock = pg.time.Clock() self.view = view self.splat_count = splat_count self.background = Ui_Color((21 / 256, 26 / 256, 27 / 256, 1)) self.background.translate(0, 0, .9) self.title_bar = Ui_Color((.25, .25, .25, 1)) self.title_bar.scale(1, 1 / 15, 1) self.title_bar.translate(0, 1 - self.title_bar.box.uy, 0) self.title_text = Text(title, 'center') self.title_text.scale(1, .1, 1) self.title_text.scale(.66, .66, 1) self.title_text.translate(0, 1 - self.title_text.box.uy, -.1) self.close_button = Close_Button() self.paint_select = [] for args in [ (-.95, .78, 1, 0, 0, 1), # red (-.95, .64, 0, .449, 0, 1), # green (-.85, .78, .7245, .7245, .7245, 1), # silver (-.85, .64, .977, .977, 0, 1), # yellow (-.85, .50, 1, 0.078125, 0.703125, 1) # pink ]: self.paint_select.append(Color_Button(args[:2], args[2:])) for args in [ (-.95, .50, blue_squares_png), (-.95, .36, red_gloop_png), (-.85, .36, pink_bubbles_png), (-.95, .22, depot_png), (-.85, .22, fractal_png) ]: self.paint_select.append(Texture_Button(*args)) self.splat_icon = objloader.Obj(square_obj, object_vs, object_fs, splat_png) self.splat_icon.generate() self.splat_icon.set_texture(1) self.splat_icon.scale(.04, .06, 1) self.splat_icon.translate(-.9, -.9, 0) self.splats_number = Splats_Number(str(splat_count[0])) self.player = player self.car = Player() self.car.generate() self.car.scale(5, 3, 5) self.car.rotate(pi / 3, 1, 0, 0)
def __init__(self, game, x, y): pg.sprite.Sprite.__init__(self) Player.__init__(self, game, x, y) self.path = [] self.game = game self.skill = 1 self.directions = [[-1, 0], [1, 0], [0, -1], [0, 1]] self.random_direction = random.choice(self.directions) self.last_direction = [2, 2] self.max_steps = int(SCREEN_WIDTH / 2) self.steps_to_take = random.randint(TILESIZE, self.max_steps) self.steps_taken = 0 self.current_state = self.explore
def setup(self): """Get game ready to play""" self.player_list = arcade.SpriteList() self.coin_list = arcade.SpriteList() self.bomb_list = arcade.SpriteList() # Set up the player self.player_sprite = Player( PLAYER_SPRITE_IMAGE, SPRITE_SCALING_PLAYER, ) self.player_sprite.center_x = 50 self.player_sprite.center_y = 50 self.player_list.append(self.player_sprite) # Create the coins for i in range(COIN_COUNT): coin = LeftMovingCoin(COIN_SPRITE_IMAGE, COIN_SPRITE_SCALING) # position of each coin coin.center_x = random.randrange(SCREEN_WIDTH) coin.center_y = random.randrange(SCREEN_HEIGHT) # add coin to coin list self.coin_list.append(coin) # Create the bombs for i in range(BOMB_COUNT): bomb = Bomb(BOMB_SPRITE_IMAGE, BOMB_SPRITE_SCALING) # position of each bomb bomb.center_x = random.randrange(SCREEN_WIDTH) bomb.center_y = random.randrange(SCREEN_HEIGHT) # add bomb to bomb list self.bomb_list.append(bomb)
def __init__(self): # Init Display self.screen = pg.display.set_mode( [params.screen_width, params.screen_height], params.screen_mode) # Init Font self.font = pg.font.SysFont('Calibri', 25, True, False) # Init Sprite Lists self.block_list = pg.sprite.Group() self.bullet_list = pg.sprite.Group() self.all_sprites_list = pg.sprite.Group() self.ball_list = pg.sprite.Group() # Add Blocks and ball self.level = 0 self.energy = params.energy self.energy_max = params.energy_max self.energy_reg = params.energy_reg self.shoot_speed = params.shoot_speed self.reset(50) # Add Player self.player = Player() self.all_sprites_list.add(self.player) self.player.rect.y = params.screen_height - self.player.height - 5
def create_player(self): self.tests = [] try: self.debug("Creating party..") # spawn player self.player = Player(self, self.name) self.player.block_id = "player" self.entities.add( self.player ) # choose ally bots bot_options = ["crystal","nathan","jack"] bot_options.remove(self.name.lower()) # spawn bots self.bots = [] for bot_name in bot_options: self.debug("Creating bot: "+bot_name) if bot_name == "crystal": bot = CrystalBot(self, bot_name) elif bot_name == "jack": bot = JackBot(self, bot_name) else: bot = NathanBot(self, bot_name) bot.rect.x = self.player.rect.x + 50 bot.rect.y = self.player.rect.y - 50 self.bots.append( bot ) self.entities.add( bot ) except Exception as e: self.debug("Party Creation Error: " + str(e))
def spawn_all_sprites(self): """ Create all sprites (player and enemy) based on their initial number """ self.player = Player.spawn(self) for _ in range(self.enemies_initial_number): Enemy.spawn(self) logging.debug('All enemies spawned')
class Game: def __init__(self): pygame.init() pygame.display.set_caption(GAME_TITLE) self.screen = pygame.display.set_mode([WIDTH, HEIGHT]) self.clock = pygame.time.Clock() self.playing = False self.load_data() self.start_game() def load_data(self): self.all_sprites = pygame.sprite.Group() self.walls = pygame.sprite.Group() self.map = Map() self.map.load_from_file('map.txt') self.map.create_sprites_from_map_data(self) self.player = Player(self, self.map.player_entry_point) def start_game(self): self.run() def run(self): self.playing = True while self.playing: self.dt = self.clock.tick(FPS) / 1000 self.events() self.update() self.draw() def events(self): for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() quit() def update(self): self.player.update() def draw(self): self.screen.fill(BLACK) self.all_sprites.draw(self.screen) pygame.display.flip()
def create_sprites(self): self.entities = pygame.sprite.Group() self.bg = pygame.image.load(self.bg_path).convert() self.bg = pygame.transform.smoothscale(self.bg, self.MAP_SIZE) self.bg_rect = self.bg.get_rect() self.player = Player(self) self.entities.add( self.player )
def __init__(self): pygame.init() self.screen = pygame.display.set_mode([WIDTH,HEIGHT]) pygame.display.set_caption(TITLE) self.clock = pygame.time.Clock() self.all_sprites = pygame.sprite.Group() for _ in range(32): Player(self, 10, 10)
def __init__(self): pygame.init() #SCREEN self.screen = pygame.display.set_mode([WIDTH, HEIGHT]) pygame.display.set_caption("Snakipy") self.clock = pygame.time.Clock() self.all_sprites = pygame.sprite.Group() self.fruits = pygame.sprite.Group() self.player = Player(self, 10, 10) self.fruit = Fruit(self) self.large_font = pygame.font.SysFont("chicken_pie", 80) self.small_font = pygame.font.SysFont("chicken_pie", 32) self.score = 0 self.font = pygame.font.SysFont("chicken_pie", 24)
def __init__(self, width, height): self.width = width self.height = height self.buffer_width = 200 self.player = Player(x=width // 2, y=height // 2) self.bg_batch = pyglet.graphics.Batch() self.fg_batch = pyglet.graphics.Batch() self.random_pool = RandomPool(batch=self.bg_batch) pyglet.resource.path = ['.', 'data'] pyglet.resource.reindex() self._sprites = [] self._scenery = [] self._blockers = [] self._bullets = [] self._labels = [] self._npcs = [] self._collections = [ self._sprites, self._scenery, self._blockers, self._bullets, self._labels, self._npcs ]
def new(self): # start a new game self.all_sprites = pg.sprite.Group() self.field_sprites = pg.sprite.Group() self.all_bullets = pg.sprite.Group() self.all_villain = pg.sprite.Group() self.platforms = pg.sprite.Group() self.player = Player() self.villain = Villain() self.field = Field(500, 500, 50, 50) self.all_sprites.add(self.player, self.villain) self.field_sprites.add(self.field)
def __init__(self): self.player1 = Player(color=(255, 255, 255), x=random.randint(0, cfg.board_size), y=random.randint(0, cfg.board_size)) self.player2 = Player(color=(0, 0, 0), x=random.randint(0, cfg.board_size), y=random.randint(0, cfg.board_size)) self.tiles = {} for x, y in itertools.product(range(0, cfg.board_size), range(0, cfg.board_size)): self.tiles[x, y] = Tile(x=x, y=y, color=random.choice(cfg.themes)) self.keyboard_inputs = { K_ESCAPE: (pygame.quit,), K_UP: (self.player1.move, 0, -1), K_DOWN: (self.player1.move, 0, 1), K_LEFT: (self.player1.move, -1, 0), K_RIGHT: (self.player1.move, 1, 0), K_RSHIFT: (self.player1.bomb, self.tiles, self.player2), K_w: (self.player2.move, 0, -1), K_s: (self.player2.move, 0, 1), K_a: (self.player2.move, -1, 0), K_d: (self.player2.move, 1, 0), K_LSHIFT: (self.player2.bomb, self.tiles, self.player1), }
def __init__(self, sw: int, sh: int): self.player = Player(0, 0, "./images/person1.png", "./images/person2.png") self.setMainSprite(self.player) self.loadFromFile() self.rooms["loft"].addSprite(self.mainSprite) self.rooms["loft"].addController(KeyboardController(self.player)) self.sw = sw self.sh = sh
def __init__(self): super(SpaceHogs, self).__init__(caption='Space Hogs', width=settings.WINDOW_WIDTH, height=settings.WINDOW_HEIGHT) pyglet.resource.path.append('data') pyglet.resource.reindex() self.batch = pyglet.graphics.Batch() self.player = Player(batch=self.batch) self.push_handlers(self.player) pyglet.clock.schedule_interval(self.update, float(1)/60)
def start(self): self.mobs = pygame.sprite.Group() self.walls = pygame.sprite.Group() self.current_map = Map() self.current_map.load_map_from_file("map.txt") self.current_map.create_sprites_from_data(self) self.player = Player( self, self.current_map.entry_point.x, self.current_map.entry_point.y ) self.run()
def new(self): # Initialisieren und/oder Zurücksetzen self.all_sprites = pg.sprite.Group() self.blocks = pg.sprite.Group() self.player = Player() self.all_sprites.add(self.player) self.block1 = Block(0, s.HEIGHT - 64, s.WIDTH, 32) self.all_sprites.add(self.block1) self.blocks.add(self.block1) self.block2 = Block(s.WIDTH/2 - 64, s.HEIGHT - 192, 128, 32) self.all_sprites.add(self.block2) self.blocks.add(self.block2) self.run()
def __init__(self, level, character): self.effects = Effects() self.score = 1 self.all_sprites = pygame.sprite.Group() self.platforms = pygame.sprite.Group() self.baddies = pygame.sprite.Group() self.powerups = pygame.sprite.Group() self.player = Player(character) self.all_sprites.add(self.player) for platform in level: plat = Platform(platform[0], platform[1], platform[2], platform[3]) self.all_sprites.add(plat) self.platforms.add(plat)
def new(self, level): # start a new game if level == 5: self.playing = False g.show_go_screen() self.score = 0 self.all_sprites = pg.sprite.LayeredUpdates() self.platforms = pg.sprite.Group() self.powerups = pg.sprite.Group() self.mobs = pg.sprite.Group() self.clouds = pg.sprite.Group() self.portal = pg.sprite.Group() self.shortcut = pg.sprite.Group() self.player = Player(self) pg.mixer.music.load(path.join(self.snd_dir, 'gameplay.mp3')) pg.mixer.music.set_volume(.3) pg.mixer.music.play(loops=-1) if level == 1: for plat in PLATFORM_LIST_1: Platform(self, *plat) if level == 2: for plat in PLATFORM_LIST_2: Platform(self, *plat) if level == 3: for plat in PLATFORM_LIST_3: Platform(self, *plat) Portal(self) Shortcut(self) self.mob_timer = 0 for i in range(8): c = Cloud(self) c.rect.y += 500 self.run(level)
def new(self): # initialize all variables and do all the setup for a new game self.draw_debug = False self.paused = False self.night = True # Sprite groups self.all_sprites = pg.sprite.LayeredUpdates() self.obstacles = pg.sprite.Group() self.mobs = pg.sprite.Group() self.bullets = pg.sprite.Group() self.items = pg.sprite.Group() # Map self.map = TiledMap(path.join(self.map_folder, '01.tmx')) self.map_img = self.map.make_map() self.map_rect = self.map_img.get_rect() # Map Objects for tile_object in self.map.tmxdata.objects: # For spawning in center of tiled object obj_center = vec(tile_object.x + tile_object.width / 2, tile_object.y + tile_object.height / 2) if tile_object.name == 'player': self.player = Player(self, obj_center.x, obj_center.y) if tile_object.name == 'zombie': Mob(self, obj_center.x, obj_center.y) if tile_object.name == 'wall': Obstacle(self, tile_object.x, tile_object.y, tile_object.width, tile_object.height) if tile_object.name in ['health', 'shotgun']: Item(self, obj_center, tile_object.name) # Camera object self.camera = Camera(self.map.width, self.map.height) # Start a new level sound self.effects_sounds['level_start'].play()
def new(self): # initialize all variables and do all the setup for a new game self.all_sprites = pg.sprite.Group() self.walls = pg.sprite.Group() for row, tiles in enumerate(self.map_data): for col, tile in enumerate(tiles): if tile == '1': colour = BLACK Wall(self, col, row, colour) elif tile == '2': colour = YELLOW Path(self, col, row, colour) elif tile == '3': colour = PINK Path(self, col, row, colour) elif tile == '4': colour = GREEN Path(self, col, row, colour) elif tile == '5': colour = BROWN Path(self, col, row, colour) elif tile == '6': colour = VIOLET Path(self, col, row, colour) elif tile == '7': colour = ORANGE Path(self, col, row, colour) elif tile == '8': colour = BLUE Path(self, col, row, colour) elif tile == '9': colour = LIGHTGREY Path(self, col, row, colour) # elif tile == '.': # colour = WHITE # Path(self, col, row, colour) elif tile == 'P': self.player = Player(self, col, row)
def __init__(self, width, height): self.width = width self.height = height self.buffer_width = 200 self.player = Player(x = width // 2, y = height // 2) self.bg_batch = pyglet.graphics.Batch() self.fg_batch = pyglet.graphics.Batch() self.random_pool = RandomPool(batch = self.bg_batch) pyglet.resource.path = ['.', 'data'] pyglet.resource.reindex() self._sprites = [] self._scenery = [] self._blockers = [] self._bullets = [] self._labels = [] self._npcs = [] self._collections = [self._sprites, self._scenery, self._blockers, self._bullets, self._labels, self._npcs]
def main(): # Initialize pygame.init() map = Map(selectedmap) player = Player(map.start_position) particles = pygame.sprite.Group([]) goombas = pygame.sprite.Group(map.enemies) all_sprites = pygame.sprite.Group(map.enemies + [player]) screen_cols, screen_rows = screen_width / BLOCK_SIZE, screen_height / BLOCK_SIZE screen = pygame.display.set_mode((screen_width, screen_height)) pygame.display.set_caption('Platformer '+VERSION) clock = pygame.time.Clock() font = pygame.font.SysFont(None, 30) invopen = 0 # True if the inventory is open, false if not. dragging = 0 # True if dragging an item, false if not. # Event loop right_down, left_down = False, False while 1: for event in pygame.event.get(): if invopen == 0: # If inventory isn't opened do this: if event.type == QUIT or event.type == KEYDOWN and event.key == K_ESCAPE: # Quit the game return elif event.type == KEYDOWN: # Handle pushed keys if event.key in (K_LEFT, K_a): left_down = True player.move_left() elif event.key in (K_RIGHT, K_d): right_down = True player.move_right() elif event.key in (K_SPACE, K_w): player.jump() elif event.key == K_i: invopen = 1 elif event.type == KEYUP: # Handle released keys if event.key in (K_LEFT, K_a): player.move_right() if right_down else player.stop_x() left_down = False elif event.key in (K_RIGHT, K_d): player.move_left() if left_down else player.stop_x() right_down = False elif event.type == MOUSEBUTTONDOWN: # Handle mouse clicks pos = pygame.mouse.get_pos() bullet = player.shoot((pos[0] + screen_x, pos[1] + screen_y)) particles.add(bullet) all_sprites.add(bullet) elif invopen== 1: # If inventory is open do this: if dragging == 0: if event.type == QUIT: return elif event.type == KEYDOWN: if event.key == K_ESCAPE or event.key == K_i: invopen = 0 elif event.type == MOUSEBUTTONDOWN: pos = pygame.mouse.get_pos() if pos[0] in range(invframe.right-30, invframe.right) and pos[1] in range(invframe.top, invframe.top+30): invopen = 0 for slot in range(50): if pos[0] in range(SLOTCORD[slot][0], SLOTCORD[slot][0]+20) and pos[1] in range(SLOTCORD[slot][1], SLOTCORD[slot][1]+20): #Drag the item if the selected slot is not empty if inventory.content[slot][0] != 0: dragItem = slot dragging = 1 elif dragging: if event.type == KEYDOWN: if event.key == K_ESCAPE or event.key == K_i: dragging = 0 # Drop the item in previous slot elif event.type == MOUSEBUTTONDOWN: pos = pygame.mouse.get_pos() for slot in range(50): # Test if there is a slot where the player clicked if pos[0] in range(SLOTCORD[slot][0], SLOTCORD[slot][0]+20) and pos[1] in range(SLOTCORD[slot][1], SLOTCORD[slot][1]+20): dragging = 0 inventory.content[slot], inventory.content[dragItem] = inventory.content[dragItem], inventory.content[slot] else: dragging = 0 # Return item to previous slot ''' TODO: Add an inventory so we don't have to disable this entirely. Add or remove land blocks from the selected square pos = pygame.mouse.get_pos() x, y = int(pos[0] + screen_x) / BLOCK_SIZE, int(pos[1] + screen_y) / BLOCK_SIZE tile = map.grid[y][x] if event.button == 1 and tile.color == LAND: map.walls.remove(tile.rect) tile.color = SKY elif event.button == 3 and tile.color == SKY: map.walls.append(tile) tile.color = LAND ''' elapsed_time = clock.tick() # If player's healty drops beyond 0, end the game if player.health <= 0: # Player is death pygame.quit() print "[-] You have died!" sys.exit() # If all enemies were killed, quit game and display win message if len(goombas) == 0: # Player has won pygame.quit() print "[+] You have won!" sys.exit() # Update all creatures. O(v*N), N: number of sprites, v: size of sprite for sprite in all_sprites: sprite.update(elapsed_time, map) # O(N^2) collided_enemies = pygame.sprite.spritecollide(player, goombas, True) for enemy in collided_enemies: player.damage(10/Player.DEFENSE) # Display damage and health message if DEBUG: print "[-] 10 Damage recieved from "+str(enemy) print "[*] Player has now "+str(player.health)+" life points" # O(N^2) shot_enemies = pygame.sprite.groupcollide(goombas, particles, True, True) # KILL EM ALL # Position screen screen_x, screen_y = max(player.rect.x - 250, 0), max(player.rect.y - 250, 0) screen_x = min(screen_x, map.width - screen_width) screen_y = min(screen_y, map.height - screen_height) # Draw the visible map grid_x, grid_y = int(screen_x) / BLOCK_SIZE, int(screen_y) / BLOCK_SIZE for row in map.grid[grid_y : grid_y + screen_rows + 1]: for square in row[grid_x : grid_x + screen_cols + 1]: # Select the correct block and blit it to the screen screen.blit(BLOCKGRAPHICS[square.type], square.rect.move(-screen_x, -screen_y)) # Draw health bar pygame.draw.rect(screen, (250, 0, 0), pygame.Rect(screen_width - 100, 5, player.health, 20), 0) # Draw sprites (Creatures, bullets, etc) for sprites in all_sprites: screen.blit(SPRITEGRAPHICS[sprites.type], sprites.rect.move(-screen_x, -screen_y)) # Draw the inventory if necessary if invopen: invframe = pygame.Rect(200, 200, 330, 400) invframe.center = screen_width/2, screen_height/2 innerframe = pygame.Rect(200, 200, 310, 160) innerframe.bottomleft = invframe.left+10, invframe.bottom-10 left = innerframe.left+10 top = innerframe.top+10 objectframe = pygame.Rect(0, 0, 20, 20) pygame.draw.rect(screen, (44, 44, 44), invframe) pygame.draw.rect(screen, (88, 88, 88), innerframe) objectframe = pygame.Rect(0, 0, 20, 20) for raw in range(5): for slot in range(10): objectframe.topleft = left, top pygame.draw.rect(screen, (100, 100, 100), objectframe) # object[1] is the itemID, OBJIMG is a dictonary of loaded images object = inventory.content[slot+(10*(raw-5))] screen.blit(OBJIMG[str(object[0])], objectframe) left += 30 left = innerframe.left+10 top += 30 statsrect = pygame.Rect(200, 200, 200, 200) statsrect.top, statsrect.right = invframe.top+10, invframe.right-10 pygame.draw.rect(screen, (22, 22, 22), statsrect) statsx, statsy = statsrect.left+10, statsrect.top+10 stats = font.render('Max. HP: '+str(Player.MAXHEALTH), True, (250, 250, 250), (22, 22, 22)) screen.blit(stats, (statsx, statsy)) statsy += 25 stats = font.render('Attack: '+str(Player.ATTACK), True, (250, 250, 250), (22, 22, 22)) screen.blit(stats, (statsx, statsy)) statsy += 25 stats = font.render('Defense: '+str(Player.DEFENSE), True, (250, 250, 250), (22, 22, 22)) screen.blit(stats, (statsx, statsy)) statsy += 25 stats = font.render('Speed: '+str(Player.SPEED), True, (250, 250, 250), (22, 22, 22)) screen.blit(stats, (statsx, statsy)) if dragging: pos = pygame.mouse.get_pos() objectframe.topleft = pos[0] , pos[1] dobject = inventory.content[dragItem] screen.blit(OBJIMG[str(dobject[0])], objectframe) # Draw FPS if necessary if DEBUG: text = font.render('FPS: ' + str(1000 / elapsed_time), True, (0, 0, 0), (250, 250, 250)) screen.blit(text, text.get_rect()) # Update the screen pygame.display.update()
class Game: WIDTH = 720 HEIGHT = WIDTH / 12 * 9 #16:9 Aspect ratio SIZE = (WIDTH, HEIGHT) MAP_WIDTH = 1920 MAP_HEIGHT = 1080 MAP_SIZE = (MAP_WIDTH, MAP_HEIGHT) FPS = 60 TIME_LIMIT = 60 GAME_OVER = False HAS_WON = False HAS_LAST = False BALL_ADD = 3 BALL_SPAWN = 10 def __init__(self): self.running = True self.lasted = 0 self.last_num = None pygame.init() self.screen = pygame.display.set_mode(self.SIZE) pygame.display.set_caption("Can You Live?") self.clock = pygame.time.Clock() self.camera = camera.Camera(self.SIZE, self.MAP_SIZE) self.create_resources() self.create_sprites() self.create_text() """ Creation Functions """ # cache resources once to not re-use def create_resources(self): # set image paths self.bg_path = os.path.join("images","background.jpg") self.dragon_path = os.path.join("images","dragon_red.png") self.fire_path = os.path.join("images","fire.png") # transparent color for sprite sheets ckey = colors.BLACK # create dragon frames from sprite sheet ss = spritesheet( self.dragon_path ) self.dragon_frames = [] self.dragon_frames.append(ss.image_at((0, 160, 280, 240),colorkey=ckey)) self.dragon_frames.append(ss.image_at((280, 160, 280, 240),colorkey=ckey)) self.dragon_frames.append(ss.image_at((590, 140, 280, 260),colorkey=ckey)) self.dragon_frames.append(ss.image_at((880, 180, 280, 240),colorkey=ckey)) self.dragon_frames.append(ss.image_at((1160, 180, 280, 240),colorkey=ckey)) self.dragon_frames.append(ss.image_at((1440, 180, 280, 240),colorkey=ckey)) self.dragon_frames.append(ss.image_at((1760, 180, 280, 240),colorkey=ckey)) self.dragon_frames.append(ss.image_at((2050, 180, 280, 240),colorkey=ckey)) self.dragon_frames_flipped = self.generate_flipped_frames(self.dragon_frames) # create fire frames from sprite sheet ss = spritesheet( self.fire_path ) self.fire_frames = [] self.fire_frames.append(ss.image_at((130, 0, 75, 45),colorkey=ckey)) self.fire_frames.append(ss.image_at((130, 45, 75, 45),colorkey=ckey)) self.fire_frames.append(ss.image_at((130, 90, 75, 45),colorkey=ckey)) self.fire_frames.append(ss.image_at((130, 130, 75, 45),colorkey=ckey)) self.fire_frames_flipped = self.generate_flipped_frames(self.fire_frames) # create sprites for game def create_sprites(self): self.entities = pygame.sprite.Group() self.bg = pygame.image.load(self.bg_path).convert() self.bg = pygame.transform.smoothscale(self.bg, self.MAP_SIZE) self.bg_rect = self.bg.get_rect() self.player = Player(self) self.entities.add( self.player ) # Render text only once def create_text(self): self.time_font = pygame.font.Font(None, 30) self.gameover_font = pygame.font.Font(None, 120) self.last_font = pygame.font.Font(None, 90) # generate rendered numbers so don't have to re-render self.numbers = {} for x in range(self.TIME_LIMIT + 1): self.numbers[str(x)] = self.time_font.render(str(x), 1, colors._BLACK) # generate cached text self.over_text = self.gameover_font.render("Game Over!", 1, colors._BLACK) self.win_text = self.gameover_font.render("You Win!", 1, colors._BLACK) self.won_bg, self.lost_bg = pygame.Surface(self.SIZE), pygame.Surface(self.SIZE) self.won_bg.fill((10, 185, 13)) self.lost_bg.fill((155, 0, 0)) # generate animation flipped frames def generate_flipped_frames(self, frames): return [pygame.transform.flip(frame, True, False) for frame in frames] # generate random fireball def gen_rand_fireball(self, damage=None): coords = [0, 0] coords[0] = random.randint( self.WIDTH/2 ,self.MAP_WIDTH) coords[1] = random.randint(0 ,self.MAP_HEIGHT) self.spawn_fireball( coords, damage) # add more fireballs def add_fireballs(self): print "adding {} fireballs".format(self.BALL_ADD) for x in range( self.BALL_ADD ): self.gen_rand_fireball() self.BALL_ADD += int(self.BALL_ADD/3) # create a new fireball def spawn_fireball(self, coords, damage=None): fireball = FireBall(self) fireball.set_pos(coords) self.entities.add( fireball ) # kill a fireball object def kill_ball(self, fireball): self.entities.remove( fireball ) fireball.kill() del fireball # check fireball collisions and deal damage def check_collisions(self): fireballs = [e for e in self.entities.sprites() if e.block_id != "player"] fire_rects = [e.rect for e in fireballs] collision = self.player.rect.collidelist( fire_rects ) if collision > -1: fireball = fireballs[ collision ] self.player.HP -= fireball.damage self.kill_ball( fireball ) # clear left over memory because game is over :) def clear_all(self): for e in self.entities.sprites(): self.kill_ball( e ) del self.bg del self.bg_rect del self.entities del self.camera del self.player del self.numbers del self.time_font """ Drawing Functions """ # Lose screen def draw_game_over(self): if not self.HAS_LAST: self.last_text = self.last_font.render("Lasted {} secs".format(self.lasted), 1, colors._BLACK) self.HAS_LAST = True self.screen.blit(self.lost_bg, (0,0)) self.screen.blit(self.over_text, (self.WIDTH/2-240, self.HEIGHT/2-120)) self.screen.blit(self.last_text, (self.WIDTH/2-240, self.HEIGHT/2)) # Win screen def draw_win(self): self.screen.blit(self.won_bg, (0,0)) self.screen.blit(self.win_text, (self.WIDTH/2-180, self.HEIGHT/2-120)) # Health Bar def draw_health(self): # calculate color if self.player.HP > 60: color = colors.H_GREEN elif self.player.HP > 30: color = colors.H_YELLOW else: color = colors.H_RED # calculate bar size bar_width = 200.0 percent_left = (self.player.HP * bar_width) / (self.player.MAX_HP*1.0) percent_lost = ((self.player.MAX_HP-self.player.HP) * bar_width) / (self.player.MAX_HP*1.0) # draw remaining health pygame.draw.rect(self.screen, color, (5, 5, percent_left, 20)) # draw lost health pygame.draw.rect(self.screen, colors.BLACK, (5+percent_left, 5, percent_lost, 20)) """ Game Functions """ def run(self): start = time.time() # start timer while self.running: # handle events for event in pygame.event.get(): if event.type == pygame.QUIT: self.running = False break if not self.GAME_OVER: self.player.update_stop(event) if not self.GAME_OVER: # update objects and screen self.camera.update(self.player) self.entities.update() self.check_collisions() # draw images self.screen.fill(colors.BLACK) self.screen.blit(self.bg, self.camera.apply(self.bg_rect)) for e in self.entities.sprites(): if e.block_id != "player": self.screen.blit(e.image, self.camera.apply(e.rect)) self.screen.blit(self.player.image, self.camera.apply(self.player.rect)) self.draw_health() # spawn fireballs if self.last_num != self.lasted: self.last_num = self.lasted if self.lasted % self.BALL_SPAWN == 0: self.add_fireballs() # keep constant amount of fireballs on screen sprite_num = len(self.entities.sprites()) if sprite_num < self.BALL_ADD: to_add = self.BALL_ADD - sprite_num for x in range(to_add): self.gen_rand_fireball() # calculate & draw time elapsed = round(time.time() - start, 1) self.lasted = int(elapsed) if self.lasted >= self.TIME_LIMIT: self.GAME_OVER = True self.HAS_WON = True self.clear_all() if not self.GAME_OVER: self.screen.blit( self.numbers[str(self.lasted)], (self.WIDTH-80, 10)) # handle game over if not self.GAME_OVER: if self.player.HP <= 0: self.GAME_OVER = True self.clear_all() else: if self.HAS_WON: self.draw_win() else: self.draw_game_over() # update pygame self.clock.tick( self.FPS ) pygame.display.flip() self.exit() def exit(self): pygame.quit() sys.exit()
def game_state(mapSize, aiSpeed, aiDifficulty): global maze global endpoint global startpoint global score # Set an FPS limit so PyGame doesn't destroy the CPU and create a singularity FPS = 60 clock = pygame.time.Clock() # Start with no score score = 0 # Running flag running = True # Setup the PyGame window pygame.init() screen = pygame.display.set_mode((32*mapSize, 32*mapSize)) pygame.display.set_caption('aMAZE - The best game ever') # Generate an initial set of conditions new_round(screen, mapSize, aiDifficulty) # Setup the User and the AI user = Player(startpoint[0], startpoint[1] , (0,255,0), 4) enemy = Player(startpoint[0], startpoint[1], (255,0,0), aiSpeed) enemy.setNodes(aiPath) # Load the maze maze_spr = pygame.image.load("maze.png") # Update the console with score information update_console() # main game loop while running: # Python Window events for event in pygame.event.get(): if event.type == QUIT: pygame.quit() sys.exit() # Update keystates keys = pygame.key.get_pressed() # Update the users position if ( keys[K_LEFT] or keys[K_RIGHT] or \ keys[K_UP] or keys[K_DOWN] ) and user.isMoving() == False: # Get the users location in the graph and its neighbors node = user.getNode() neighbors = maze.graph()[user.getNode()] dx = 0 dy = 0 # Determine what node the user will end up on if keys[K_LEFT]: dx = -1 elif keys[K_RIGHT]: dx = 1 elif keys[K_UP]: dy = -1 elif keys[K_DOWN]: dy = 1 nextNode = (node[0]+dx, node[1]+dy) # Determine if this is an acceptable node if nextNode in neighbors: user.setNodes([nextNode]) # Move the user and the AI user.move() enemy.move() # Render the scene screen.blit(maze_spr,(0,0)) pygame.draw.rect(screen, (0, 255, 255), (endpoint[0]*32+8,endpoint[1]*32+8,16,16), 0) # Render the user and the AI enemy.render(screen) user.render(screen) # Flip the display buffer pygame.display.update() # Check to see if the user beat the AI to the end if user.atNode(endpoint) and not enemy.atNode(endpoint): # Don't increment the Difficulty if its maxed out or a special # Variant if aiDifficulty in [101, -1, -2]: pass else: # Up the difficulty aiDifficulty += 1 # Increase the users score depending on the difficulty score += int(aiDifficulty/100)*aiSpeed + mapSize/4 # Update the console with this new score update_console(score) # Generate a new set of conditions new_round(screen, mapSize, aiDifficulty) # Move the User and player back to the start and update the # AI path user.jump(startpoint) enemy.clearPath() enemy.setNodes(aiPath) enemy.jump(startpoint) # Update the maze maze_spr = pygame.image.load("maze.png") # Check to see if the AI Beat the user to the end elif enemy.atNode(endpoint) and not user.atNode(endpoint): # Quit the game and run the gameover State pygame.quit() os.system("clear") running = False aMAZE.game_over(score) # Limit the framerate clock.tick(FPS) # Quit the application if the user presses q if keys[K_q]: pygame.quit() os.system("clear") running = False aMAZE.game_over(score) return '0'
def runGame(): """Initialize new game.""" pygame.display.set_caption('Escape from Wikipedia - Loading') fpsclock = pygame.time.Clock() camx = 0 camy = 0 section = 0 player = Player(PLAYER_START) loading = Word("LOADING", (camx - 205, camy - 55), attr=BOLD, size=2, color=PURPLE) rabbyt.clear(WHITE) loading.render() # Loading screen pygame.display.flip() # Short, simple page #page = Page("http://en.wikipedia.org/wiki/Solariellidae") # Longest page in Wikipedia #page = Page("http://en.wikipedia.org/wiki/Character_mask") # Random page page = Page("http://en.wikipedia.org/wiki/Special:Random") pygame.display.set_caption('Escape from... ' + page.title) # xkcd #page = Page("http://en.wikipedia.org/wiki/Xkcd") #print len(page.words) # Main loop while True: for event in pygame.event.get(): if event.type == QUIT: terminate() elif event.type == KEYDOWN: if event.key in QUIT_KEYS: terminate() elif event.key in RESTART_KEYS: glutils.scroll(-camx, -camy) # Reset glMatrix return elif event.key in LEFT_KEYS: player.goingleft = True player.goingright = False player.image.tex_shape = (1, 1, 0, 0) elif event.key in RIGHT_KEYS: player.goingright = True player.goingleft = False player.image.tex_shape = (0, 1, 1, 0) elif event.key in UP_KEYS: player.jump() elif event.key in DOWN_KEYS and player.plat is not None: # Enter hyperlink if not player.plat.hyperlink == "": pygame.display.set_caption( 'Escape from Wikipedia - Loading') loading = Word("LOADING", (camx - 205, camy - 55), attr=BOLD, size=2, color=PURPLE) rabbyt.clear(WHITE) loading.render() # Display load screen pygame.display.flip() page = Page(player.plat.hyperlink) pygame.display.set_caption(page.title) pygame.display.set_caption('Escape from... ' + page.title) #print len(page.words) player.reset(page) elif event.type == KEYUP: if event.key in LEFT_KEYS: player.goingleft = False elif event.key in RIGHT_KEYS: player.goingright = False elif event.key in UP_KEYS and player.velocity[1] > 0: player.velocity[1] *= 0.5 # Control jump height # Update position player.update() # Check for player-platform collisions collisions = rabbyt.collisions.aabb_collide_single(player, page.visible_words) # Player forced out of platforms by most direct route, more or less; for plat in collisions: if (player.right / 3 + 2 * player.left / 3 < plat.left and player.velocity[0] > 0): player.right = plat.left - 1 elif (player.left / 3 + 2 * player.right / 3 > plat.right and player.velocity[0] < 0): player.left = plat.right + 1 # More sensitive about the top, to compensate for high fall veloc elif player.top > plat.top and player.velocity[1] < 0: player.bottom = plat.top + 1 player.plat = plat player.velocity[1] = 0 # Stop falling player.jumps = 0 # Reset jumps if plat.hyperlink != "": player.hl_landed(TIMEOUT) elif (2 * player.top / 3 + player.bottom / 3 < plat.bottom and player.velocity[1] > 0): player.top = plat.bottom - 1 player.velocity[1] = 0 # Jump stops prev_section = section prev_y = camy # adjust camera if beyond the "camera slack" if camx - player.x > CAMERASLACK: glutils.scroll(player.x + CAMERASLACK - camx, 0) camx = player.x + CAMERASLACK elif player.x - camx > CAMERASLACK: glutils.scroll(player.x - CAMERASLACK - camx, 0) camx = player.x - CAMERASLACK if camy - player.y > CAMERASLACK: glutils.scroll(0, player.y + CAMERASLACK - camy) camy = player.y + CAMERASLACK elif player.y - camy > CAMERASLACK: glutils.scroll(0, player.y - CAMERASLACK - camy) camy = player.y - CAMERASLACK # Keep track of viewing section section += int(prev_y / WINHEIGHT) - int(camy / WINHEIGHT) if not section == prev_section: if section > len(page.sections) + 1: glutils.scroll(-camx, -camy) # Reset glMatrix return page.visible_words = page.words[ page.sections[min(len(page.sections) - 1, max(0, section - 1))]: page.sections[max(0, min(len(page.sections) - 1, section + 1))]] # Slow to FPS fpsclock.tick(FPS) # Need to tell Rabbyt what time it is every frame rabbyt.set_time(pygame.time.get_ticks() / TIME_FACTOR) # Draw screen rabbyt.clear(WHITE) rabbyt.render_unsorted(page.visible_words) rabbyt.render_unsorted(page.lines) player.render() pygame.display.flip()
class Scene(object): def __init__(self, width, height): self.width = width self.height = height self.buffer_width = 200 self.player = Player(x = width // 2, y = height // 2) self.bg_batch = pyglet.graphics.Batch() self.fg_batch = pyglet.graphics.Batch() self.random_pool = RandomPool(batch = self.bg_batch) pyglet.resource.path = ['.', 'data'] pyglet.resource.reindex() self._sprites = [] self._scenery = [] self._blockers = [] self._bullets = [] self._labels = [] self._npcs = [] self._collections = [self._sprites, self._scenery, self._blockers, self._bullets, self._labels, self._npcs] def add_sprite(self, sprite): self._sprites.append(sprite) sprite.batch = self.bg_batch try: if sprite.sprite_type == "bullet": self._bullets.append(sprite) sprite.batch = self.fg_batch elif sprite.sprite_type == "blocker": self._blockers.append(sprite) elif sprite.sprite_type == "npc": self._npcs.append(sprite) elif sprite.sprite_type == "text": self._labels.append(sprite) else: # scenery self._scenery.append(sprite) except: self._scenery.append(sprite) def remove_sprite(self, sprite): for collection in self._collections: if sprite in collection: collection.remove(sprite) try: sprite.delete() except AttributeError as e: print "Warning:", e def action(self, action): state, action = action.split() self.player.action(state, action) if state == "+" and action == "blink": self.Bullet() def draw(self): self.bg_batch.draw() self.player.draw() self.fg_batch.draw() def update(self, dt): self.player.update(dt) bw = self.buffer_width dx = self.player.vx * dt dy = self.player.vy * dt for sprite in self._sprites: sprite.x -= dx sprite.y -= dy for sprite in self._sprites: if (sprite.x < - bw or sprite.y < - bw or sprite.x > self.width + bw or sprite.y > self.height + bw): if sprite in self._scenery or sprite in self._bullets: self.remove_sprite(sprite) else: # wrap if sprite.x < -bw: sprite.x += self.width + 2 * bw sprite.y += bw if sprite.x > self.width + bw: sprite.x -= self.width + 2 * bw sprite.y -= bw if sprite.y < -bw: sprite.y += self.height + 2 * bw sprite.x += bw if sprite.y > self.height + bw: sprite.y -= self.height + 2 * bw sprite.x -= bw for bullet in self._bullets: bullet.update(dt) #if collision(bullet, self.player): #self.remove_sprite(bullet) #self.game_over() for npc in self._npcs: if collision(npc, bullet): self.remove_sprite(npc) self.remove_sprite(bullet) npc.on_death() for npc in self._npcs: npc.update(self.get_state(), dt) if collision(npc, self.player): self.game_over() for text in self._labels: if collision(self.player, text): text.on_select() def get_state(self): return {"player": (self.player.x, self.player.y), "bullets": ((b.x, b.y) for b in self._bullets)} def random_event(self, dt): for obj in next(self.random_pool): (obj.x, obj.y) = self.random_offscreen_point() obj.batch = self.bg_batch self.add_sprite(obj) def random_offscreen_point(self): bw = self.buffer_width side = random.randint(0,3) if side == 0: # north x = random.randint(0, self.width) y = random.randint(self.height, self.height + bw) elif side == 1: # east x = random.randint(-bw, 0) y = random.randint(0, self.height) elif side == 2: # south x = random.randint(0, self.width) y = random.randint(-bw, 0) else: # west x = random.randint(self.width, self.width + bw) y = random.randint(0, self.height) return x, y def random_onscreen_point(self): x = random.randint(0, self.width) y = random.randint(0, self.height) return x, y def random_point(self, on_screen = True): if on_screen: return self.random_onscreen_point() else: return self.random_offscreen_point() def resize(self, width, height): h = self.height w = self.width self.height = height self.width = width self.player.set_position(width // 2, height // 2) dy = (self.height - h) // 2 dx = (self.width - w) // 2 for sprite in self._sprites: sprite.x += dx sprite.y += dy def fade_text(self): for text in self._labels: text.color = (0, 0, 0, 128) self._scenery.extend(self._labels) self._labels = [] def Title(self, text, on_screen = True): (x, y) = self.random_point(on_screen=on_screen) self.add_sprite(Text(text, 34, (0, 0, 0, 255), x=self.width * 0.5, y=self.height * 0.75, batch=self.bg_batch)) def Narration(self, text, size=24, on_screen = False): (x, y) = self.random_point(on_screen=on_screen) self.add_sprite(Text(text, size, (0, 0, 0, 255), x=x, y=y, batch=self.bg_batch)) def Choice(self, text, size=24, on_select = do_nothing, on_screen = False): (x, y) = self.random_point(on_screen=on_screen) t = Text(text, size, (0, 0, 255, 255), x = x, y = y, batch=self.bg_batch, on_select = None) def on_select_wrapper(): t.color = (255, 0, 0, 255) self.fade_text() on_select() t.on_select = on_select_wrapper self.add_sprite(t) def Troll(self, on_death = do_nothing): (x, y) = self.random_point(on_screen=False) self.add_sprite(Troll(x, y, on_death = on_death)) def Villager(self, on_death = do_nothing): (x, y) = self.random_point(on_screen=False) self.add_sprite(HaplessVillager(x, y, on_death = on_death)) def House(self): (x, y) = self.random_point(on_screen=False) img = pyglet.resource.image("house.png") house = pyglet.sprite.Sprite(img, x=x, y=y) house.sprite_type = "scenery" self.add_sprite(house) def fade_out(self): pass def Bullet(self): x = self.player.x y = self.player.y vx = self.player.vx + self.player.last_vx * 0.5 vy = self.player.vy + self.player.last_vy * 0.5 self.add_sprite(Bullet(x, y, vx, vy)) def game_over(self): self.Narration("And this is how it ends.", on_screen = True)
class Game: WIDTH = 720 HEIGHT = WIDTH/12*9 SIZE = (WIDTH, HEIGHT) MAP_WIDTH = 1980 MAP_HEIGHT = 1080 MAP_SIZE = (MAP_WIDTH, MAP_HEIGHT) FPS = 60 LOG_FILE = "gamelog.log" SAVE_FILE = "save.json" HAS_MAP = False HAS_HEALTH = True MAX_SCALES = 100 def __init__(self): self.create_logger() try: self.debug("Initializing pygame") pygame.init() except Exception as e: self.debug("Init Error: "+str(e)) self.music = None self.bg_vol = 0.4 self.name = None self.entities = None self.map_layer = None self.collisions = [] self.transport_rects = {} try: self.shop = Shop(self) self.manager = LevelManager(self) self.rsc = resources.ResourceManager(self) self.scenes = CutScenes(self) except Exception as e: self.debug("Manager Error: "+str(e)) def init(self, classname="Crystal"): # Create window os.environ['SDL_VIDEO_CENTERED'] = '1' # center screen self.screen = pygame.display.set_mode(self.SIZE) pygame.display.set_caption("Dragon TakeOver") # Load levels try: self.debug("Loading levels...") self.manager.load_all_levels() except Exception as e: self.debug("Level.All Error: " + str(e)) # Add icon ico_path = os.path.join("resources","images","icon.png") ico_surf = self.rsc.load_image(ico_path,(32,32),colors.WHITE) pygame.display.set_icon(ico_surf) # create camera, fps, and game var self.clock = pygame.time.Clock() self.running = True self.game_dead = False self.camera = Camera(self.SIZE, self.MAP_SIZE) self.name = str(classname).lower() # load game try: self.debug("loading resources") font = pygame.font.Font(None, 48) self.load_text = font.render("Loading...",1,colors.WHITE) self.load_rect = self.load_text.get_rect() self.load_rect.centerx = self.screen.get_rect().centerx self.load_rect.centery = self.screen.get_rect().centery self.IS_LOADING = True load_thread = self.create_thread(self.loading_screen) self.rsc.load_resources() self.IS_LOADING = False self.debug("waiting for loading thread to stop...") load_thread.join() self.debug("loading thread killed") except Exception as e: self.debug("Resource error: " + str(e)) try: self.debug("loading shop resources") self.shop.init() except Exception as e: self.debug("Shop.init Error: " + str(e)) self.create_sprites() self.load_save() ### Load Game Save file def load_save(self): save_data = None try: self.debug("loading save data") if os.path.exists(self.SAVE_FILE): with open(self.SAVE_FILE, 'r') as f: save_data = json.loads(f.read()) self.name = save_data['player'] self.scenes.reset_scenes() self.create_player() if os.path.exists(self.SAVE_FILE): self.manager.load_level(save_data['level']) self.load_player_info(save_data) except Exception as e: self.debug("Save data Error: " + str(e)) ### Create/Overwrite Game save file def write_save(self): self.debug("writing save") save = {} save['level'] = self.manager.level save['player'] = self.name save['max_hp'] = self.player.MAX_HP save['max_ap'] = self.player.MAX_AP save['attack'] = self.player.attack save['scales'] = self.player.scales save['boss_scales']= self.player.boss_scales save['party_hp'] = self.player.party_health save['party_atk'] = self.player.party_attack with open(self.SAVE_FILE, 'w') as f: f.write(json.dumps(save, indent=4, sort_keys=True)) ### Create Debug/Game log def create_logger(self): # delete existing log file if os.path.exists(self.LOG_FILE): os.remove(self.LOG_FILE) # create logger logging.basicConfig(filename=self.LOG_FILE, level=logging.DEBUG) ### Create game sprites def create_sprites(self): self.debug("creating sprites") self.background = Block(self.MAP_SIZE) self.background.block_id = "bg" self.entities = pygame.sprite.Group() self.entities.add( self.background ) def create_player(self): self.tests = [] try: self.debug("Creating party..") # spawn player self.player = Player(self, self.name) self.player.block_id = "player" self.entities.add( self.player ) # choose ally bots bot_options = ["crystal","nathan","jack"] bot_options.remove(self.name.lower()) # spawn bots self.bots = [] for bot_name in bot_options: self.debug("Creating bot: "+bot_name) if bot_name == "crystal": bot = CrystalBot(self, bot_name) elif bot_name == "jack": bot = JackBot(self, bot_name) else: bot = NathanBot(self, bot_name) bot.rect.x = self.player.rect.x + 50 bot.rect.y = self.player.rect.y - 50 self.bots.append( bot ) self.entities.add( bot ) except Exception as e: self.debug("Party Creation Error: " + str(e)) ### Load player info from save file def load_player_info(self, info): self.player.MAX_HP = info['max_hp'] self.player.MAX_AP = info['max_ap'] self.player.attack = info['attack'] self.player.scales = info['scales'] self.player.boss_scales = info['boss_scales'] self.player.party_attack = info['party_atk'] self.player.party_health = info['party_hp'] """ EVENT LOOP FUNCTIONS """ def draw(self): for event in pygame.event.get(): if event.type == pygame.QUIT: self.running = False self.player.update_stop(event) self.clock.tick(self.FPS) self.screen.fill(colors.BLACK) self.draw_sprites() self.draw_player_info() self.entities.update() pygame.display.flip() def draw_sprites(self, isScene=False): self.camera.update(self.player) for e in self.entities.sprites(): if e.block_id not in ["player","bot"]: self.screen.blit(e.image, self.camera.apply(e.rect)) # prioritize drawing of player and bots for bot in self.bots: self.screen.blit(bot.image, self.camera.apply(bot.rect)) self.screen.blit(self.player.image, self.camera.apply(self.player.rect)) # do collision for sprite in self.entities.sprites(): if sprite.block_id in ["player","bot"]: if sprite.rect.collidelist(self.collisions) > -1: sprite.move_back() # check transport if not isScene: for name in self.transport_rects: rect = self.transport_rects[name] if self.player.rect.colliderect(rect): print str(name) if name == "void": if self.player.boss_scales < 3: self.player.rect.y -= 30 self.player.h_decel, self.player.v_decel = True, True self.scenes.load_scene(3) spawn = self.manager.levels["village"]["spawn"] self.player.set_pos(spawn[0], spawn[1]) break else: self.manager.load_level(name) break else: pass for x in self.tests: self.screen.blit(x[1], self.camera.apply(x[0])) def draw_bars(self, sprite): _mid = (sprite.MAX_HP*60/100) _low = (sprite.MAX_HP*30/100) bar_width = sprite.bar_width # get length of health percent_left = (sprite.HP * bar_width) / (sprite.MAX_HP * 1.0) percent_lost = ((sprite.MAX_HP - sprite.HP) * bar_width) / (sprite.MAX_HP * 1.0) # get length of ap ap_left = (sprite.AP * bar_width) / (sprite.MAX_AP * 1.0) ap_lost = ((sprite.MAX_AP - sprite.AP) * bar_width) / (sprite.MAX_AP * 1.0) # calculate color if sprite.HP > _mid: color = colors.H_GREEN elif sprite.HP > _low: color = colors.H_YELLOW else: color = colors.H_RED # draw player health if sprite.block_id == "player": bar_x, bar_y = 40, 10 bar_height = 15 # draw HP left = (bar_x+3,bar_y+3, percent_left, bar_height) lost = (bar_x+percent_left+3, bar_y+3, percent_lost, bar_height) pygame.draw.rect(self.screen, color, left) pygame.draw.rect(self.screen, (10, 10, 10), lost) # draw ap left = (bar_x + 3, bar_y + 30, ap_left, bar_height) lost = (bar_x + ap_left+3, bar_y + 30, ap_lost, bar_height) pygame.draw.rect(self.screen, colors.AP_COLOR, left) pygame.draw.rect(self.screen, (10, 10, 10), lost) # draw boss health elif sprite.block_id == "boss": pass # draw mob health else: hp_rect = self.camera.apply(sprite.rect) x, y = hp_rect.x, hp_rect.y start_x = x + (sprite.WIDTH/2) start_y = y - sprite.hp_evel bar_height = 5 left = (start_x, start_y, percent_left, bar_height) lost = (start_x+percent_left, start_y, percent_lost, bar_height) pygame.draw.rect(self.screen, color, left) pygame.draw.rect(self.screen, (10,10,10), lost) def draw_player_info(self): # draw face face = self.player.face self.screen.blit(face, (5,5)) # draw scales scale_text = self.rsc.scale_nums[str(self.player.scales)] boss_text = self.rsc.scale_nums[str(self.player.boss_scales)] self.screen.blit(self.rsc.scale, (5, 65)) self.screen.blit(self.rsc.boss_scale, (105, 65)) self.screen.blit(scale_text, (35, 65)) self.screen.blit(boss_text, (135, 65)) # draw all entity health bars for e in self.entities.sprites(): if e.IS_ALIVE: self.draw_bars(e) #### Other def draw_loading(self): self.clock.tick(self.FPS) self.screen.fill(colors.BLACK) self.screen.blit(self.load_text, self.load_rect) pygame.display.flip() def run(self): while self.running: self.draw() self.exit() def exit(self): self.write_save() pygame.quit() sys.exit() def loading_screen(self): while self.IS_LOADING: self.draw_loading() def create_thread(self, func, *args): t = threading.Thread(target=func, args=args) t.daemon = True t.start() return t def debug(self, text, debug=True): _log = text starter = "> " if not isinstance(text, basestring): _log = repr(text) if debug: logging.debug(starter + _log) else: logging.info(starter + _log) print _log