Exemplo n.º 1
0
    def __init__(self):
        ''' Sets up the initial game board, with the player at a set position.
                Once everything is set up, starts the game.
        '''
        # Set up the screen
        self.screen = GameScreen()
        self.bg = pygame.image.load(IMG_DIR + 'rainbowbg.png')

        # Set up some game components
        self.inventory = Inventory()
        self.map = Map()
        self.map.player = (1 * TILE_SIZE, 1 * TILE_SIZE)
        self.player_stats = Player()
        treasure = self.map.clear_treasure(self.map.player)
        if treasure:
            self.add_treasure(treasure)

        self.clock = pygame.time.Clock()
        self.direction = 0

        self.map.clear_block(self.map.player)
        self.map.set_current_position(self.map.player)

        self.screen.draw_screen_layers(player_stats=self.player_stats,
                                       map=self.map)

        self.run()
Exemplo n.º 2
0
    def load_map(self, file_name):
        """ Indlæser bane """
        # Initialiserer map klasse
        self.map = Map(file_name)

        # Find ud af hvor spilleren er
        player_pos = self.map.get_player_pos()
        if player_pos is not None:
            self.player = Player(player_pos)

        # Konverter bane matrice så det kan bruges af a* pathfinding algoritmen
        map_matrix = self.map.pathfinding_matrix()
        # Find spøgelserne
        ghost_pos = self.map.get_ghost_pos()

        ghosts = []
        for i in range(0, len(ghost_pos)):
            pos, map_type = ghost_pos[i]
            # Initialiser spøgelse klasse
            ghost = Ghost(pos, map_type)
            # Indlæs pathfinding matrice
            ghost.load_matrix(map_matrix)
            ghosts.append(ghost)

        self.ghosts = ghosts
Exemplo n.º 3
0
 def __init__(self, entities: Set[Entity], event_handler: EventHandler,
              gamemap: Map, player: Entity):
     self.entities = entities
     self.event_handler = event_handler
     self.player = player
     self.gamemap = gamemap
     gamemap.load_map("maps/hub.json")
Exemplo n.º 4
0
	def __init__(self):
		''' Sets up the initial game board, with the player at a set position.
	    	    Once everything is set up, starts the game.
		'''
		self.screen = pygame.display.set_mode((1280, 832))
		self.font = pygame.font.SysFont(None, 48)
		self.small_font = pygame.font.SysFont(None, 20)
		self.draw_alert("Welcome to Katie's Roguelike!")
		self.inventory = Inventory()
		self.inventory_screen = self.small_font.render("Inventory", True, WHITE, BLACK)
		self.player = pygame.image.load(IMG_DIR + 'dude.png')
		self.bg = pygame.image.load(IMG_DIR + 'rainbowbg.png')
		self.clock = pygame.time.Clock()
		self.direction = 0
		self.position = (0, 0)
		self.map = Map()
		self.map.clear_block(self.position)
		self.map.set_current_position(self.position)
		treasure = self.map.clear_treasure(self.position)
		if treasure:
			self.add_treasure(treasure)
		self.screen.blit(self.bg, (0,0))
		self.draw_walls()
		self.draw_treasure()
		self.draw_monsters()
		self.draw_darkness()
		self.draw_inventory()
                self.screen.blit(self.player, self.position)
		self.screen.blit(self.alert, (0, 790))
		self.run()
Exemplo n.º 5
0
    def __init__(self):
        ''' Sets up the initial game board, with the player at a set position.
                Once everything is set up, starts the game.
        '''
        # Set up the screen
        self.screen = GameScreen()
        self.bg = pygame.image.load(IMG_DIR + 'rainbowbg.png')

        # Set up some game components
        self.inventory = Inventory()
        self.map = Map()
        self.map.player = (1*TILE_SIZE, 1*TILE_SIZE)
        self.player_stats = Player()
        treasure = self.map.clear_treasure(self.map.player)
        if treasure:
            self.add_treasure(treasure)

        self.clock = pygame.time.Clock()
        self.direction = 0
        
        self.map.clear_block(self.map.player)
        self.map.set_current_position(self.map.player)

        self.screen.draw_screen_layers(player_stats=self.player_stats, map=self.map)
        
        self.run()
