예제 #1
0
 def __init__(self):
     self.text = Text()
     self.myPlayer = Player(self)
     self.myEnemy = Enemy(self)
     self.quests = Quests(self)
     self.zonemap = zonemap
     self.equipment_set = equipment_set
예제 #2
0
    def initialize(self):
        self.score = 0
        self.time = 60

        if self.bgm_on:
            pygame.mixer.music.play(-1)

        # characters
        self.man: Player = Player(300, self.height - 105, 64, 64)
        self.goblins: List[Enemy] = []
        self.bullets: List[Projectile] = []

        # round
        self.round = 1
        self.pass_score = 50

        # loops
        self.shoot_loop = 0
        self.shoot_interval = 5
        self.enemy_loop = 0
        self.enemy_interval = 30
        self.dead_loop = 0
        self.dead_interval = 40
        self.is_dead = False

        # limits
        self.bullets_limit = 5
        self.enemies_limit = 3
예제 #3
0
 def initialize_player(self):
     """ (None) -> None
     Initialize the player character for use in the game loop.
     """
     if not self.player:
         player_spritesheet = Spritesheet('player.png', 2, 4)
         self.player = Player(self.screen_w // 2, self.screen_h // 2, 7, *player_spritesheet[0:6])
         self.player.set_aiming_image(player_spritesheet[6])
예제 #4
0
    def test_randomize_initial_position(self):

        test_player = Player()
        test_player.randomize_initial_position(self.map_for_player_test)

        self.assertIn(test_player.player_x,
                      range(0, self.map_for_player_test.map_size[0]))
        self.assertIn(test_player.player_y,
                      range(0, self.map_for_player_test.map_size[1]))
예제 #5
0
    def __init__(self):

        self.dungeon_map = DungeonMap()
        self.player_map = PlayerMap()
        self.player = Player()
        self.enemy = Enemy()
        self.is_game_ongoing = False
        self.time = time.clock()
        self.enemy_last_position = []
        self.enemy_cell = '?'
예제 #6
0
 def __init__(self, scene_manager):
     Scene.__init__(self, scene_manager)
     self.level = Level()
     self.bg = self.level.pre_render_map()
     self.allsprites = load_spritesheet_nested(
         'assets/character_sprites.png')
     self.sprites = pygame.sprite.LayeredDirty()
     self.player = Player(self.level, self.allsprites[0], [self.sprites],
                          (1, 1))
     monster = MonsterNPC(self.level, self.allsprites[4], [self.sprites],
                          (1, 2))
     girl = WanderingNPC(self.level, self.allsprites[1], [self.sprites],
                         (0, 0))
     rock = RockNPC(self.level, self.allsprites[3], [self.sprites], (3, 3))
     for char in [self.player, girl, rock, monster]:
         self.sprites.change_layer(char, 1)
예제 #7
0
    def divide_cards(self):
        """
        Divides cards (Room, Item and Guest):
            1. Selects room, murder weapon and killer.
            2. Shuffle remaining cards.
            3. Splits some cards between Policemen.
            4. Creates Players and splits remaining cards between them.
        """
        cards = []
        cards.extend(Room.rooms)
        cards.extend(Item.items)
        cards.extend(Guest.guests)

        sec = [randint(0, 8), randint(9, 14), randint(15, 20)]
        self._secret["room"] = cards[sec[0]]
        self._secret["item"] = cards[sec[1]]
        self._secret["guest"] = cards[sec[2]]

        del cards[sec[2]]
        del cards[sec[1]]
        del cards[sec[0]]

        division = {
            3: [2, 2, 2, 6, 6],
            4: [2, 1, 2, 4, 5, 4],
            5: [2, 1, 1, 3, 4, 3, 4],
            6: [1, 1, 1, 3, 3, 3, 3, 3]
        }
        shuffle(cards)
        shuffle(cards)

        index = 0
        for i in range(division[self._players][0]):
            Police.polices[0].add_card(cards[index])
            index += 1
        for i in range(division[self._players][1]):
            Police.polices[1].add_card(cards[index])
            index += 1
        for i in range(division[self._players][2]):
            Police.polices[2].add_card(cards[index])
            index += 1

        for i in range(self._players - 1):
            p = Player("Player " + str(i + 1), "")
            for j in range(division[self._players][i + 3]):
                p.add_card(cards[index])
                index += 1
예제 #8
0
def main():
    pygame.init()

    BACKGROUND_COLOR = (144, 201, 120)

    WINDOW_SIZE = (400, 300)
    screen = pygame.display.set_mode(WINDOW_SIZE)
    pygame.display.set_caption('text')

    clock = pygame.time.Clock()
    FPS = 60

    player = Player('hero', 50, 184, 1, 4, screen)
    moving_left = False
    moving_right = False

    run = True
    level = map.Map('test_scene.tmx', 'data/maps')
    level.convert_images()
    level.get_rect_tiles()
    while run:
        for event in pygame.event.get():
            if event.type == QUIT:
                run = False
            if event.type == pygame.KEYDOWN:
                if event.key == K_a:
                    moving_left = True
                if event.key == K_d:
                    moving_right = True
                if event.key == K_w and not player.in_air:
                    player.jump = True
            if event.type == pygame.KEYUP:
                if event.key == K_a:
                    moving_left = False
                if event.key == K_d:
                    moving_right = False
                if event.key == K_ESCAPE:
                    run = False
        screen.fill(BACKGROUND_COLOR)
        player.move(moving_left, moving_right, level.dict_tiles)
        level.render(screen)
        player.draw()
        pygame.display.update()
        clock.tick(FPS)
    pygame.quit()
    sys.exit()
예제 #9
0
 def __init__(self):
     pygame.init()
     self.__screen = pygame.display.set_mode([screen_width, screen_height])
     self.__clock = pygame.time.Clock()
     self.__player = Player(self.__screen, Vector(0, 0), 50, 50)
     self.__finish = Surface(self.__screen, Vector(2400, 200),
                             platform_width, platform_height)
     self.__platform = (Surface(self.__screen, Vector(20, 240),
                                platform_width, platform_height),
                        Surface(self.__screen, Vector(640, 300),
                                platform_width, platform_height),
                        Surface(self.__screen, Vector(940, 240),
                                platform_width, platform_height),
                        Surface(self.__screen, Vector(1340, 300),
                                platform_width, platform_height),
                        Surface(self.__screen, Vector(1640, 460),
                                platform_width, platform_height),
                        Surface(self.__screen, Vector(2000, 300),
                                platform_width, platform_height))
예제 #10
0
    def __init__(self, game):
        """ Initialise game run """
        self.game = game
        self.screen = self.game.screen
        self.settings = self.game.settings

        # create and draw grid
        self.grid = Grid(self)

        # create sprite groups
        self.characters_group = pygame.sprite.Group(
        )  # used for all characters (player and enemies)
        self.hp_counters_group = pygame.sprite.Group(
        )  # used for all HP counter (player and enemies)
        self.enemies_group = pygame.sprite.Group(
        )  # used for enemy characters only

        # create player
        self.player = Player(self, self.grid.tiles_dict["player_tile"][0])
        self.characters_group.add(self.player)
예제 #11
0
    def test_valid_move(self):

        valid_moves = [('w', 'You have moved up'),
                       ('a', 'You have moved left'),
                       ('s', 'You have moved down'),
                       ('d', 'You have moved right')]
        test_player = Player()
        test_player.randomize_initial_position(self.map_for_player_test)
        test_player.player_x = self.map_for_player_test.map_size[0] / 2
        test_player.player_y = self.map_for_player_test.map_size[1] / 2

        for move, move_message in valid_moves:

            with self.assertLogs(my_logger, level=logging.INFO) as log:

                result = test_player.make_move(
                    move, *self.map_for_player_test.map_size)
                self.assertTrue(result)

            self.assertEqual(log.output[0],
                             ''.join(["INFO:dungeon_logger:", move_message]))
예제 #12
0
    def start_game(self):
        self.mapmask = BitMask32(0x1)
        self.itemmask = BitMask32(0x2)
        self.map = Map("models/roem.bam")
        self.player = Player()
        self.load_sound()
        self.monsters = []
        self.monsters.append(Monster())

        self.text_a = OnscreenText(text="HENDRIK-JAN'S",
                                   fg=(0, 0, 0, 1),
                                   scale=0.06,
                                   font=self.font)
        self.text_a.set_pos(-0.3, 0, 0.3)
        self.set_text_style(self.text_a)

        self.text_b = OnscreenText(text="SYNDACTYLY",
                                   fg=(0, 0, 0, 1),
                                   scale=0.23,
                                   font=self.font)
        self.set_text_style(self.text_b)
        self.text_b.textNode.setShadow(0.02, 0.02)

        self.text_c = OnscreenText(
            text="listen closely (headphones essential)",
            fg=(1, 1, 1, 1),
            scale=0.04,
            font=self.font)
        self.text_c.set_pos(0, 0, 0. - 0.15)

        self.text_d = OnscreenText(text="hold left or right arrow to start",
                                   fg=(1, 1, 1, 1),
                                   scale=0.04,
                                   font=self.font)
        self.text_d.set_pos(0, 0, -0.1)
        self.text_shown = True

        self.taskMgr.add(self.update)
예제 #13
0
def main():

    choice = MainMenuPrompt()

    if choice == 'n':
        NewGame()
    elif choice == 'l':
        LoadGame()
    elif choice == 'e':
        Exit()
    else:
        print("Invalid Option!")

    hero = Player("John")

    newMap = Map(10, 10)
    for _ in range(3):
        newMap.addCharacter(Monster())
    newMap.addCharacter(hero)
    while True:
        os.system("clear")
        print(newMap)
        newMap.update()
예제 #14
0
                        pygame.draw.rect(window, (255, 250, 250),
                                         ((i) * blocksW,
                                          (j) * blocksH, blocksW, blocksH))
                    if mazeRender[i][j][1] == 1:
                        #Represents Bomb, Black
                        pygame.draw.rect(window, (0, 0, 0),
                                         ((i) * blocksW,
                                          (j) * blocksH, blocksW, blocksH))
                    if mazeRender[i][j][1] == 2:
                        #Represents explosion, orange
                        pygame.draw.rect(window, (255, 165, 0),
                                         ((i) * blocksW,
                                          (j) * blocksH, blocksW, blocksH))
                    if mazeRender[i][j][0] == 1:
                        #Represents player 1. blue
                        Bomberman = Player(i, j, blocksW - 10, blocksH - 10)
                        playerPos = Bomberman.getPos()

                        values = Bomberman.renderValues()
                        pygame.draw.rect(window, (0, 0, 255),
                                         (((values[0]) * blocksW) + 4,
                                          ((values[1]) * blocksH) + 4,
                                          values[2], values[3]))
                    if mazeRender[i][j][0] == 2:
                        #Represents player 2. Red
                        NumNPC -= 1
                        newNPC = NPC(i, j, blocksW - 10, blocksH - 10, 1,
                                     playerPos, menu, 0)

                        NPCs.append(newNPC)
                        values = NPCs[0].renderValues()
예제 #15
0
def main():
    """ Main function for the game. """
    pygame.init()

    # Set the width and height of the screen [width,height]

    screen = pygame.display.set_mode(
        [constants.screenWidth, constants.screenHeight])

    pygame.display.set_caption("Donkey Kong Country")

    # Create the player
    player = Player()

    # Create Sprite Group
    allSpritesList = pygame.sprite.Group()

    # Add player sprite to list of all sprites
    allSpritesList.add(player)

    player.rect.x = 350
    player.rect.y = 450

    # Loop until the user clicks the close button.
    done = False

    # Used to manage how fast the screen updates
    clock = pygame.time.Clock()

    # -------- Main Program Loop -----------
    while not done:
        # ALL EVENT PROCESSING SHOULD GO BELOW THIS COMMENT
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                done = True
            # If user presses a key down
            elif event.type == pygame.KEYDOWN:
                # Figure what key it was, adjust change_x
                if event.key == pygame.K_d:
                    player.goRight()
                if event.key == pygame.K_a:
                    player.goLeft()
                if event.key == pygame.K_w:
                    player.goUp()
                if event.key == pygame.K_s:
                    player.goDown()

            elif event.type == pygame.MOUSEBUTTONDOWN:
                mousePressed = pygame.mouse.get_pressed()
                if mousePressed[0]:
                    player.punch()
                elif mousePressed[2]:
                    player.spin()

            # If user lets up a key
            elif event.type == pygame.KEYUP:
                # If an arrow key, reset vector
                if event.key == pygame.K_d or event.key == pygame.K_a or event.key == pygame.K_w or event.key == pygame.K_s:
                    player.stop()

        # ALL EVENT PROCESSING SHOULD GO ABOVE THIS COMMENT

        # ALL GAME LOGIC SHOULD GO BELOW THIS COMMENT
        if player.rect.x >= 740:
            player.rect.x = 740
        elif player.rect.x <= 20:
            player.rect.x = 20

        allSpritesList.update()

        # ALL GAME LOGIC SHOULD GO ABOVE THIS COMMENT

        # ALL CODE TO DRAW SHOULD GO BELOW THIS COMMENT

        # First, clear the screen to white. Don't put other drawing commands
        # above this, or they will be erased with this command.
        screen.fill(constants.WHITE)
        allSpritesList.draw(screen)

        # ALL CODE TO DRAW SHOULD GO ABOVE THIS COMMENT

        # Go ahead and update the screen with what we've drawn.
        pygame.display.flip()

        # Limit to 60 frames per second
        clock.tick(60)

    # Close the window and quit.
    # If you forget this line, the program will 'hang'
    # on exit if running from IDLE.
    pygame.quit()
예제 #16
0
    def __init__(self, config=None):
        """Create a game world using the supplied configuration details.
        If no config specified, then use default_config world configuration.
        The game world has: title, rooms, characters, items, messages,
        and the success criteria.
        """
        # use default_config is none supplied
        if config == None:
            config = default_config

        # instance variables for a world
        self.title = config['title']
        self.rooms = {}
        self.items = {}
        self.characters = {}
        self.player = None
        self.messages = config['messages']
        self.success = config['success']

        # populate the world using the configuration details
        try:
            # configure rooms
            doing = "rooms"
            # room config has: (name, description, key_item, used_msg)*
            keyitems = []  # list of key items to config later
            for conf in config['rooms']:
                self.rooms[conf[0]] = Room(conf[0], conf[1])
                if conf[3] != None:  # key items to be set when have items
                    keyitems.append(
                        (conf[0], conf[2], conf[3]))  # (room, item, msg)

            # configure links between rooms
            doing = "links"
            # links config has: (room1, direction1, room2, direction2)*
            for conf in config['links']:
                self.rooms[conf[0]].link_room(self.rooms[conf[2]], conf[1],
                                              conf[3])
            # configure items
            doing = "items"
            # items config has: (name, description, location)
            player_items = []  # list of player items to config later
            for conf in config['items']:
                self.items[conf[0]] = Item(conf[0], conf[1])
                if conf[2] in self.rooms:  # place item in room
                    self.rooms[conf[2]].leave(self.items[conf[0]])
                else:  # item on character to add later
                    player_items.append((conf[0], conf[2]))

            # now configure key_items in rooms - has (room, item, msg)
            doing = "key_items"
            for conf in keyitems:
                self.rooms[conf[0]].set_key_item(self.items[conf[1]], conf[2])

            # configure characters (enemies, friends, player)
            doing = "enemies"
            # links config has: (name, description, conversation, location, weakness, defeat_msg)*
            for conf in config['enemies']:
                self.characters[conf[0]] = Enemy(conf[0], conf[1])
                self.characters[conf[0]].set_conversation(conf[2])
                self.characters[conf[0]].move_to(self.rooms[conf[3]])
                if conf[4] != None:
                    self.characters[conf[0]].set_weakness(
                        self.items[conf[4]], conf[5])

            doing = "friends"
            # friends config has: (name, description, conversation, location, desire, thank_msg)*
            for conf in config['friends']:
                self.characters[conf[0]] = Friend(conf[0], conf[1])
                self.characters[conf[0]].set_conversation(conf[2])
                self.characters[conf[0]].move_to(self.rooms[conf[3]])
                if conf[4] != None:
                    self.characters[conf[0]].set_desires(
                        self.items[conf[4]], conf[5])

            doing = "players"
            # players config has: (name, description, location)*
            num_players = 0
            for conf in config['players']:
                self.characters[conf[0]] = Player(conf[0], conf[1])
                self.characters[conf[0]].move_to(self.rooms[conf[2]])
                self.player = self.characters[conf[0]]
                num_players += 1
            if num_players != 1:
                print("You can only have 1 player character in the game!")

            # now configure player_items on characters - has (item, character)
            doing = "player_items"
            for conf in player_items:
                self.characters[conf[1]].add(self.items[conf[0]])

        except (IndexError, KeyError, ValueError) as msg:
            print("### Error: Incorrect format or values in " + doing +
                  " config: " + str(conf))
            print(str(msg))
            raise
예제 #17
0
while availableExits == 0:
   exitsList = freeExits(longestPath[index].exits)
   availableExits = len(exitsList)
   if availableExits == 0: index -= 1
if exitsList == None: print("FAIL")
else:
   selectedExit = random.randint(0, len(exitsList) - 1)
   selectedExit = exitsList[selectedExit]
   roomList["start"] = Room(startingDescription, "start")
   longestPath[index].exits[selectedExit] = roomList["start"]
   roomList["start"].exits[oppositeDirection(selectedExit)] = longestPath[index]
   longestPath.insert(index, roomList["start"])


#create player and monster
player = Player(roomList["start"])
#select monster
monsterIndex = random.randint(0, len(monsters) - 1)
monsterKeys = list(monsters)
monsterName = monsterKeys[monsterIndex]
monsterDescription = monsters[monsterName]
monster = Monster(player, roomList["monster"], monsterName, monsterDescription)

# shortestPath = []
# findShortestPath()

#game loop start


#game loop end
#reset room tracking for monster pathfinding
예제 #18
0
pygame.display.set_caption(const.TITLE_WINDOW)
# Dark Background
BG_DARK = pygame.image.load(const.BG_DARK).convert_alpha()

game_window = True
while game_window:  # Main Loop
    print('Loading...')
    # Init. Item list
    Item.instances_in_level = []
    # Init. UI Slots
    UI.list_slot_ui = []
    # Create level structure
    level = Level(const.LVL_LABYRINTH)
    level.gen_level()
    # Create Player
    player = Player(const.SPR_PLAYER, level, level.begin_position)
    # UI
    ui = UI(player, MAIN_WINDOW)
    ui.init_ui()
    # Create Guardian
    guard = Guardian(const.SPR_GUARD, level, level.end_position)
    # Items Creation
    create_item(Type.TUBE)
    create_item(Type.ETHER)
    create_item(Type.NEEDLE)
    print('Nb items in Level : ' + str(len(Item.instances_in_level)))
    print('...Ready')
    # Init Booleans
    end_pause = False
    game_loop = True
    while game_loop:  # Game Loop
예제 #19
0
from character import Player
from attack_kind import FireAttackKind, IceAttackKind
from monsters import FireMonster, IceMonster, StoneMonster, KungfuMonster, ArrowMonster

fm = FireMonster()
im = IceMonster()
sm = StoneMonster()
kfm = KungfuMonster()

monsters = []
monsters.extend((fm, im, sm, kfm))

# Dependency Injection : DI  --> main.py 에서
player = Player('john', 120, 20, FireAttackKind(), IceAttackKind())

for mon in monsters:
    player.attack(mon, 'Fire')

for mon in monsters:
    print(mon.get_attack_kind())
    mon.attack(player, mon.get_attack_kind())

new_mon = ArrowMonster()

print(player)
예제 #20
0
    escape_call = Escape()

    while True:
        pygame.time.Clock().tick(40)
        pos = pygame.mouse.get_pos()
        if rect.collidepoint(pos):
            screen.blit(cont_go, rect)
        else:
            screen.blit(cont_no, rect)
        for event in pygame.event.get():
            if event.type == QUIT:
                pygame.quit()
                sys.exit()

            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE:
                    escape_call.escape_menu(screen)
                    break

            elif event.type == MOUSEBUTTONDOWN:
                if rect.collidepoint(pos):
                    return
        pygame.display.update()


if __name__ == '__main__':
    pygame.display.init()
    screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
    player = Player()
    repair(screen, player, None)
예제 #21
0
from catacomb_setup import commandsHelp
from character import Player

# Make a new player object that is currently in the 'outside' room.
global player
player = Player(room['outside'])

gameRunning = True


def quitGame():
    print('Quitting Game')
    global gameRunning
    gameRunning = False


####################
# Command functions
###################


def parseInput(*args):
    args = args[0]
    command1 = args[0].lower()
    if command1 in "nesw": move(player, command1)
    elif command1 in {"look", "l"}: look(player, args)
    elif command1 in {
            "score",
    }: player.getScore()
    elif command1 in {"pickup", "p"}: player.pickupItem(args)
    elif command1 in {"drop", "d"}: player.dropItem(args)
예제 #22
0
from matrix import Matrix
from character import Player
from direction import Direction

#define the dimension of the Terminal
rows, column = 23, 40

matrix = Matrix(rows, column, default_character='')
player = Player("&")
direction = Direction()


class Menu(object):
    def __init__(self):
        self.display = '''
        ----* TERMINAL GAME *----
                Press:
        'U'  For Move Your Player Up
        'D'  For Move Your Player Down
        'L'  For Move Your Player Left
        'R'  For Move Your Player Right
        'Q'  For Quitting
        '''

    @property
    def choice(self):
        choice_dict = {
            "U": direction.Up,
            "D": direction.Down,
            "L": direction.Left,
            "R": direction.Rigth
    def __init__(self):

        self.dungeon_map = DungeonMap()
        self.player_map = PlayerMap()
        self.player = Player()
예제 #24
0
 def add_player(self, grid_x, grid_y, grid_scale, player=None):
     if player:
         self.player = player
     else:
         self.player = Player(grid_x, grid_y, grid_scale)
     self.add_widget(self.player)
예제 #25
0
def startGame():
    global music
    pygame.init()  # Инициация PyGame, обязательная строчка
    pygame.mixer.music.load("config/battlesong.mp3")
    pygame.mixer.music.set_volume(.1)
    if music:
        pygame.mixer.music.play()

    level = [
        "------------------------------------------------------------",
        "-                                                          -",
        "-                                                          -",
        "-  ---                                                ---- -",
        "-                            -                             -",
        "-                            -                             -",
        "--                  ---      -       ----                  -",
        "-                            --                 -          -",
        "-                            -                             -",
        "-                            -                             -",
        "-          ----                                        -   -",
        "-                                                      -  --",
        "-                            -                         -   -",
        "-                            -                         -   -",
        "-                     --     -                     -----   -",
        "-       ----                 -                             -",
        "-                            -        -----                -",
        "-                                                          -",
        "-                   -                                     --",
        "-                                           -              -",
        "-                            -                 -----       -",
        "-          ---------         -                             -",
        "-                            -                           ---",
        "--                          --                             -",
        "-                            -    ---                      -",
        "-                                                          -",
        "-                                           ------         -",
        "-                   ---                                    -",
        "-   -------                  -                             -",
        "-                       ---  -       ----                  -",
        "-                            -                             -",
        "------------------------------------------------------------",
    ]

    # Стартовая настройка фона
    screen = pygame.display.set_mode(DISPLAY)  # Создаем окошко
    pygame.display.set_caption("Sheriff Bob")  # Пишем в шапку
    bg = Surface((WIN_WIDTH, WIN_HEIGHT))  # Создание видимой поверхности
    bg.blit(pygame.image.load("images/background.jpeg"), (0, 0))

    # Начальные настройки игры
    up = up1 = False
    left = right = left1 = right1 = False  # по умолчанию — стоим
    entities = pygame.sprite.Group()  # Все объекты
    paddles = []  # то, во что мы будем врезаться или опираться
    coins = []
    num_of_coins = 10
    # Создание персонажей
    hero = Player(55, 55, "images/first_character")
    hero2 = Player(1865, 55, "images/second_character")
    level = Level(level)
    # Добавление персонажей в группу entities для последующей их прорисовки
    entities.add(hero)
    entities.add(hero2)

    # Создание таймера
    timer = pygame.time.Clock()

    # Расположение монет
    level.createCoin(num_of_coins)

    # Создание уровня
    level.update(entities, paddles, coins)

    start = t.time()
    # Основной цикл программы
    while True:

        # Настройка частоты кадров
        timer.tick(60)
        game_time = t.time() - start
        # Обрабатываем события
        for e in pygame.event.get():
            if e.type == QUIT:
                raise SystemExit("QUIT")

            if e.type == KEYDOWN and e.key == K_p:
                pauseTheGame(screen)

            if e.type == KEYDOWN and e.key == K_LEFT:
                left = True
            if e.type == KEYDOWN and e.key == K_RIGHT:
                right = True

            if e.type == KEYUP and e.key == K_RIGHT:
                right = False
            if e.type == KEYUP and e.key == K_LEFT:
                left = False
            if e.type == KEYDOWN and e.key == K_UP:
                up = True
            if e.type == KEYUP and e.key == K_UP:
                up = False

            if e.type == KEYDOWN and e.key == K_a:
                left1 = True
            if e.type == KEYDOWN and e.key == K_d:
                right1 = True

            if e.type == KEYUP and e.key == K_d:
                right1 = False
            if e.type == KEYUP and e.key == K_a:
                left1 = False
            if e.type == KEYDOWN and e.key == K_w:
                up1 = True
            if e.type == KEYUP and e.key == K_w:
                up1 = False

        # Главная логика догонялок

        hero2.getCoin(coins)
        hero.catch(hero2, screen, game_time, entities)

        # Обновление спрайтов
        screen.blit(bg, (0, 0))
        hero.update(left1, right1, up1, paddles, coins)
        hero2.update(left, right, up, paddles, coins)
        entities.draw(screen)  # отображение
        printText(screen,
                  "TIME: " + ("%.2f" % game_time),
                  870,
                  -8,
                  font_color=pygame.Color("#2d3436"),
                  font_size=30)
        pygame.display.update()  # обновление и вывод всех изменений на экран
예제 #26
0
    def __init__(self):
        # Load info from .json file
        data = self._load_data()

        if data is None:
            raise RuntimeError

        # Load image of the game
        self.assets = self._load_assets(data["List of sprites"])
        if self.assets is None:
            raise RuntimeError

        maze = data["Maze"]
        # Initialize all sprite for maze background
        self.map = {}
        for index, val in enumerate(maze):
            pos = (index % constant.MAZE_SIZE, index // constant.MAZE_SIZE)
            if not val:
                self.map[pos] = Cell(self.assets["wall"], pos)
            else:
                self.map[pos] = Cell(self.assets["floor"], pos)

        # Initialize Guardian
        index = maze.index("G")
        self.guardian = Character(
            self.assets["guardian"],
            (index % constant.MAZE_SIZE, index // constant.MAZE_SIZE),
        )

        # Initialize player
        index = maze.index("P")
        self.player = Player(
            self.assets["player"],
            (index % constant.MAZE_SIZE, index // constant.MAZE_SIZE),
        )

        # Initialize items in random position
        self.items = []
        for i in range(3):
            self.items.append(
                Cell(self.assets[constant.ITEMS[i]], self._random_pos())
            )

        # Sprite group for display
        self.all_sprites = pygame.sprite.Group()

        for sprite in self.map.values():
            self.all_sprites.add(sprite)
        for sprite in self.items:
            self.all_sprites.add(sprite)
        self.all_sprites.add(self.guardian)
        self.all_sprites.add(self.player)

        # Create Message and Cell to display
        # if player collect enough items to fight guardian

        self.not_ready_message = Message(
            (
                constant.MAZE_SIZE * constant.SPRITE_W * 3 // 4,
                constant.MAZE_SIZE * constant.SPRITE_H
                + constant.SPRITE_H // 2,
            ),
            "Mac Gywer not Ready, Be Carefull",
            constant.SMALL_SIZE,
            constant.BIG_FONT,
            constant.RED,
        )

        self.ready_message = Message(
            (
                constant.MAZE_SIZE * constant.SPRITE_W * 4 // 5,
                constant.MAZE_SIZE * constant.SPRITE_H
                + constant.SPRITE_H // 2,
            ),
            "Ready to Fight",
            constant.SMALL_SIZE,
            constant.BIG_FONT,
            constant.GREEN,
        )

        self.arrow = Cell(
            self.assets[constant.ARROW_NAME],
            (len(constant.ITEMS) + 1, constant.MAZE_SIZE),
        )
        self.weapon = Cell(
            self.assets[constant.WEAPON],
            (
                len(constant.ITEMS) + constant.ARROW_SIZE + 1,
                constant.MAZE_SIZE,
            ),
        )
        self.weapon_sprites = pygame.sprite.Group()
        self.weapon_sprites.add(self.arrow)
        self.weapon_sprites.add(self.weapon)
예제 #27
0
    def setup(self):
        self.map = Map()
        self.all_sprites_list = arcade.SpriteList()
        self.wall_list = arcade.SpriteList()
        self.stair_list = arcade.SpriteList()
        self.gate_list = arcade.SpriteList()

        draw_carrot = [[2, 2], [5, 14], [13, 2], [15, 6], [17, 10]]
        for x in draw_carrot:
            _center_x = self.map.convertToCenter([x[0]])
            _center_y = self.map.convertToCenter([x[1]])
            self.carrot_list = []
            carrot = Carrot(_center_x, _center_y)
            self.carrot_list.append({
                "obj": carrot,
                "x": _center_x,
                "y": _center_y
            })
            self.all_sprites_list.append(carrot)
            self.add_map(_center_x, _center_y, carrot.width, carrot.height,
                         "carrot", carrot)

        #base floor
        for x in range(24, 1152, 48):
            wall = arcade.Sprite("images/tileset/grassCenter.png",
                                 1)  #128 to 64x64
            wall.center_x = x
            wall.center_y = 24
            self.all_sprites_list.append(wall)
            self.wall_list.append(wall)
            self.add_map(x, 24, wall.width, wall.height, "floor", wall)

        for x in range(24, 1152, 48):
            wall = arcade.Sprite("images/tileset/grassMid.png",
                                 1)  #128 to 64x64
            wall.center_x = x
            wall.center_y = 72
            self.all_sprites_list.append(wall)
            self.wall_list.append(wall)
            self.add_map(x, 72, wall.width, wall.height, "floor", wall)

        #gate
        #base floor
        stair = arcade.Sprite("images/tileset/gate.png", 1)
        stair.center_x = 240
        stair.center_y = 168
        self.all_sprites_list.append(stair)
        self.stair_list.append(stair)
        self.add_map(240, 168, stair.width, stair.height, "gate", stair)
        block = self.map.convertToBlock(stair.center_x, stair.center_y,
                                        stair.width, stair.height)
        self.map.gate_list2.append({"x": block["x"], "y": block["y"]})

        #second floor
        stair = arcade.Sprite("images/tileset/gate.png", 1)
        stair.center_x = 48
        stair.center_y = 360
        self.all_sprites_list.append(stair)
        self.stair_list.append(stair)
        self.add_map(48, 360, stair.width, stair.height, "gate", stair)
        block = self.map.convertToBlock(stair.center_x, stair.center_y,
                                        stair.width, stair.height)
        self.map.gate_list2.append({"x": block["x"], "y": block["y"]})

        #third floor
        stair = arcade.Sprite("images/tileset/gate.png", 1)
        stair.center_x = 144
        stair.center_y = 552
        self.all_sprites_list.append(stair)
        self.stair_list.append(stair)
        self.add_map(144, 552, stair.width, stair.height, "gate", stair)
        block = self.map.convertToBlock(stair.center_x, stair.center_y,
                                        stair.width, stair.height)
        self.map.gate_list2.append({"x": block["x"], "y": block["y"]})

        #fourth floor
        stair = arcade.Sprite("images/tileset/gate.png", 1)
        stair.center_x = 48
        stair.center_y = 744
        self.all_sprites_list.append(stair)
        self.stair_list.append(stair)
        self.add_map(48, 744, stair.width, stair.height, "gate", stair)
        block = self.map.convertToBlock(stair.center_x, stair.center_y,
                                        stair.width, stair.height)
        self.map.gate_list2.append({"x": block["x"], "y": block["y"]})

        #upper pedan
        for x in range(24, 1152, 48):
            wall = arcade.Sprite("images/tileset/stoneMid.png", 1)
            wall.center_x = x
            wall.center_y = 840
            self.all_sprites_list.append(wall)
            self.wall_list.append(wall)
            self.add_map(x, 840, wall.width, wall.height, "floor", wall)

        #first floor
        #-----------------------------------------------------------
        for x in range(24, 288, 48):
            wall = arcade.Sprite("images/tileset/brick.png",
                                 1)  #64x64 to 32x32
            wall.center_x = x
            wall.center_y = 264
            self.all_sprites_list.append(wall)
            self.wall_list.append(wall)
            self.add_map(x, 264, wall.width, wall.height, "floor", wall)

        stair = arcade.Sprite("images/tileset/stair_left.png", 1)
        stair.center_x = 408
        stair.center_y = 120
        self.all_sprites_list.append(stair)
        self.stair_list.append(stair)
        self.add_map(408, 120, stair.width, stair.height, "stair", stair)

        stair = arcade.Sprite("images/tileset/stair_left.png", 1)
        stair.center_x = 456
        stair.center_y = 168
        self.all_sprites_list.append(stair)
        self.stair_list.append(stair)
        self.add_map(456, 168, stair.width, stair.height, "stair", stair)

        stair = arcade.Sprite("images/tileset/stair_left.png", 1)
        stair.center_x = 504
        stair.center_y = 216
        self.all_sprites_list.append(stair)
        self.stair_list.append(stair)
        self.add_map(504, 216, stair.width, stair.height, "stair", stair)

        for x in range(552, 816, 48):
            wall = arcade.Sprite("images/tileset/brick.png",
                                 1)  #64x64 to 32x32
            wall.center_x = x
            wall.center_y = 264
            self.all_sprites_list.append(wall)
            self.wall_list.append(wall)
            self.add_map(x, 264, wall.width, wall.height, "floor", wall)

        stair = arcade.Sprite("images/tileset/stair_right.png", 1)
        stair.center_x = 936
        stair.center_y = 120
        self.all_sprites_list.append(stair)
        self.stair_list.append(stair)
        self.add_map(936, 120, stair.width, stair.height, "stair", stair)

        stair = arcade.Sprite("images/tileset/stair_right.png", 1)
        stair.center_x = 888
        stair.center_y = 168
        self.all_sprites_list.append(stair)
        self.stair_list.append(stair)
        self.add_map(888, 168, stair.width, stair.height, "stair", stair)

        stair = arcade.Sprite("images/tileset/stair_right.png", 1)
        stair.center_x = 840
        stair.center_y = 216
        self.all_sprites_list.append(stair)
        self.stair_list.append(stair)
        self.add_map(840, 216, stair.width, stair.height, "stair", stair)

        #----------------------- second floor ---------------------------------------
        for x in range(24, 192, 48):
            wall = arcade.Sprite("images/tileset/brick.png",
                                 1)  #64x64 to 32x32
            wall.center_x = x
            wall.center_y = 456
            self.all_sprites_list.append(wall)
            self.wall_list.append(wall)
            self.add_map(x, 456, wall.width, wall.height, "floor", wall)

        stair = arcade.Sprite("images/tileset/stair_left.png", 1)
        stair.center_x = 408
        stair.center_y = 408
        self.all_sprites_list.append(stair)
        self.stair_list.append(stair)
        self.add_map(408, 408, stair.width, stair.height, "stair", stair)

        stair = arcade.Sprite("images/tileset/stair_left.png", 1)
        stair.center_x = 312
        stair.center_y = 312
        self.all_sprites_list.append(stair)
        self.stair_list.append(stair)
        self.add_map(312, 312, stair.width, stair.height, "stair", stair)

        stair = arcade.Sprite("images/tileset/stair_left.png", 1)
        stair.center_x = 360
        stair.center_y = 360
        self.all_sprites_list.append(stair)
        self.stair_list.append(stair)
        self.add_map(360, 360, stair.width, stair.height, "stair", stair)

        for x in range(456, 1056, 48):
            wall = arcade.Sprite("images/tileset/brick.png", 1)  #32x32
            wall.center_x = x
            wall.center_y = 456
            self.all_sprites_list.append(wall)
            self.wall_list.append(wall)
            self.add_map(x, 456, wall.width, wall.height, "floor", wall)

        #--------------------------------- third floor -----------------------------------------------------
        for x in range(24, 384, 48):
            wall = arcade.Sprite("images/tileset/brick.png",
                                 1)  #64x64 to 32x32
            wall.center_x = x
            wall.center_y = 648
            self.all_sprites_list.append(wall)
            self.wall_list.append(wall)
            self.add_map(x, 648, wall.width, wall.height, "floor", wall)

        stair = arcade.Sprite("images/tileset/stair_left.png", 1)
        stair.center_x = 696
        stair.center_y = 600
        self.all_sprites_list.append(stair)
        self.stair_list.append(stair)
        self.add_map(696, 600, stair.width, stair.height, "stair", stair)

        stair = arcade.Sprite("images/tileset/stair_left.png", 1)
        stair.center_x = 600
        stair.center_y = 504
        self.all_sprites_list.append(stair)
        self.stair_list.append(stair)
        self.add_map(600, 504, stair.width, stair.height, "stair", stair)

        stair = arcade.Sprite("images/tileset/stair_left.png", 1)
        stair.center_x = 648
        stair.center_y = 552
        self.all_sprites_list.append(stair)
        self.stair_list.append(stair)
        self.add_map(648, 552, stair.width, stair.height, "stair", stair)

        for x in range(744, 1056, 48):
            wall = arcade.Sprite("images/tileset/brick.png", 1)  #32x32
            wall.center_x = x
            wall.center_y = 648
            self.all_sprites_list.append(wall)
            self.wall_list.append(wall)
            self.add_map(x, 648, wall.width, wall.height, "floor", wall)

        self.player_sprite = Player(self)
        self.player_sprite.center_x = 48
        self.player_sprite.center_y = 144
        #self.player_sprite.center_y = SCREEN_HEIGHT / 2
        self.add_map(self.player_sprite.center_x, self.player_sprite.center_y,
                     self.player_sprite.width, self.player_sprite.height,
                     "player", self.player_sprite)
        self.all_sprites_list.append(self.player_sprite)

        self.enemy_sprite = Enemy(self)
        self.enemy_sprite.center_x = 144
        self.enemy_sprite.center_y = 144
        #self.player_sprite.center_y = SCREEN_HEIGHT / 2
        self.add_map(self.enemy_sprite.center_x, self.enemy_sprite.center_y,
                     self.enemy_sprite.width, self.enemy_sprite.height,
                     "enemy", self.enemy_sprite)
        self.all_sprites_list.append(self.enemy_sprite)
예제 #28
0
# main.py
from world import Spot
from character import Player, Enemy


alkirasc = Spot('Alkira Secondary College', 'A lot of kids spend their lives here.')
daveshome = Spot("Dave's Home", "It is a dark house and a bad smell comes out from it.")
alkirasc.connect(daveshome, 'south')
daveshome.connect(alkirasc, 'north')

#player_name = input('Name of the Great Adventure please: ')
player_name = 'Jeremy'
player = Player(player_name, alkirasc)

dave = Enemy('Dave', 'A smelly zombie.', 'garlic')
dave.conversation = 'I like to eat humans.'
steve = Enemy('Steve', 'A shifty ghost.', 'cake')
steve.conversation = "This doesn't look good, dude."
daveshome.add_characters(dave)
daveshome.add_characters(steve)


def who(command):
    commands = command.split()
    if len(commands) == 1:
        return player.current_spot.characters[0]
    elif len(commands) == 2:
        for character in player.current_spot.characters:
            if character.name.lower() == commands[1].lower():
                return character
예제 #29
0
    def test_invalid_move(self):

        test_player = Player()
        test_player.randomize_initial_position(self.map_for_player_test)
        self.assertFalse(result)
예제 #30
0
파일: main.py 프로젝트: Naxaes/pacman
def main():
    screen = settings.SCREEN
    clock = settings.CLOCK
    fps = settings.FPS

    tile_map = TileMap()
    add_points(tile_map)

    player = Player(position=settings.SPAWNS["pacman"])
    ghosts = pygame.sprite.Group(
        Ghost(position=settings.SPAWNS[name])
        for name in ["blinky", "inky", "pinky", "clyde"])
    single_text = pygame.sprite.GroupSingle()
    setting_text = pygame.sprite.GroupSingle()
    setting_text_pos = (screen.get_width() // 2 - 9, 12)
    font = pygame.font.SysFont(None, 32)

    # Starting with scatter and alternating in following interval (in secs):
    # Level 1: 7, 20, 7, 20, 5, 20, 5, inf;
    # Level 2-4: 7, 20, 7, 20, 5, 1033, 1 / 60, inf;
    # Level 5+: 5, 20, 5, 20, 5, 1037, 1 / 60, inf;
    normal_mode = Mode(["scatter", "chase"],
                       [7, 20, 7, 20, 5, 20, 5, math.inf])
    frighten_mode = Mode(["frightened", "unfrightened"], [5, 3], 1)
    mode = "scatter"

    score = 0
    speed_factor = 1.2  # How fast to run the game.
    time = 0
    start_timer = 2
    paused = False
    started = False
    music = False
    grid = False
    see_target = False
    while 1:
        dt = (clock.tick(fps) / 1000
              )  # "dt" is the time between each loop in seconds.
        time += dt if started and not paused and not player.dead else 0
        dt *= speed_factor  # "time" shouldn't be affected, the rest should.

        for event in pygame.event.get():
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE:
                    quit()
                elif event.key == pygame.K_f:
                    fps = (fps % 120) + 20
                    setting_text.add(
                        text.FadingText("FPS: {}".format(fps),
                                        fade_out=1,
                                        pos=setting_text_pos,
                                        origin="midtop",
                                        font=font,
                                        color=(255, 255, 255)))
                elif event.key == pygame.K_r or event.key == pygame.K_SPACE:
                    for tile in tile_map.tile.values():
                        for ghost in ghosts:
                            if ghost in tile.content:
                                tile.remove_content(ghost)
                    Ghost.ID = 0
                    player = Player(position=settings.SPAWNS["pacman"])
                    ghosts = pygame.sprite.Group(
                        Ghost(position=settings.SPAWNS[name])
                        for name in ["blinky", "inky", "pinky", "clyde"])
                    start_timer = 2
                    started = False
                elif event.key == pygame.K_p:
                    pygame.mixer.music.unpause(
                    ) if paused else pygame.mixer.music.pause()
                    paused = not paused
                    temp = "Paused" if paused else "Unpaused"
                    setting_text.add(
                        text.FadingText(temp,
                                        fade_out=1,
                                        pos=setting_text_pos,
                                        origin="midtop",
                                        font=font,
                                        color=(255, 255, 255)))
                elif event.key == pygame.K_1:
                    change_music(track=0)
                    setting_text.add(
                        text.FadingText(settings.MUSIC[0][29:46],
                                        fade_out=1,
                                        pos=setting_text_pos,
                                        origin="midtop",
                                        font=font,
                                        color=(255, 255, 255)))
                elif event.key == pygame.K_2:
                    change_music(track=1)
                    setting_text.add(
                        text.FadingText(settings.MUSIC[1][29:48],
                                        fade_out=1,
                                        pos=setting_text_pos,
                                        origin="midtop",
                                        font=font,
                                        color=(255, 255, 255)))
                elif event.key == pygame.K_3:
                    pygame.mixer.music.stop()
                    setting_text.add(
                        text.FadingText("Paused music",
                                        fade_out=1,
                                        pos=setting_text_pos,
                                        origin="midtop",
                                        font=font,
                                        color=(255, 255, 255)))
                elif event.key == pygame.K_g:
                    grid = not grid
                    setting_text.add(
                        text.FadingText("Grid",
                                        fade_out=1,
                                        pos=setting_text_pos,
                                        origin="midtop",
                                        font=font,
                                        color=(255, 255, 255)))
                elif event.key == pygame.K_t:
                    see_target = not see_target
                    setting_text.add(
                        text.FadingText("Target",
                                        fade_out=1,
                                        pos=setting_text_pos,
                                        origin="midtop",
                                        font=font,
                                        color=(255, 255, 255)))
                elif event.key == pygame.K_x:
                    speed_factor = (speed_factor +
                                    0.1) % 2.05 if 2 > speed_factor >= 1 else 1
                    setting_text.add(
                        text.FadingText("Speed: {0:.1f}".format(speed_factor),
                                        fade_out=1,
                                        pos=setting_text_pos,
                                        origin="midtop",
                                        font=font,
                                        color=(255, 255, 255)))
            elif event.type == pygame.QUIT:
                quit()

        if not paused and started and not player.dead:  # Do game updates and logic checks
            if score >= 60 and not Ghost.SPAWN[3]:  # 60
                Ghost.SPAWN[3] = True
                print("Clyde's coming out!")
            if score >= 30 and not Ghost.SPAWN[1]:  # 30
                Ghost.SPAWN[1] = True
                print("Inky's coming out!")

            if mode in ("frightened", "unfrightened"):
                mode = frighten_mode.update(dt)
                if mode is not None:
                    Ghost.MODE = Ghost.MODES[mode]
                else:
                    frighten_mode = Mode(["frightened", "unfrightened"],
                                         [5, 3], 1)
                    change_unfrightened(ghosts)
            else:
                mode = normal_mode.update(dt)
                Ghost.MODE = Ghost.MODES[mode]
            player.update(tile_map, dt)
            ghosts.update(tile_map, dt, player, ghosts)
            Point.instances.update(dt)
            mode, score = collision(player, ghosts, tile_map, single_text,
                                    mode, score, clock)
            single_text.update(dt)

        elif player.dead:
            player.animate(dt)

        tile_map.draw(screen)
        text.put_text(screen,
                      "Score: {0}".format(score),
                      pos=(-128, 36),
                      origin="bottomleft")
        text.put_text(screen,
                      "Time: {0:.1f}".format(time),
                      pos=(16, 36),
                      origin="bottomleft")
        setting_text.update(dt)
        setting_text.draw(screen)
        Point.instances.draw(screen)
        if grid:
            draw_grid(screen, tile_map)
        if see_target:
            show(ghosts, target=True, house=True)
        if not player.dead:
            ghosts.draw(screen)
        single_text.draw(screen)
        screen.blit(player.image, player.rect)
        if not started:
            start_timer -= dt
            text.put_text(screen,
                          "READY!", (224, 328),
                          color=(255, 255, 0),
                          font=pygame.font.SysFont(None, 32, 1, 1))
            if not music:
                change_music(track=0)
                music = True
            if start_timer <= 0:
                start_timer = 2
                started = True
        if len(Point.instances) <= 0:
            text.put_text(screen, "WON!", settings.SPAWNS["pacman"])
            pygame.display.update()
            # delay(2, clock)  # Will delay every update.
        pygame.display.update()