Exemplo n.º 6
0
class Game(object):
	"""width and height are the width and height of the starting level"""
	def __init__(self, width, height):
		self.mapt = Map(width, height)

		self.player = Character("Frank", "thief", int(width / 2), int(height / 2))

		self.current_level.set_entity(self.player.x, self.player.y, "guy")



	@property
	def current_level(self):
		return self.mapt.get_level()

	def entity_at(self, x, y):
		return self.current_level.entitylist[y][x]

	def tick(self):
		for entity in self.entitylist:
			entity.tick()

	def move_player(self, direction):	# direction should be one of N, S, E, W, NE, SE, NW, SW as a string
		x = self.player.x
		y = self.player.y
		# horizontal/vertical movement
		if direction.lower() == "n":
			if self.entity_at(x, y - 1).walkable:
				self.player.move(x, y - 1)
				self.current_level.move_entity(x, y, x, y - 1)
		if direction.lower() == "s":
			if self.entity_at(x, y + 1).walkable:
				self.player.move(x, y + 1)
				self.current_level.move_entity(x, y, x, y + 1)
		if direction.lower() == "e":
			if self.entity_at(x + 1, y).walkable:
				self.player.move(x + 1, y)
				self.current_level.move_entity(x, y, x + 1, y)
		if direction.lower() == "w":
			if self.entity_at(x - 1, y).walkable:
				self.player.move(x - 1, y)
				self.current_level.move_entity(x, y, x - 1, y)

		# diagonal movement
		if direction.lower() == "ne":
			if self.entity_at(x + 1, y - 1).walkable:
				self.player.move(x + 1, y - 1)
				self.current_level.move_entity(x, y, x + 1, y - 1)
		if direction.lower() == "se":
			if self.entity_at(x + 1, y + 1).walkable:
				self.player.move(x + 1, y + 1)
				self.current_level.move_entity(x, y, x + 1, y + 1)
		if direction.lower() == "nw":
			if self.entity_at(x - 1, y - 1).walkable:
				self.player.move(x - 1, y - 1)
				self.current_level.move_entity(x, y, x - 1, y - 1)
		if direction.lower() == "sw":
			if self.entity_at(x - 1, y + 1).walkable:
				self.player.move(x - 1, y + 1)
				self.current_level.move_entity(x, y, x - 1, y + 1)
Exemplo n.º 7
0
    def chase(self, player):
        """ Går direkte efter spilleren """
        targetgrid = Map.get_grid(player.pos)
        nexttarget = self.pathfinding(targetgrid)
        if nexttarget is None:
            return

        self.move(nexttarget)
Exemplo n.º 8
0
 def __init__(self, players, clientsocket_list):
     self.bullet_list = []
     self.players = players
     self.strmap = Map(players, self.bullet_list).getrendermap()
     self.gameround = 0
     self.socket = clientsocket_list
     loop = threading.Thread(target=self.gameLoop)
     loop.start()
Exemplo n.º 9
0
    def pathfinding(self, targetgrid):
        """ Find den korteste vej """
        currentgrid = Map.get_grid(self.pos)
        """ matrix = self.matrix.copy()
        if hasattr(self, "prev_grid"):
            # Bloker tile som er bag spøgelse for at den ikke bevæge sig modsat
            # Gem den tile som spøgelset sidst var inde i
            matrix[self.prev_grid[0]][self.prev_grid[1]] = 1 """

        path = astar(self.matrix, tuple(currentgrid), tuple(targetgrid))
        if path is False or len(path) is 0:
            return None

        nextgrid = list(path[-1])
        nextpos = Map.grid_to_pos(nextgrid)

        # Path må kun ændre sig hvis man ikke kommer til at bevæge sig den modsatte vej af hvad man gør nu

        return nextpos
Exemplo n.º 10
0
 def _create_map(self, properties):
     ''' private function that creates a Map
         properties - a dictionary of properties defining how the Map is created.
     '''
     key = properties['key']
     layer = int(properties['layer'])
     sprite_sheet_key = properties['sprite']
     tile_map = self._get_tile_map(properties['map'])
     char_definitions = self._get_char_definitions(properties['char_map'])
     active = (properties['active'].lower() == 'true')
     game_map = Map(key, self._event_manager, layer, sprite_sheet_key, tile_map, char_definitions, active)
     self._event_manager.post(MapCreatedEvent(game_map))
Exemplo n.º 11
0
    def move(self, target):
        """ Vil prøve at bevæge sig til en bestemt position"""

        if Map.inside_grid(self.pos) is True:
            self.prev_grid = Map.get_grid(self.pos)

        if Map.inside_grid(self.pos) is False and Map.axis_aligned(
                self.pos, target) is False:
            # Hvis man ikke er inde i en grid, og x- eller y-aksen ikke er den samme, så gå helt ind i den grid man er i
            # Dette tvinger spøgelserne til kun at bevæge sig inde i tiles
            currentgrid = Map.get_grid(self.pos)
            target = Map.grid_to_pos(currentgrid)

        if self.pos[0] < target[0]:
            self.pos[0] = target[0] if self.pos[0] + self.speed > target[
                0] else self.pos[0] + self.speed
            self.direction = 3
        elif self.pos[0] > target[0]:
            self.pos[0] = target[0] if self.pos[0] - self.speed < target[
                0] else self.pos[0] - self.speed
            self.direction = 4
        elif self.pos[1] < target[1]:
            self.pos[1] = target[1] if self.pos[1] + self.speed > target[
                1] else self.pos[1] + self.speed
            self.direction = 1
        elif self.pos[1] > target[1]:
            self.pos[1] = target[1] if self.pos[1] - self.speed < target[
                1] else self.pos[1] - self.speed
            self.direction = 0
Exemplo n.º 12
0
	def __init__(self):
		self.screen = GameScreen()
		self.bg = pygame.image.load(IMG_DIR + 'background.png')
		death_sound = pygame.mixer.Sound(SFX_DIR + 'death.ogg')
		
		self.inventory = Inventory()
		self.map = Map()
		self.map.player = (1*TILE_SIZE, 1*TILE_SIZE)
		self.player_stats = Player()
		treasure = self.map.clear_treasure(self.map.player)
		if treasure:
			self.add_treasure(treasure)

		self.clock = pygame.time.Clock()
		self.direction = 0

		self.map.clear_block(self.map.player)
		self.map.set_current_position(self.map.player)
		
		self.screen.draw_screen_layers(player_stats=self.player_stats, map=self.map)
		
		self.run()
Exemplo n.º 13
0
    def _create_map(self, element):
        ''' private function that creates a Map
            element - an xml element defining how the Map is created.
        '''
        key = element.attributes['key'].value
        active = element.attributes['active'].value.lower() == 'true'
        tmp = element.attributes['size'].value.lower().split('x')
        size = (int(tmp[0]), int(tmp[1]))
        tmp = element.attributes['unit_size'].value.lower().split('x')
        unit_size = (int(tmp[0]), int(tmp[1]))

        tiles = []

        xmldoc = minidom.parse(element.attributes['map'].value)
        for tile in xmldoc.getElementsByTagName('tile'):
            sprite_key = tile.attributes['sprite'].value
            x = int(tile.attributes['x'].value)
            y = int(tile.attributes['y'].value)
            tiles.append(Tile(0, sprite_key, x, y))

        map = Map(key, 0, tiles, active, size, unit_size)
        event_manager.post(MapCreatedEvent(map))
Exemplo n.º 14
0
def main() -> None:
    screen_width = 100
    screen_height = 80

    mapwidth = 100
    mapheight = 80

    #define tileset
    #tileset = tcod.tileset.load_tilesheet(
    #    "terminal.png", 16, 16, tcod.tileset.CHARMAP_TCOD
    #)

    event_handler = EventHandler()

    player = Entity(35, 35, "@", (0, 255, 213))
    creature = Entity(35, 15, "S", (255, 0, 0))
    entities = {creature, player}
    gamemap = Map(mapwidth, mapheight)

    engine = Engine(entities=entities,
                    event_handler=event_handler,
                    gamemap=gamemap,
                    player=player)

    #init terminal window
    with tcod.context.new_terminal(
            150,
            120,
            #tileset = tileset,
            title="Hartbrook",
            vsync=True) as context:
        root_console = tcod.Console(screen_width, screen_height, order="F")
        while True:

            engine.render(console=root_console, context=context)

            events = tcod.event.wait()

            engine.handle_events(events)
Exemplo n.º 15
0
def time_end(players, game):
    i = 0
    #一股C味
    #结束双方回合,进行回合运算,输入命令和玩家字典,给玩家对象和命令对象迭代
    for player in players:
        move = {
            "W": player.up,
            "A": player.right,
            "S": player.down,
            "D": player.left
        }
        for cmditem in player.cmd:
            if cmditem.isdigit():
                game.bullet_list.extend(player.handcard.useCard(cmditem))
            elif isinstance(cmditem, str):
                move[cmditem]()
        i += 1

    result = bullet_move(game.bullet_list, players)
    if result is not None:
        return (result)
    game.strmap = Map(players, game.bullet_list).getrendermap()
    return (game.strmap)
Exemplo n.º 16
0
class Game(object):
    ''' The game object. Controls rendering the game and moving the player.
    '''
    def __init__(self):
        ''' Sets up the initial game board, with the player at a set position.
                Once everything is set up, starts the game.
        '''
        # Set up the screen
        self.screen = GameScreen()
        self.bg = pygame.image.load(IMG_DIR + 'rainbowbg.png')

        # Set up some game components
        self.inventory = Inventory()
        self.map = Map()
        self.map.player = (1 * TILE_SIZE, 1 * TILE_SIZE)
        self.player_stats = Player()
        treasure = self.map.clear_treasure(self.map.player)
        if treasure:
            self.add_treasure(treasure)

        self.clock = pygame.time.Clock()
        self.direction = 0

        self.map.clear_block(self.map.player)
        self.map.set_current_position(self.map.player)

        self.screen.draw_screen_layers(player_stats=self.player_stats,
                                       map=self.map)

        self.run()

    def add_treasure(self, treasure):
        ''' Adds the treasure to the player's inventory
        '''
        text = "You found a %s. %s" % (treasure.title, treasure.description)
        self.inventory.add_to_inventory(treasure, self.player_stats)
        self.screen.draw_alert(text)

    def move(self, hor, vert):
        ''' Moves the player, given a keypress. 
            Also evaluates if the player needs to fight or pick up some treasure.
        '''
        self.old_row, self.old_col = self.map.player
        row = self.old_row + hor
        col = self.old_col + vert
        if row > (ROWS - 1) * TILE_SIZE or row < 0 or col > (
                COLUMNS - 1) * TILE_SIZE or col < 0:
            return
        if self.map.has_wall(row, col):
            return
        if self.map.has_monster(row, col):
            Combat(self.player_stats,
                   self.map.monsters[row / TILE_SIZE][col / TILE_SIZE])
            if self.map.monsters[row / TILE_SIZE][col /
                                                  TILE_SIZE].current_hp <= 0:
                pass  #put death throes here
            if self.player_stats.current_hp <= 0:
                self.end_game()
            self.move(0, 0)
            return
        self.map.player = (row, col)
        self.map.player = (row, col)
        self.map.clear_block(self.map.player)
        self.map.set_current_position(self.map.player)
        treasure = self.map.clear_treasure(self.map.player)
        if treasure:
            self.add_treasure(treasure)
            self.screen.draw_inventory(self.inventory)
            self.screen.draw_equipment(self.player_stats.equipped)

    def refresh_screen(self):
        self.screen.draw_player(self.map.player)
        self.screen.draw_screen_layers(self.map, self.player_stats)

    def end_game(self):
        ''' The exit screen for when the player has died, or completed the game. 
            So far, all it does is exit the game.
        '''
        sys.exit()

    def run(self):
        ''' The main loop of the game.
        '''
        # Fix for double move from Joshua Grigonis! Thanks!
        hor = 0
        vert = 0
        while 1:
            self.clock.tick(30)
            for event in pygame.event.get():
                if event.type == QUIT:
                    sys.exit(0)
                if event.type == KEYDOWN:
                    if event.key == K_ESCAPE:
                        sys.exit(0)
                    if event.key == K_LEFT:
                        hor = -TILE_SIZE
                        vert = 0
                    if event.key == K_RIGHT:
                        hor = TILE_SIZE
                        vert = 0
                    if event.key == K_UP:
                        vert = -TILE_SIZE
                        hor = 0
                    if event.key == K_DOWN:
                        vert = TILE_SIZE
                        hor = 0
                if event.type == KEYUP:
                    # updates only occur is player has moved.
                    if vert or hor:
                        self.move(hor, vert)
                        self.map.move_monsters()
                        hor = 0
                        vert = 0
            self.refresh_screen()
Exemplo n.º 17
0
class Game:
    """ Initialiserer game klasse """
    def __init__(self):
        self.state = 0
        self.score = 0
        self.lives = 3

    def load_map(self, file_name):
        """ Indlæser bane """
        # Initialiserer map klasse
        self.map = Map(file_name)

        # Find ud af hvor spilleren er
        player_pos = self.map.get_player_pos()
        if player_pos is not None:
            self.player = Player(player_pos)

        # Konverter bane matrice så det kan bruges af a* pathfinding algoritmen
        map_matrix = self.map.pathfinding_matrix()
        # Find spøgelserne
        ghost_pos = self.map.get_ghost_pos()

        ghosts = []
        for i in range(0, len(ghost_pos)):
            pos, map_type = ghost_pos[i]
            # Initialiser spøgelse klasse
            ghost = Ghost(pos, map_type)
            # Indlæs pathfinding matrice
            ghost.load_matrix(map_matrix)
            ghosts.append(ghost)

        self.ghosts = ghosts

    def tick(self, pressed):
        """ Kaldes hver iteration i spil loopet """

        if self.player:
            x = self.player.pos[0]
            y = self.player.pos[1]

            self.player.above = self.map.grid_type(
                [x, y - self.player.speed],
                True) is Map.WALL or self.map.grid_type(
                    [x + 15, y - self.player.speed], True) is Map.WALL
            self.player.below = self.map.grid_type(
                [x, y + 15 + self.player.speed],
                True) is Map.WALL or self.map.grid_type([x + 15, y + 16],
                                                        True) is 1
            self.player.right = self.map.grid_type(
                [x + 15 + self.player.speed, y],
                True) is Map.WALL or self.map.grid_type(
                    [x + 15 + self.player.speed, y + 15], True) is Map.WALL
            self.player.left = self.map.grid_type(
                [x - self.player.speed, y],
                True) is Map.WALL or self.map.grid_type(
                    [x - self.player.speed, y + 15], True) is Map.WALL

            grid = self.map.get_grid(self.player.pos)

            if self.map.grid_type(grid) is None and self.map.inside_grid(
                    self.player.pos) is True:
                # Teleporter spilleren til den modsatte side
                if self.player.direction in (2, 3):
                    self.player.pos[0] = self.player.pos[0] % (self.map.width *
                                                               16)
                else:
                    self.player.pos[1] = self.player.pos[0] % (
                        self.map.height * 16)
            else:
                if self.map.grid_type(
                        grid) is Map.POINT and self.map.inside_grid(
                            self.player.pos) is True:
                    # Hvis spilleren står inde i et grid med et point, og spilleren er helt inde i grid, så fjern
                    # point fra banen og incrementer scoren
                    self.score += 10
                    self.map.remove_point(grid)
                    if self.map.removed_points == self.map.total_points:
                        # Der er ikke flere point i banen, start ny bane
                        self.load_map("default.png")
                        return
                self.player.tick(pressed)

        if len(self.ghosts) is not 0:
            for ghost in self.ghosts:
                # Spøgelserne skal vide hvor spilleren er
                ghost.tick(self.player)

            # Tjek om et spøgelse befinder sig i pacman's tile
            if Map.grid_match(self.player.pos, ghost.pos, True) is True:
                self.lives -= 1
                if self.lives is 0:
                    self.end_game()
                else:
                    self.load_map("default.png")

    def start_game(self):
        """ Starter spillet """
        if self.state == 0:
            # Starter et nyt spil
            self.state = 1
        elif self.state == 3:
            # Spillet er stoppet, starter et nyt
            self.state = 1
            self.score = 0
            self.lives = 3
            self.load_map("default.png")

    def end_game(self):
        """ Stopper spillet """
        self.state = 3

    def toggle_pause(self):
        """ Pauser spillet """
        if self.state == 1:
            # Spillet er i gang, pauser det
            self.state = 2
        elif self.state == 2:
            # Spillet er pauset, starter det
            self.state = 1
Exemplo n.º 18
0
    def tick(self, pressed):
        """ Kaldes hver iteration i spil loopet """

        if self.player:
            x = self.player.pos[0]
            y = self.player.pos[1]

            self.player.above = self.map.grid_type(
                [x, y - self.player.speed],
                True) is Map.WALL or self.map.grid_type(
                    [x + 15, y - self.player.speed], True) is Map.WALL
            self.player.below = self.map.grid_type(
                [x, y + 15 + self.player.speed],
                True) is Map.WALL or self.map.grid_type([x + 15, y + 16],
                                                        True) is 1
            self.player.right = self.map.grid_type(
                [x + 15 + self.player.speed, y],
                True) is Map.WALL or self.map.grid_type(
                    [x + 15 + self.player.speed, y + 15], True) is Map.WALL
            self.player.left = self.map.grid_type(
                [x - self.player.speed, y],
                True) is Map.WALL or self.map.grid_type(
                    [x - self.player.speed, y + 15], True) is Map.WALL

            grid = self.map.get_grid(self.player.pos)

            if self.map.grid_type(grid) is None and self.map.inside_grid(
                    self.player.pos) is True:
                # Teleporter spilleren til den modsatte side
                if self.player.direction in (2, 3):
                    self.player.pos[0] = self.player.pos[0] % (self.map.width *
                                                               16)
                else:
                    self.player.pos[1] = self.player.pos[0] % (
                        self.map.height * 16)
            else:
                if self.map.grid_type(
                        grid) is Map.POINT and self.map.inside_grid(
                            self.player.pos) is True:
                    # Hvis spilleren står inde i et grid med et point, og spilleren er helt inde i grid, så fjern
                    # point fra banen og incrementer scoren
                    self.score += 10
                    self.map.remove_point(grid)
                    if self.map.removed_points == self.map.total_points:
                        # Der er ikke flere point i banen, start ny bane
                        self.load_map("default.png")
                        return
                self.player.tick(pressed)

        if len(self.ghosts) is not 0:
            for ghost in self.ghosts:
                # Spøgelserne skal vide hvor spilleren er
                ghost.tick(self.player)

            # Tjek om et spøgelse befinder sig i pacman's tile
            if Map.grid_match(self.player.pos, ghost.pos, True) is True:
                self.lives -= 1
                if self.lives is 0:
                    self.end_game()
                else:
                    self.load_map("default.png")
Exemplo n.º 19
0
	def __init__(self, width, height):
		self.mapt = Map(width, height)

		self.player = Character("Frank", "thief", int(width / 2), int(height / 2))

		self.current_level.set_entity(self.player.x, self.player.y, "guy")
Exemplo n.º 20
0
class Game(object):
    ''' The game object. Controls rendering the game and moving the player.
    '''
    def __init__(self):
        ''' Sets up the initial game board, with the player at a set position.
                Once everything is set up, starts the game.
        '''
        # Set up the screen
        self.screen = GameScreen()
        self.bg = pygame.image.load(IMG_DIR + 'rainbowbg.png')

        # Set up some game components
        self.inventory = Inventory()
        self.map = Map()
        self.map.player = (1*TILE_SIZE, 1*TILE_SIZE)
        self.player_stats = Player()
        treasure = self.map.clear_treasure(self.map.player)
        if treasure:
            self.add_treasure(treasure)

        self.clock = pygame.time.Clock()
        self.direction = 0
        
        self.map.clear_block(self.map.player)
        self.map.set_current_position(self.map.player)

        self.screen.draw_screen_layers(player_stats=self.player_stats, map=self.map)
        
        self.run()

    def add_treasure(self, treasure):
        ''' Adds the treasure to the player's inventory
        '''
        text = "You found a %s. %s" % (treasure.title, treasure.description)
        self.inventory.add_to_inventory(treasure, self.player_stats)
        self.screen.draw_alert(text)

    def move(self, hor, vert):
        ''' Moves the player, given a keypress. 
            Also evaluates if the player needs to fight or pick up some treasure.
        '''
        self.old_row, self.old_col = self.map.player
        row = self.old_row + hor
        col = self.old_col + vert
        if row > (ROWS-1) * TILE_SIZE or row < 0 or col > (COLUMNS-1) * TILE_SIZE or col < 0:
            return
        if self.map.has_wall(row, col):
            return
        if self.map.has_monster(row, col):
            Combat(self.player_stats, self.map.monsters[row/TILE_SIZE][col/TILE_SIZE])
            if self.map.monsters[row/TILE_SIZE][col/TILE_SIZE].current_hp <= 0:
                pass #put death throes here
            if self.player_stats.current_hp <= 0:
                self.end_game()
            self.move(0,0)
            return
        self.map.player = (row, col)
        self.map.player = (row, col)
        self.map.clear_block(self.map.player)
        self.map.set_current_position(self.map.player)
        treasure = self.map.clear_treasure(self.map.player)
        if treasure:
            self.add_treasure(treasure)
            self.screen.draw_inventory(self.inventory)
            self.screen.draw_equipment(self.player_stats.equipped)

    def refresh_screen(self):
        self.screen.draw_player(self.map.player)
        self.screen.draw_screen_layers(self.map, self.player_stats)

    def end_game(self):
        ''' The exit screen for when the player has died, or completed the game. 
            So far, all it does is exit the game.
        '''
        sys.exit()

    def run(self):
        ''' The main loop of the game.
        '''
        # Fix for double move from Joshua Grigonis! Thanks!
        hor = 0
        vert = 0
        while 1:
            self.clock.tick(30)
            for event in pygame.event.get():
                if event.type == QUIT:
                    sys.exit(0)
                if event.type == KEYDOWN:
                    if event.key == K_ESCAPE: 
                        sys.exit(0)
                    if event.key == K_LEFT:
                        hor = -TILE_SIZE
                        vert = 0
                    if event.key == K_RIGHT:
                        hor = TILE_SIZE
                        vert = 0
                    if event.key == K_UP:
                        vert = -TILE_SIZE
                        hor = 0
                    if event.key == K_DOWN:
                        vert = TILE_SIZE
                        hor = 0
                if event.type == KEYUP:
                    # updates only occur is player has moved.
                    if vert or hor:
                        self.move(hor, vert)
                        self.map.move_monsters()
                        hor = 0
                        vert = 0    
            self.refresh_screen()
Exemplo n.º 21
0
class Game(object):
	# game object, controls rendering game and moving player
	def __init__(self):
		self.screen = GameScreen()
		self.bg = pygame.image.load(IMG_DIR + 'background.png')
		death_sound = pygame.mixer.Sound(SFX_DIR + 'death.ogg')
		
		self.inventory = Inventory()
		self.map = Map()
		self.map.player = (1*TILE_SIZE, 1*TILE_SIZE)
		self.player_stats = Player()
		treasure = self.map.clear_treasure(self.map.player)
		if treasure:
			self.add_treasure(treasure)

		self.clock = pygame.time.Clock()
		self.direction = 0

		self.map.clear_block(self.map.player)
		self.map.set_current_position(self.map.player)
		
		self.screen.draw_screen_layers(player_stats=self.player_stats, map=self.map)
		
		self.run()

	def add_treasure(self, treasure):
		text = 'You found a %s. %s' % (treasure.title, treasure.description)
		self.inventory.add_to_inventory(treasure, self.player_stats)
		self.screen.draw_alert(text)

	def move(self, hor, vert):
		# given keypress, moves player
		# also checks for fight or treasure pick-up
		self.old_row, self.old_col = self.map.player
		row = self.old_row + hor
		col = self.old_col + vert
		if row > (ROWS-1)*TILE_SIZE or row < 0 or col > (COLUMNS-1)*TILE_SIZE or col < 0:
			return
		if self.map.has_wall(row, col):
			return
		if self.map.has_monster(row, col):
			Combat(self.player_stats, self.map.monsters[row/TILE_SIZE][col/TILE_SIZE]).fight()
			if self.map.monsters[row/TILE_SIZE][col/TILE_SIZE].current_hp <= 0:
				Combat(self.player_stats, self.map.monsters[row/TILE_SIZE][col/TILE_SIZE]).award_exp()
				Combat(self.player_stats, self.map.monsters[row/TILE_SIZE][col/TILE_SIZE]).death_note(self.map.monsters[row/TILE_SIZE][col/TILE_SIZE].stats['Death Note'])
				self.map.monsters[row/TILE_SIZE][col/TILE_SIZE] = 0
			if self.player_stats.current_hp <= 0:
				death_sound.play()
				self.end_game()
			self.move(0, 0)
			return
		self.map.player = (row, col)
		self.map.player = (row, col)
		self.map.clear_block(self.map.player)
		self.map.set_current_position(self.map.player)
		treasure = self.map.clear_treasure(self.map.player)
		if treasure:
			self.add_treasure(treasure)
			self.screen.draw_inventory(self.inventory)
			self.screen.draw_equipment(self.player_stats.equipped)

	def refresh_screen(self):
		self.screen.draw_player(self.map.player)
		self.screen.draw_screen_layers(self.map, self.player_stats)

	def end_game(self):
		# exit screen for when player has died or won

		self.terminate()

	def run(self):
		# event handler
		hor = 0
		vert = 0
		hard_music = 0
		while hard_music == 0:
			self.begin_music()
			hard_music = 1

		while 1:
			self.clock.tick(30)

			for event in pygame.event.get():
				if not hasattr(event, 'key'):
					continue
				if event.type == KEYDOWN:
					if event.key == K_ESCAPE:
						self.terminate()
					if event.key == K_LEFT:
						hor = -TILE_SIZE
						vert = 0
					if event.key == K_RIGHT:
						hor = TILE_SIZE
						vert = 0
					if event.key == K_UP:
						vert = -TILE_SIZE
						hor = 0
					if event.key == K_DOWN:
						vert = TILE_SIZE
						hor = 0
				if event.type == KEYUP:
					self.map.move_monsters()
					self.move(hor, vert)
					hor = 0
					vert = 0
			self.refresh_screen()

	def terminate(self):
		pygame.quit()
		sys.exit()

	def begin_music(self):
		pygame.mixer.init(22050, -8, 4, 4096)
		pygame.mixer.music.load(SFX_DIR + 'Raver.flac')
		pygame.mixer.music.play(-1, 0.0)
Exemplo n.º 22
0
class Game(object):
    ''' The game object. Controls rendering the game and moving the player.
    '''
    def __init__(self):
        ''' Sets up the initial game board, with the player at a set position.
                Once everything is set up, starts the game.
        '''
        # Set up the screen
        self.screen = pygame.display.set_mode((1280, 832))
        self.font = pygame.font.SysFont(None, 48)
        self.small_font = pygame.font.SysFont(None, 20)
        self.draw_alert("Welcome to Katie's Roguelike!")
        self.bg = pygame.image.load(IMG_DIR + 'rainbowbg.png')
        self.player_blit = pygame.image.load(IMG_DIR + 'dude.png')
        self.screen.blit(self.bg, (0,0))

        # Set up some game components
        self.inventory = Inventory()
        self.map = Map()
        self.map.player = (0, 0)
        self.player_stats = Player()
        treasure = self.map.clear_treasure(self.map.player)
        if treasure:
            self.add_treasure(treasure)

        self.inventory_screen = self.small_font.render("Inventory", True, WHITE, BLACK)
        self.stats_screen = self.small_font.render("ARGH", True, WHITE, BLACK)
        
        self.clock = pygame.time.Clock()
        self.direction = 0
        
        self.map.clear_block(self.map.player)
        self.map.set_current_position(self.map.player)
        
        self.draw_walls()
        self.draw_stats()
        self.draw_treasure()
        self.draw_monsters()
        self.draw_darkness()
        self.draw_inventory()
        self.draw_stats()
        self.screen.blit(self.player_blit, self.map.player)
        self.screen.blit(self.alert, (0, 790))
        self.run()

    def draw_stats(self, color=WHITE):
        self.screen.blit(self.stats_screen, (1008, 0))
        self.stats_screen = self.small_font.render(self.player_stats.name, True, color, BLACK)
        self.screen.blit(self.stats_screen, (1008, 0))
        self.stats_screen = self.small_font.render("Level: " + str(self.player_stats.level), True, color, BLACK)
        self.screen.blit(self.stats_screen, (1008, 15))
        self.stats_screen = self.small_font.render("HP: %s/%s" % (str(self.player_stats.current_hp), str(self.player_stats.max_hp)), True, color, BLACK)
        self.screen.blit(self.stats_screen, (1008, 30)) 

    def draw_alert(self, alert, color=WHITE):
        ''' Draws the alert box at the bottom 
        '''
        self.alert = self.font.render(LONG_STRING, True, BLACK, BLACK)
        self.screen.blit(self.alert, (0, 790))
        try:
            pygame.display.flip()
        except:
            pass
        self.alert = self.font.render(alert, True, color, BLACK)

    def draw_inventory(self):
        self.screen.blit(self.inventory_screen, (1008, 100))
        items = self.inventory.get_items()
        for i in range(items.__len__()):
            line = self.small_font.render(LONG_STRING, True, BLACK, BLACK)
            self.screen.blit(line, (1008, ((i+1)*15)+100))
        pygame.display.flip()
        for item in items:
            line = self.small_font.render(item, True, WHITE, BLACK)
            self.screen.blit(line, (1008, (items.index(item)+1)*15+100))
        pygame.display.flip()

    def add_treasure(self, treasure):
        text = "You found a %s. %s" % (treasure.title, treasure.description)
        self.inventory.add_to_inventory(treasure.title)
        self.draw_alert(text)

    def draw_treasure(self):
        ''' Draws the treasure chests yet to be opened.
        '''
        for row in range(ROWS):
            for col in range(COLUMNS):
                if self.map.treasure[row][col] != 0:
                    treasure = pygame.image.load(IMG_DIR + 'chest.png')
                    self.screen.blit(treasure, (row*TILE_SIZE, col*TILE_SIZE))
    
    def draw_monsters(self):
        for row in range(ROWS):
            for col in range(COLUMNS):
                if self.map.monsters[row][col] != 0 and self.map.current[row][col] != 0:
                    monster = pygame.image.load(IMG_DIR + 'dumb_monster.png')
                    self.screen.blit(monster, (row*TILE_SIZE, col*TILE_SIZE))
    
    def draw_walls(self):
        for row in range(ROWS):
            for col in range(COLUMNS):
                if self.map.walls[row][col] != 0:
                    wall = pygame.image.load(IMG_DIR + 'wall.png')
                    self.screen.blit(wall, (row*TILE_SIZE, col*TILE_SIZE))

    def draw_darkness(self):
        ''' Draws the darkness and shadows on the board. 0 is dark, 1 is in shadows,
        '''
        for row in range(ROWS):
            for col in range(COLUMNS):
                if self.map.cleared[row][col] == 0:
                    if not self.map.current[row][col]:
                        pygame.draw.rect(self.screen, BLACK, (row*TILE_SIZE, col*TILE_SIZE, TILE_SIZE, TILE_SIZE))  
                if self.map.cleared[row][col] == 1:
                    if not self.map.current[row][col]:
                        shadow = pygame.Surface((TILE_SIZE, TILE_SIZE))
                        shadow.set_alpha(200)
                        shadow.fill(BLACK)
                        self.screen.blit(shadow, (row*TILE_SIZE, col*TILE_SIZE))

    def has_wall(self, row, col):
        row = row/TILE_SIZE
        col = col/TILE_SIZE
        if self.map.walls[row][col]:
            return True
        else:
            return False

    def has_monster(self, row, col):
        row = row/TILE_SIZE
        col = col/TILE_SIZE
        if self.map.monsters[row][col]:
            return True
        else:
            return False
    

    def move(self, hor, vert):
        ''' Moves the player, given a keypress. 
        '''
        self.old_row, self.old_col = self.map.player
        row = self.old_row + hor
        col = self.old_col + vert
        if row > (ROWS-1) * TILE_SIZE or row < 0 or col > (COLUMNS-1) * TILE_SIZE or col < 0:
            return
        if self.has_wall(row, col):
            return
        if self.has_monster(row, col):
            Combat(self.player_stats, self.map.monsters[row/TILE_SIZE][col/TILE_SIZE]).fight()
            return
        self.map.player = (row, col)
        self.map.player = (row, col)
        self.map.clear_block(self.map.player)
        self.map.set_current_position(self.map.player)
        treasure = self.map.clear_treasure(self.map.player)
        if treasure:
            self.add_treasure(treasure)
            self.draw_inventory()
        self.screen.blit(self.player_blit, self.map.player)
        self.draw_screen_layers()
        self.screen.blit(self.player_blit, self.map.player)
        pygame.display.flip()

    def draw_screen_layers(self):
        self.screen.blit(self.bg, (0, 0))
        self.draw_treasure()
        self.draw_walls()
        self.draw_monsters()
        self.draw_darkness()
        self.draw_stats()
        self.screen.blit(self.alert, (0, 790))

    def animate_move(self, hor, vert, blit):
        if vert:
            if vert > 0:
                for i in range(TILE_SIZE/MOVEMENT_SIZE):
                    self.draw_screen_layers()
                    self.screen.blit(self.__getattribute__(blit), [self.old_row, self.old_col+i*MOVEMENT_SIZE])
                    pygame.display.update()
            else:
                for i in range(TILE_SIZE/MOVEMENT_SIZE):
                    self.draw_screen_layers()
                    self.screen.blit(self.__getattribute__(blit), [self.old_row, self.old_col-i*MOVEMENT_SIZE])
                    pygame.display.update()
        if hor:
            if hor > 0:
                for i in range(TILE_SIZE/MOVEMENT_SIZE):
                    self.draw_screen_layers()
                    self.screen.blit(self.__getattribute__(blit), [self.old_row+i*MOVEMENT_SIZE, self.old_col])
                    pygame.display.update()
            else:
                for i in range(TILE_SIZE/MOVEMENT_SIZE):
                    self.draw_screen_layers()
                    self.screen.blit(self.__getattribute__(blit), [self.old_row-i*MOVEMENT_SIZE, self.old_col])
                    pygame.display.update()

    def run(self):
        ''' The main loop of the game.
        '''
        # Fix for double move from Joshua Grigonis! Thanks!
        hor = 0
        vert = 0
        while 1:
            self.clock.tick(30)
            for event in pygame.event.get():
                if not hasattr(event, 'key'): 
                    continue
                if event.type == KEYDOWN:
                    if event.key == K_ESCAPE: 
                        sys.exit(0)
                    if event.key == K_LEFT:
                        hor = -TILE_SIZE
                        vert = 0
                    if event.key == K_RIGHT:
                        hor = TILE_SIZE
                        vert = 0
                    if event.key == K_UP:
                        vert = -TILE_SIZE
                        hor = 0
                    if event.key == K_DOWN:
                        vert = TILE_SIZE
                        hor = 0
                if event.type == KEYUP:
                    self.move(hor, vert)
                    self.map.move_monsters()
                    hor = 0
                    vert = 0