コード例 #1
0
ファイル: pyPlatformer.py プロジェクト: kburts/pygame-gamemvp
    def main(self, screen):
        clock = pygame.time.Clock()

        background = pygame.image.load('background.png')

        self.tilemap = tmx.load('map.tmx', screen.get_size())

        self.sprites = tmx.SpriteLayer()
        start_cell = self.tilemap.layers['triggers'].find('player')[0]
        self.player = Player((start_cell.px, start_cell.py), self.sprites)
        self.tilemap.layers.append(self.sprites)

        while 1:
            dt = clock.tick(30)

            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    return
                if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
                    return

            self.tilemap.update(dt / 1000., self)
            screen.blit(background, (0, 0))
            self.tilemap.draw(screen)
            pygame.display.flip()
コード例 #2
0
ファイル: bunnymain.py プロジェクト: Cardboard/bunny_quest
    def main(self):
	screen = pygame.display.set_mode((256,224))
	pygame.display.set_caption('bunny_quest')
	clock = pygame.time.Clock()
	fps = 60

	pygame.mixer.init()
	pygame.mixer.music.load(os.path.join('music', 'music.ogg'))
	pygame.mixer.music.play()

	self.tilemap = tmx.load('level1.tmx', screen.get_size())

	self.sprites = tmx.SpriteLayer()
	player_start = self.tilemap.layers['triggers'].find('player')[0]
	self.player = Player((player_start.px, player_start.py), self.sprites)
	self.bunny = Bunny(self.sprites)
	self.tilemap.layers.append(self.sprites)

	while 1:
	    dt = clock.tick(fps)
	    dt = dt
	    
	    for event in pygame.event.get():
		if event.type == pygame.QUIT:
		    return
		if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
		    return

	    self.tilemap.update(dt, self)
	    screen.fill((255,255,255))
	    self.tilemap.draw(screen)
	    pygame.display.flip()
コード例 #3
0
    def main(self, screen):
        clock = pygame.time.Clock()
        self.jump = pygame.mixer.Sound('jump.wav')
        self.shoot = pygame.mixer.Sound('shoot.wav')
        self.explosion = pygame.mixer.Sound('explosion.wav')

        self.tilemap = tmx.load('map.tmx', screen.get_size())

        self.sprites = tmx.SpriteLayer()
        start_cell = self.tilemap.layers['triggers'].find('player')[0]
        self.player = Player((start_cell.px, start_cell.py), self.sprites)
        self.tilemap.layers.append(self.sprites)

        self.enemies = tmx.SpriteLayer()
        for enemy in self.tilemap.layers['triggers'].find('enemy'):
            Enemy((enemy.px, enemy.py), self.enemies)
        self.tilemap.layers.append(self.enemies)

        while True:
            dt = clock.tick(30)
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    return
                if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
                    return

            self.tilemap.update(dt / 1000., self)
            screen.fill((200, 200, 200))
            # screen.blit(background, (0, 0))
            self.tilemap.draw(screen)
            pygame.display.flip()

            if self.player.is_dead:
                print "YOU DIED"
                return
コード例 #4
0
ファイル: engine.py プロジェクト: GamesCreatorsClub/GCC
def LoadMap(mapName):
    global tilemap, playerPos, tilesByName, autoAnimationObjects, animationObjects, objectLayer

    tilemap = tmx.load(mapName, screen.get_size())

    objectLayer = tilemap.layers["objects"]
    startObject = objectLayer.find_by_name("start_position")
    if not startObject == None:
        objectLayer.objects.remove(startObject)
        setupPlayer((startObject.px, startObject.py))
    else:
        setupPlayer((tilemap.px_width / 2, tilemap.px_height / 2))

    tilemap.set_focus(playerPos.x, playerPos.y)

    if "OnCreate" in tilemap.properties:
        onCreate = tilemap.properties["OnCreate"]
        game.execute(onCreate)

    processNames()

    processOnCreate(tilemap.layers["objects"])
    processOnCreate(tilemap.layers["ground1"])
    processOnCreate(tilemap.layers["ground2"])
    processOnCreate(tilemap.layers["overlay"])

    autoAnimationObjects = tilemap.layers["objects"].find("Animate")
    animationObjects = tilemap.layers["objects"].find("OnAnimate")
コード例 #5
0
    def main(self, screen):
        clock = pygame.time.Clock()

        background = pygame.image.load("background.png")

        self.tilemap = tmx.load("map-enemies.tmx", screen.get_size())

        self.sprites = tmx.SpriteLayer()
        start_cell = self.tilemap.layers["triggers"].find("player")[0]
        self.player = Player((start_cell.px, start_cell.py), self.sprites)
        self.tilemap.layers.append(self.sprites)

        self.enemies = tmx.SpriteLayer()
        for enemy in self.tilemap.layers["triggers"].find("enemy"):
            Enemy((enemy.px, enemy.py), self.enemies)
        self.tilemap.layers.append(self.enemies)

        while 1:
            dt = clock.tick(30)

            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    return
                if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
                    return

            self.tilemap.update(dt / 1000.0, self)
            screen.blit(background, (0, 0))
            self.tilemap.draw(screen)
            pygame.display.flip()

            if self.player.is_dead:
                print "YOU DIED"
                return
コード例 #6
0
    def initArea(self, mapFile):  # initArea
        # *** *** ***

        self.tilemap = tmx.load(mapFile, screen.get_size())
        print(type(self.tilemap.layers))
        self.players = tmx.SpriteLayer()
        self.objects = tmx.SpriteLayer()
        self.sprites = []
        # Initializing other animated sprites
        try:
            for cell in self.tilemap.layers['sprites'].find('src'):
                SpriteLoop((cell.px, cell.py), cell, self.objects)
            for cell in self.tilemap.layers['npcSprites'].find('src'):
                self.sprites.append(
                    npcSprite((cell.px, cell.py), cell, 'down', self.objects))
                print(cell['src'])
                print('above is the src')

        # In case there is no sprite layer for the current map
        except KeyError:
            pass
        else:
            self.tilemap.layers.append(self.objects)
        # Initializing player sprite
        startCell = self.tilemap.layers['triggers'].find('playerStart')[0]
        self.player = Player((startCell.px, startCell.py),
                             startCell['playerStart'], self.players)
        self.tilemap.layers.append(self.players)
        self.tilemap.set_focus(self.player.rect.x, self.player.rect.y)
コード例 #7
0
    def main(self):
        screen = pygame.display.set_mode((256, 224))
        pygame.display.set_caption('bunny_quest')
        clock = pygame.time.Clock()
        fps = 60

        pygame.mixer.init()
        pygame.mixer.music.load(os.path.join('music', 'music.ogg'))
        pygame.mixer.music.play()

        self.tilemap = tmx.load('level1.tmx', screen.get_size())

        self.sprites = tmx.SpriteLayer()
        player_start = self.tilemap.layers['triggers'].find('player')[0]
        self.player = Player((player_start.px, player_start.py), self.sprites)
        self.bunny = Bunny(self.sprites)
        self.tilemap.layers.append(self.sprites)

        while 1:
            dt = clock.tick(fps)
            dt = dt

            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    return
                if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
                    return

            self.tilemap.update(dt, self)
            screen.fill((255, 255, 255))
            self.tilemap.draw(screen)
            pygame.display.flip()
コード例 #8
0
def LoadMap(mapName):
    global tilemap, playerPos, tilesByName, autoAnimationObjects, animationObjects, objectLayer

    tilemap = tmx.load(mapName, screen.get_size())

    objectLayer = tilemap.layers["objects"]
    startObject = objectLayer.find_by_name("start_position")
    if not startObject == None:
        objectLayer.objects.remove(startObject)
        setupPlayer((startObject.px, startObject.py))
    else:
        setupPlayer((tilemap.px_width / 2, tilemap.px_height / 2))

    tilemap.set_focus(playerPos.x, playerPos.y)

    if "OnCreate" in tilemap.properties:
        onCreate = tilemap.properties["OnCreate"]
        game.execute(onCreate)

    processNames()

    processOnCreate(tilemap.layers["objects"])
    processOnCreate(tilemap.layers["ground1"])
    processOnCreate(tilemap.layers["ground2"])
    processOnCreate(tilemap.layers["overlay"])

    autoAnimationObjects = tilemap.layers["objects"].find("Animate")
    animationObjects = tilemap.layers["objects"].find("OnAnimate")
コード例 #9
0
    def initArea(self, mapFile):
        """Load maps and initialize sprite layers for each new area"""
        self.tilemap = tmx.load(mapFile, screen.get_size())
        self.players = tmx.SpriteLayer()
        self.objects = tmx.SpriteLayer()

        #self.life = pygame.image.load('life.png')
        #self.gamefont = pygame.font.Font(None,30)
        #self.timertext = gamefont.render('Timer:' +str(timer),1,[255,0,0])
        #self.boxsize = self.timertext.get_rect()
        #self.timerXpos = (640-self.boxsize[2])/2
        #screen.blit(self.timertext,[0,0])

        try:
            for cell in self.tilemap.layers['sprites'].find('src'):
                SpriteLoop((cell.px,cell.py), cell, self.objects)
        # In case there is no sprite layer for the current map
        except KeyError:
            pass
        else:
            self.tilemap.layers.append(self.objects)
            #self.life.layers.append(self.objects) #추가한거
        # Initializing player sprite

            startCell1 = self.tilemap.layers['triggers'].find('playerStart')[random.randint(0,30)]
            self.player1 = character.Player((startCell1.px, startCell1.py), startCell1['playerStart'], self.players)
            startCell2 = self.tilemap.layers['triggers'].find('playerStart')[random.randint(0, 30)]
            self.player2 = character.Player2((startCell2.px, startCell2.py), startCell2['playerStart'], self.players)

            for i in range (0,9):
                startCell3 = self.tilemap.layers['triggers'].find('playerStart')[random.randint(0, 30)]
                self.player3 = character.NPC((startCell3.px, startCell3.py), startCell2['playerStart'],self.players)
            self.tilemap.layers.append(self.players)
            self.tilemap.set_focus(self.player1.rect.x, self.player1.rect.y) # 1p 시점
コード例 #10
0
ファイル: platformer.py プロジェクト: devforfu/pycon2014
    def main(self, screen):
        clock = pygame.time.Clock()
        background = pygame.image.load('background.png')

        self.tilemap = tmx.load('map-enemies.tmx', screen.get_size())
        self.jump = pygame.mixer.Sound('jump.wav')
        self.shoot = pygame.mixer.Sound('shoot.wav')
        self.explosion = pygame.mixer.Sound('explosion.wav')
        self.sprites = tmx.SpriteLayer()
        self.enemies = tmx.SpriteLayer()
        for enemy in self.tilemap.layers['triggers'].find('enemy'):
            Enemy((enemy.px, enemy.py), self.enemies)
        self.tilemap.layers.append(self.enemies)
        start_cell = self.tilemap.layers['triggers'].find('player')[0]
        self.player = Player((start_cell.px, start_cell.py), self.sprites)
        self.tilemap.layers.append(self.sprites)

        while True:
            dt = clock.tick(30)

            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    return
                if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
                    return

            self.tilemap.update(dt / 1000., self)
            screen.blit(background, (0, 0))
            self.tilemap.draw(screen)
            pygame.display.flip()

            if self.player.is_dead:
                print('- YOU DIED -')
                return
コード例 #11
0
ファイル: main.py プロジェクト: NicolasFig/juegopy
    def main(self, screen):
        clock = pygame.time.Clock()

        background = pygame.image.load(data.cargar_imagen('fondo'))

        self.tilemap = tmx.load('mapa.tmx', screen.get_size())

        self.sprites = tmx.SpriteLayer()
        start_cell = self.tilemap.layers['triggers'].find('player')[0]
        self.player = Player((start_cell.px, start_cell.py), self.sprites)
        self.tilemap.layers.append(self.sprites)

        self.enemies = tmx.SpriteLayer()
        for enemy in self.tilemap.layers['triggers'].find('enemy'):
            Enemy((enemy.px, enemy.py), self.enemies)
        self.tilemap.layers.append(self.enemies)

        done = False
        while done == False:
            dt = clock.tick(30)

            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    done = True
                if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
                    done = True

            self.tilemap.update(dt / 1000., self)
            screen.blit(background, (0, 0))
            self.tilemap.draw(screen)
            pygame.display.flip()

            if self.player.is_dead:
                done = True
        pygame.quit()
コード例 #12
0
ファイル: 18-shooting.py プロジェクト: MikeTam1021/WEP_class
    def main(self, screen):
        clock = pygame.time.Clock()

        background = pygame.image.load('background.png')

        self.tilemap = tmx.load('map-enemies.tmx', screen.get_size())

        self.sprites = tmx.SpriteLayer()
        start_cell = self.tilemap.layers['triggers'].find('player')[0]
        self.player = Player((start_cell.px, start_cell.py), self.sprites)
        self.tilemap.layers.append(self.sprites)

        self.enemies = tmx.SpriteLayer()
        for enemy in self.tilemap.layers['triggers'].find('enemy'):
            Enemy((enemy.px, enemy.py), self.enemies)
        self.tilemap.layers.append(self.enemies)

        while 1:
            dt = clock.tick(100)

            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    return
                if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
                    return

            self.tilemap.update(dt / 1000., self)
            screen.blit(background, (0, 0))
            self.tilemap.draw(screen)
            pygame.display.flip()

            if self.player.is_dead:
                print 'YOU DIED'
                return
コード例 #13
0
ファイル: main.py プロジェクト: bluesrv/LikeAPiePY
    def main(self, screen):
        clock = pygame.time.Clock()

        self.blocked = pygame.mixer.Sound("{0}blocked.wav".format("sound/"))
        self.jump = pygame.mixer.Sound("{0}jump.wav".format("sound/"))
        self.respawn = pygame.mixer.Sound("{0}respawn.wav".format("sound/"))
        self.respawn_2 = pygame.mixer.Sound("{0}respawn_2.wav".format("sound/"))
        self.clear = pygame.mixer.Sound("{0}clear.wav".format("sound/"))

        self.tilemap = tmx.load("likeapiepy2.tmx", screen.get_size())

        self.sprites = tmx.SpriteLayer()
        start_cell = self.tilemap.layers['triggers'].find('player')[0]
        self.player = Player((start_cell.px, start_cell.py), self.sprites)
        self.tilemap.layers.append(self.sprites)

        pygame.display.set_caption("Like a PiePy")

        while 1:
            clock.tick(30)
            dt = clock.tick(30)

            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    return False
                if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
                    return False

            if self.player.end:
                self.clear.play()
                return True

            self.tilemap.update(dt / 1000., self)
            self.tilemap.draw(screen)
            pygame.display.flip()
コード例 #14
0
 def init(self):
     self.pygame.init()
     self.size = (self.width, self.height)
     self.screen = pygame.display.set_mode(self.size)
     self.clock = self.pygame.time.Clock()
     self.time_step = 0
     # TODO: init sprite, tile,...
     self.tilemap = tmx.load("untitled.tmx", self.screen.get_size())
コード例 #15
0
ファイル: dave.py プロジェクト: ryesalvador/pydave
 def __init__(self, screen):
     self.screen = screen
     self.clock = pygame.time.Clock()
     self.background = pygame.image.load('data/background.png')
     self.tilemap = tmx.load('map.tmx', screen.get_size())
     self.sprites = tmx.SpriteLayer()
     start_cell = self.tilemap.layers['triggers'].find('player')[0]
     self.player = Player((start_cell.px, start_cell.py), self.sprites)
     self.tilemap.layers.append(self.sprites)
     self.items = tmx.SpriteLayer()
コード例 #16
0
ファイル: game.py プロジェクト: viljums/Grey
 def __init__ (self):
     self.changeLevel = False
     self.sprites = tmx.SpriteLayer()
     self.mapLib = ['Maps/layer3.tmx', 'Maps/layer2.tmx', 'Maps/layer3.tmx']
     self.mapNumber = 0
     self.mapFile = self.mapLib[self.mapNumber]
     self.tilemap = tmx.load (self.mapFile, screen.get_size())
     start_cell = self.tilemap.layers['triggers'].find('player')[0]
     self.player = Player((start_cell.px, start_cell.py), self.sprites)
     self.sword = Sword (self.sprites)
     self.cdBar = CDBar (self.sprites)
コード例 #17
0
    def set_tilemap(self, *, map_path: str, focus: Tuple[int, int] = (0, 0)):
        try:
            self.objects.remove(self.tilemap)
        except KeyError:
            pass

        rect = self.screen.get_rect()

        self.tilemap = tmx.load(map_path, (rect.height, rect.width))
        self.tilemap.set_focus(*focus)
        self.objects.add(self.tilemap)
コード例 #18
0
ファイル: main 004.py プロジェクト: kburts/PygameRPG
    def Level01(self, screen):
        self.tilemap = tmx.load('map v4.tmx', screen.get_size())

        self.sprites = tmx.SpriteLayer()
        start_cell = self.tilemap.layers['triggers'].find('player')[0]
        end_cell = self.tilemap.layers['triggers'].find('levelend')[0]

        self.player = Player((start_cell.px, start_cell.py), self.sprites)

        self.Appendtotilemap()

        self.mainloop()
コード例 #19
0
    def Level01(self, screen):
        self.tilemap = tmx.load('map v4.tmx', screen.get_size())

        self.sprites = tmx.SpriteLayer()
        start_cell = self.tilemap.layers['triggers'].find('player')[0]
        end_cell = self.tilemap.layers['triggers'].find('levelend')[0]

        self.player = Player((start_cell.px, start_cell.py), self.sprites)

        self.Appendtotilemap()

        self.mainloop()
コード例 #20
0
ファイル: main 004.py プロジェクト: kburts/PygameRPG
    def Level02(self, screen):
        print 'got into level 2! It is a little more spooky in here.'
        self.tilemap = tmx.load('level02.tmx', screen.get_size())

        self.sprites = tmx.SpriteLayer()
        start_cell = self.tilemap.layers['triggers'].find('player')[0]
        end_cell = self.tilemap.layers['triggers'].find('levelend')[0]

        self.player = Player((start_cell.px, start_cell.py), self.sprites)

        self.Appendtotilemap()

        self.mainloop()
コード例 #21
0
ファイル: main 004.py プロジェクト: kburts/PygameRPG
    def Level03(self, screen):
        print 'First town, how exciting!'
        self.tilemap = tmx.load('Town01.tmx', screen.get_size())

        self.sprites = tmx.SpriteLayer()
        start_cell = self.tilemap.layers['triggers'].find('player')[0]
        end_cell = self.tilemap.layers['triggers'].find('levelend')[0]

        self.player = Player((start_cell.px, start_cell.py), self.sprites)

        self.Appendtotilemap()

        self.mainloop()
コード例 #22
0
    def Level03(self, screen):
        print 'First town, how exciting!'
        self.tilemap = tmx.load('Town01.tmx', screen.get_size())

        self.sprites = tmx.SpriteLayer()
        start_cell = self.tilemap.layers['triggers'].find('player')[0]
        end_cell = self.tilemap.layers['triggers'].find('levelend')[0]

        self.player = Player((start_cell.px, start_cell.py), self.sprites)

        self.Appendtotilemap()

        self.mainloop()
コード例 #23
0
    def Level02(self, screen):
        print 'got into level 2! It is a little more spooky in here.'
        self.tilemap = tmx.load('level02.tmx', screen.get_size())

        self.sprites = tmx.SpriteLayer()
        start_cell = self.tilemap.layers['triggers'].find('player')[0]
        end_cell = self.tilemap.layers['triggers'].find('levelend')[0]

        self.player = Player((start_cell.px, start_cell.py), self.sprites)

        self.Appendtotilemap()

        self.mainloop()
コード例 #24
0
ファイル: mario.py プロジェクト: vtlkzmn/Mario
    def main(self, screen):
        clock = pygame.time.Clock()
        
        pygame.mixer.init()

        self.tilemap = tmx.load('map.tmx', screen.get_size())
        
        self.sprites = tmx.SpriteLayer()
        start_cell = self.tilemap.layers['triggers'].find('player')[0]
        self.player = Player((start_cell.px, start_cell.py), self.sprites)
        self.tilemap.layers.append(self.sprites)

        self.enemies = tmx.SpriteLayer()
        for enemy in self.tilemap.layers['triggers'].find('enemy'):
            Enemy((enemy.px, enemy.py), self.enemies)
        self.tilemap.layers.append(self.enemies)

        self.coinblox = tmx.SpriteLayer()
        for block in self.tilemap.layers['triggers'].find('coinblock'):
            Coinblock((block.px, block.py), self.coinblox)
        self.tilemap.layers.append(self.coinblox)

        self.bricks = tmx.SpriteLayer()
        for block in self.tilemap.layers['triggers'].find('brickblock'):
            Brickblock((block.px, block.py), self.bricks)
        self.tilemap.layers.append(self.bricks)

        play_sound('main_theme.ogg')

        global score

        while True:
            dt = clock.tick(30)
            global player_dead
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    pygame.quit()
                    sys.exit()
                if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
                    pygame.quit()
                    sys.exit()

            self.tilemap.update(dt / 1000., self)
            self.tilemap.draw(screen)
            display_text(screen, score , 0, 0, 15)
            if player_dead:
                display_text(screen, 'Game over.  Press esc to quit.',0, 40, 17)

            if game_won:
                display_text(screen, 'You win. Press esc to quit.', 0, 40, 17)
            pygame.display.flip()
コード例 #25
0
ファイル: game.py プロジェクト: bdero/pygame-tutorial
    def main(self, screen):
        clock = pygame.time.Clock()

        self.background = pygame.sprite.Group()
        Background(self.background)

        self.sounds = {}
        for sound in ['jump', 'land', 'shoot']:
            self.sounds[sound] = pygame.mixer.Sound('sounds/' + sound + '.wav')

        self.tilemap = tmx.load('map.tmx', screen.get_size())

        start_cell = self.tilemap.layers['triggers'].find('player')[0]
        start_position = (start_cell.px, start_cell.py)

        self.sprites = tmx.SpriteLayer()
        self.player = Player(start_position, self.sprites)
        self.tilemap.layers.append(self.sprites)

        self.enemies = tmx.SpriteLayer()
        for enemy in self.tilemap.layers['triggers'].find('enemy'):
            Enemy((enemy.px, enemy.py), self.enemies)
        self.tilemap.layers.append(self.enemies)


        self.tilemap.set_focus(start_position[0], start_position[1])
        
        while 1:
            dt = clock.tick(30)/1000.0

            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    return
                if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
                    return

            #screen.blit(background, (0, 0))
            self.tilemap.update(dt, self)
            self.tilemap.set_focus(
                self.tilemap.fx + (self.player.rect.x - self.tilemap.fx)/6.0,
                self.tilemap.fy + (self.player.rect.y - self.tilemap.fy)/6.0
            )
            self.background.draw(screen)
            self.tilemap.draw(screen)

            pygame.display.flip()

            if self.player.is_dead:
                print 'YOU DIED'
                return
コード例 #26
0
ファイル: tmx.py プロジェクト: Jbolt01/rpg-engine
    def __init__(self,
                 *,
                 size=(0, 0),
                 start_map_path,
                 focus=(0, 0),
                 tickrate,
                 **kwargs):
        super().__init__(size=size, **kwargs)

        self.clock = pygame.time.Clock()
        self.tilemap = tmx.load(start_map_path, size)
        self.tilemap.set_focus(*focus)
        self.objects.add(self.tilemap)
        self.tickrate = tickrate
コード例 #27
0
ファイル: game.py プロジェクト: alGatto/Tuto_Pygame
    def main(self, screen):

        clock = pygame.time.Clock()

        self.size = self.width, self.height = 1024, 683

        background =pygame.image.load('ressources/level1back.png') #charge l'image de fond

        self.tilemap = tmx.load('levelMap/map.tmx', screen.get_size())

        self.sprites = tmx.SpriteLayer()
        start_cell = self.tilemap.layers['triggers'].find('player')[0]
        self.player = player.Player((start_cell.px, start_cell.py - 400), self.sprites)
        self.tilemap.layers.append(self.sprites)

        self.enemies = tmx.SpriteLayer()
        for self.enemy in self.tilemap.layers['triggers'].find('enemy'):
            enemy.Enemy((self.enemy.px, self.enemy.py), self.enemies)
        self.tilemap.layers.append(self.enemies)

        self.jump = pygame.mixer.Sound('sound/jump.wav')
        self.shoot = pygame.mixer.Sound('sound/shoot.wav')
        self.explosion = pygame.mixer.Sound('sound/explosion.wav')

        while 1:
            dt = clock.tick(30)
            for event in pygame.event.get():
                if event.type == pygame.QUIT: # si la croix en haut à gauche de la fenêtre est cliquée
                    running = False # la boucle de jeu s'arrête
                    pygame.quit()
                    quit()



            self.tilemap.update(dt / 1000., self)

            screen.blit(background, (0, 0)) # place le fond

            self.tilemap.draw(screen)
            screen.blit(score.Score().text,(0,0))

            life.Life().display(screen,life.Life().image)

            pygame.display.flip()

            if self.player.is_dead: #si le perso meurt
                print('Perdu!') #afficher le message
                return
コード例 #28
0
    def init_map(self, map_file, new_pos, first_time):
        self.tilemap = tmx.load(map_file, self.screen.get_size())

        if first_time:
            # condition for first attempt
            self.sprites = tmx.SpriteLayer()
            start_cell = self.tilemap.layers['triggers'].find('player')[0]
            self.my_mario = mario.Mario((start_cell.px, start_cell.py),
                                        self.sprites)
        else:
            start_cell = self.tilemap.layers['triggers'].find(new_pos)[0]
        self.my_mario.rect.topleft = (start_cell.px, start_cell.py)

        self.coinboxs = tmx.SpriteLayer()
        for _coinbox in self.tilemap.layers['triggers'].find('coinbox'):
            box_type = getattr(coinbox,
                               _coinbox.properties.get("type", "SECRET"))
            prize = None
            if _coinbox.properties.get("item"):
                prize = getattr(powerup, _coinbox.properties.get("item"))
            count = _coinbox.properties.get("count", 1)
            coinbox.CoinBox(self, (_coinbox.px, _coinbox.py), box_type, prize,
                            count, self.coinboxs)

        self.bricks = tmx.SpriteLayer()
        for _brick in self.tilemap.layers['triggers'].find('brick'):
            brick.Brick(self, (_brick.px, _brick.py), self.bricks)

        self.coins = tmx.SpriteLayer()
        for _coin in self.tilemap.layers['triggers'].find('coin'):
            coin.Coin((_coin.px, _coin.py), self.coins)

        self.enemies = tmx.SpriteLayer()
        for _turtle in self.tilemap.layers['triggers'].find('turtle'):
            turtle.Turtle((_turtle.px, _turtle.py), self.enemies)
        for _flower in self.tilemap.layers['triggers'].find('flower'):
            color = getattr(flower,
                            _flower.properties.get("color", "GREEN_FLOWER"))
            flower.Flower((_flower.px, _flower.py), color, self.enemies)

        self.powerups = tmx.SpriteLayer()
        # layer order: background, midground + sprites, foreground
        self.insert_layer(self.powerups, "powerups", 1)
        self.insert_layer(self.coins, "coins", 2)
        self.insert_layer(self.coinboxs, "coinboxs", 3)
        self.insert_layer(self.bricks, "bricks", 4)
        self.insert_layer(self.enemies, "enemies", 5)
        self.insert_layer(self.sprites, "sprites", 6)
コード例 #29
0
    def main(self, screen):
        clock = pygame.time.Clock()

        self.background = pygame.sprite.Group()
        Background(self.background)

        self.sounds = {}
        for sound in ['jump', 'land', 'shoot']:
            self.sounds[sound] = pygame.mixer.Sound('sounds/' + sound + '.wav')

        self.tilemap = tmx.load('map.tmx', screen.get_size())

        start_cell = self.tilemap.layers['triggers'].find('player')[0]
        start_position = (start_cell.px, start_cell.py)

        self.sprites = tmx.SpriteLayer()
        self.player = Player(start_position, self.sprites)
        self.tilemap.layers.append(self.sprites)

        self.enemies = tmx.SpriteLayer()
        for enemy in self.tilemap.layers['triggers'].find('enemy'):
            Enemy((enemy.px, enemy.py), self.enemies)
        self.tilemap.layers.append(self.enemies)

        self.tilemap.set_focus(start_position[0], start_position[1])

        while 1:
            dt = clock.tick(30) / 1000.0

            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    return
                if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
                    return

            #screen.blit(background, (0, 0))
            self.tilemap.update(dt, self)
            self.tilemap.set_focus(
                self.tilemap.fx + (self.player.rect.x - self.tilemap.fx) / 6.0,
                self.tilemap.fy + (self.player.rect.y - self.tilemap.fy) / 6.0)
            self.background.draw(screen)
            self.tilemap.draw(screen)

            pygame.display.flip()

            if self.player.is_dead:
                print 'YOU DIED'
                return
コード例 #30
0
ファイル: _game.py プロジェクト: joshdeweese/pygame_tmx_game
    def main(self, screen):
        clock = pygame.time.Clock()
        background = pygame.image.load('graphics/background960-512.png')
        self.tilemap = tmx.load('tilemap.tmx', screen.get_size())
        self.sprites = tmx.SpriteLayer()
        start_cell = self.tilemap.layers['triggers'].find('player')[0]
        self.player = Player((start_cell.px, start_cell.py), self.sprites)

        self.tilemap.layers.append(self.sprites)
        self.enemies = tmx.SpriteLayer()
        self.coins = tmx.SpriteLayer()
        for enemy in self.tilemap.layers['triggers'].find('enemy'):
            Enemy((enemy.px, enemy.py), self.enemies)
        for coin in self.tilemap.layers['triggers'].find('coin'):
            Coin((coin.px, coin.py), self.coins)
        self.tilemap.layers.append(self.enemies)
        self.tilemap.layers.append(self.coins)
        foreground = self.tilemap.layers['foreground']
        self.tilemap.layers.append(foreground)

        x = 0
        while x < 1250:
            dt = clock.tick(30)
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    pygame.quit()
                    exit()
            self.tilemap.update(dt / 1000., self)
            screen.blit(background, (0, 0))
            self.tilemap.draw(screen)
            pygame.font.init()
            score_color = (100, 100, 100)
            score_message = 'Score: ' + str(self.player.score)
            score_font = pygame.font.SysFont('tahoma', 16)
            score_text = score_font.render(score_message, 1, score_color)
            screen.blit(score_text, (875, 15))
            if self.player.is_dead:
                pygame.font.init()
                died_color = (255, 255, 255)
                died_message = 'YOU LOSE!'
                died_font = pygame.font.SysFont('tahoma', 150)
                died_text = died_font.render(died_message, 1, died_color)
                screen.blit(died_text, (x-300, 250))
                x += 10
            pygame.display.flip()
        else:
            Menu().main(screen)
コード例 #31
0
ファイル: main.py プロジェクト: axelhodler/code-G
    def main(self, screen):
        clock = pygame.time.Clock()

        # tiled part
        self.tilemap = tmx.load('tiled/map.tmx', screen.get_size())

        self.sprites = tmx.SpriteLayer()
        # get the start cell in the map and set the player position accordingly
        start_cell = self.tilemap.layers['triggers'].find('player')[0]
        self.player = Player((start_cell.px, start_cell.py), self.sprites)
        self.tilemap.layers.append(self.sprites)
        
        # enemies
        self.enemies = tmx.SpriteLayer()
        for enemy in self.tilemap.layers['triggers'].find('enemy'):
            Enemy((enemy.px, enemy.py), self.enemies)
        self.tilemap.layers.append(self.enemies)
        
        # cat
        self.cat = tmx.SpriteLayer()
        for cats in self.tilemap.layers['cat'].find('cat'):
          Cat((cats.px, cats.py), self.cat)
        self.tilemap.layers.append(self.cat)
        
        # weapon sound
        self.shoot = pygame.mixer.Sound('sounds/weapons/shotgun_shot.wav')
        self.reload = pygame.mixer.Sound('sounds/weapons/shotgun_reload.wav')
        
        # gameloop
        while 1:
            dt = clock.tick(30)

            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    return
                if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
                    return

            self.tilemap.update(dt / 1000., self)
            self.tilemap.draw(screen)
            pygame.display.flip()
            
            # whatever
            if self.player.is_dead:
                print 'U DYED......... YOUR SHIRT RED'
                return
コード例 #32
0
ファイル: main.py プロジェクト: maitreyak/game_platformer
    def start(self):

        #init the game clock
        clock = pygame.time.Clock()
        
        #load the tile map
        self.tilemap = tmx.load('map.tmx',self.screen.get_size())
        self.sprites = tmx.SpriteLayer()
        
        self.tilemap.layers.append(self.sprites)
        
        start_cell = self.tilemap.layers['triggers'].find('player')[0]
        self.player = Player((start_cell.px, start_cell.py), self.sprites)

        opponent_cell = self.tilemap.layers['triggers'].find('opponent')[0]
        Opponent((opponent_cell.px, opponent_cell.py), self.sprites)

        
        #set view port
        self.tilemap.set_focus(640,480)
        
        background = pygame.Surface(screen.get_size())
        background.fill((255, 255, 255))
        
        #main event loop of the game
        while True:
            
            #setting fps to 30 calls per second.
            delta_t = clock.tick(40)

            #loop thru the events and pick the right one.
            for event in pygame.event.get():
                #close button
                if event.type == pygame.QUIT:
                    return
                #esc key
                if event.type == pygame.KEYDOWN\
                   and event.key == pygame.K_ESCAPE:
                    return
             
            screen.blit(background,(0,0))
            self.tilemap.update(delta_t/1000.,self)
            self.tilemap.draw(self.screen)
            pygame.display.flip()
コード例 #33
0
    def load_sprites(self):

        # loads enemy and map
        enemy = __import__('enemy'+str(self.enemyn))
        self.tilemap = tmx.load(enemy.tilemap, self.screen.get_size())  # map

        self.sprite_e = tmx.SpriteLayer()
        start_cell = self.tilemap.layers['triggers'].find('enemy')[0]
        self.enemy = enemy.Enemy((start_cell.px, start_cell.py), self.sprite_e)
        self.tilemap.layers.append(self.sprite_e)  # enemy

        # loads player
        self.sprite_p = tmx.SpriteLayer()
        start_cell = self.tilemap.layers['triggers'].find('player')[0]
        self.player = Player((start_cell.px, start_cell.py), self.enemyn, self.level, self.sprite_p)
        self.tilemap.layers.append(self.sprite_p)

        self.player.sensors = Sensors()
        self.enemy.sensors = Sensors()
コード例 #34
0
        def load_sprites(self):

		# loads enemy and map 
		enemy = __import__('enemy'+str(self.enemyn))
		self.tilemap = tmx.load(enemy.tilemap, self.screen.get_size())  # map

		self.sprite_e = tmx.SpriteLayer()
		start_cell = self.tilemap.layers['triggers'].find('enemy')[0]	
		self.enemy = enemy.Enemy((start_cell.px, start_cell.py), self.sprite_e)
		self.tilemap.layers.append(self.sprite_e)  # enemy

		# loads player 
		self.sprite_p = tmx.SpriteLayer()
		start_cell = self.tilemap.layers['triggers'].find('player')[0]
		self.player = Player((start_cell.px, start_cell.py), self.enemyn, self.level, self.sprite_p) 
		self.tilemap.layers.append(self.sprite_p)
 
                self.player.sensors = Sensors()
                self.enemy.sensors = Sensors()
コード例 #35
0
ファイル: main.py プロジェクト: SuperThunder/Dead
    def main(self, screen):

        clock = pygame.time.Clock()     # Game clock

        bg = pygame.image.load('data/images/bg.png')    # Load image file

        self.tilemap = tmx.load('data/maps/intro.tmx', screen.get_size())   # Load TMX file

        ## Load the UPC
        self.sprites = tmx.SpriteLayer()
        start_cell = self.tilemap.layers['triggers'].find('player')[0]
        self.player = Player((start_cell.px, start_cell.py), self.sprites)
        self.tilemap.layers.append(self.sprites)

        ## Sounds
        self.gun_sound = pygame.mixer.Sound('data/sounds/shot.wav')

        ## Main game loop
        while True:

            dt = clock.tick(30)      # Slows the while loop to 30 FPS
            ## Get single keypress events (opposed to holding a key down)
            for event in pygame.event.get():
                ## If the player tries to quit the game, exit
                if event.type == pygame.QUIT:
                    return

                if event.type == pygame.KEYDOWN and \
                        pygame.key.get_mods() & pygame.KMOD_CTRL and event.key == pygame.K_q:
                    return

            if self.player.rect.y > self.tilemap.height * 32:
                self.player.is_dead = True

            if self.player.is_dead:
                return

            screen.blit(bg, (0, 0))     # Shows the background image
            self.tilemap.update(dt, self)
            self.tilemap.draw(screen)


            pygame.display.flip()   # Loads the image from memory
コード例 #36
0
    def __init__(self):
        self.background = pygame.image.load('background.png')
        self.tilemap = tmx.load('marathon.tmx', screen.get_size())
        #actions layer
        self.actions = tmx.SpriteLayer()
        self.tilemap.layers.append(self.actions)
        for x in self.tilemap.layers['triggers'].find('trumpet'):
            Trumpet((x.px, x.py-64), self.actions)
            
        for x in self.tilemap.layers['triggers'].find('enemy'):
            Enemy((x.px, x.py), self.actions)
            
        for x in self.tilemap.layers['triggers'].find('tardis'):
            Tardis((x.px, x.py-64), self.actions)
            
        for x in self.tilemap.layers['triggers'].find('drum'):
            Drum((x.px, x.py-64), self.actions)
            
        for x in self.tilemap.layers['triggers'].find('mic'):
            Microphone((x.px, x.py-64), self.actions)
            
        for x in self.tilemap.layers['triggers'].find('kytara'):
            Guitar((x.px, x.py-64), self.actions)

        self.sprites = tmx.SpriteLayer()
        start_cell = self.tilemap.layers['triggers'].find('player')[0]
        self.player = Player((start_cell.px, start_cell.py), self.sprites)
        self.tilemap.layers.append(self.sprites)
        
        "Create pipe"
        self.spell_conn, spell_child_conn = Pipe()
        "create process"
        self.spell_p = Process(target=_startSpell, args=(spell_child_conn,))
        "start it"
        self.spell_p.start()
        
        "Create pipe"
        self.camera_conn, camera_child_conn = Pipe()
        "create process"
        self.camera_p = Process(target=_startCamera, args=(camera_child_conn,))
        "start it"
        self.camera_p.start()
コード例 #37
0
 def initArea(self, mapFile):
     """Load maps and initialize sprite layers for each new area"""
     self.tilemap = tmx.load(mapFile, screen.get_size())
     self.players = tmx.SpriteLayer()
     self.objects = tmx.SpriteLayer()
     # Initializing other animated sprites
     try:
         for cell in self.tilemap.layers['sprites'].find('src'):
             SpriteLoop((cell.px, cell.py), cell, self.objects)
     # In case there is no sprite layer for the current map
     except KeyError:
         pass
     else:
         self.tilemap.layers.append(self.objects)
     # Initializing player sprite
     startCell = self.tilemap.layers['triggers'].find('playerStart')[0]
     self.player = Player((startCell.px, startCell.py),
                          startCell['playerStart'], self.players)
     self.tilemap.layers.append(self.players)
     self.tilemap.set_focus(self.player.rect.x, self.player.rect.y)
コード例 #38
0
ファイル: pylletTown.py プロジェクト: cortstar/pylletTown
 def initArea(self, mapFile):
     """Load maps and initialize sprite layers for each new area"""
     self.tilemap = tmx.load(mapFile, screen.get_size())
     self.players = tmx.SpriteLayer()
     self.objects = tmx.SpriteLayer()
     # Initializing other animated sprites
     try:
         for cell in self.tilemap.layers['sprites'].find('src'):
             SpriteLoop((cell.px,cell.py), cell, self.objects)
     # In case there is no sprite layer for the current map
     except KeyError:
         pass
     else:
         self.tilemap.layers.append(self.objects)
     # Initializing player sprite
     startCell = self.tilemap.layers['triggers'].find('playerStart')[0]
     self.player = Player((startCell.px, startCell.py), 
                          startCell['playerStart'], self.players)
     self.tilemap.layers.append(self.players)
     self.tilemap.set_focus(self.player.rect.x, self.player.rect.y)  
コード例 #39
0
ファイル: Game.py プロジェクト: doctordesh/pygame-megaman
  def main(self, screen):
    clock = pygame.time.Clock()

    background  = pygame.image.load('assets/background.png')

    self.tilemap = tmx.load('assets/maps/map.tmx', screen.get_size())

    self.sprites = tmx.SpriteLayer()
    start_cell   = self.tilemap.layers['triggers'].find('player')[0]
    self.player  = Player.Player((start_cell.px, start_cell.py), self.sprites)
    self.tilemap.layers.append(self.sprites)

    # sprites     = pygame.sprite.Group()
    # self.player = Player.Player(sprites)

    # self.walls  = pygame.sprite.Group()
    # block       = pygame.image.load('assets/block.png')
    # for x in range(0, 640, 32):
    #   for y in range(0, 480, 32):
    #     if x in (0, 640 - 32) or y in (0, 480 - 32):
    #       wall = pygame.sprite.Sprite(self.walls)
    #       wall.image = block
    #       wall.rect  = pygame.rect.Rect((x, y), block.get_size())
    # sprites.add(self.walls)

    while 1:
      dt = clock.tick(60)

      for event in pygame.event.get():
        if event.type == pygame.QUIT:
          return
        if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
          return

      sprites.update(dt / 1000.0, self)
      screen.fill((200, 200, 255))
      screen.blit(background, (0, 0))
      sprites.draw(screen)
      pygame.display.flip()
コード例 #40
0
ファイル: _game.py プロジェクト: joshdeweese/pygame_tmx_game
 def main(self, screen):
     clock = pygame.time.Clock()
     background = pygame.image.load('graphics/black_background960-512.png')
     self.tilemap = tmx.load('menu_tilemap.tmx', screen.get_size())
     self.tilemap.set_focus(0, 0)
     while 1:
         dt = clock.tick(30)
         for event in pygame.event.get():
             if event.type == pygame.QUIT:
                 pygame.quit()
                 exit()
         self.tilemap.update(dt / 1000., self)
         screen.blit(background, (0, 0))
         self.tilemap.draw(screen)
         pygame.display.flip()
         pos = pygame.mouse.get_pos()
         click = pygame.mouse.get_pressed()
         if click[0] == 1 and 385 < pos[0] < 540 and 160 < pos[1] < 220:
             Game().main(screen)
         if click[0] == 1 and 385 < pos[0] < 540 and 260 < pos[1] < 315:
             pygame.quit()
             exit()
コード例 #41
0
ファイル: driving.py プロジェクト: MikeTam1021/WEP_class
def main():
    screen = pygame.display.set_mode((800, 600))

    map = tmx.load('driving-map.tmx', screen.get_size())
    sprites = tmx.SpriteLayer()
    map.layers.append(sprites)
    car = CarSprite(sprites)

    clock = pygame.time.Clock()
    while True:
        dt = clock.tick(30) / 1000.0

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                return
            if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
                return

        screen.fill((50,50,50))
        map.update(dt)
        map.set_focus(*car.rect.center)
        map.draw(screen)
        pygame.display.flip()
コード例 #42
0
ファイル: platformer.py プロジェクト: begerter/magic-improv
    def __init__(self, clock, screen):
        minigame.Minigame.__init__(self, screen)
        self.clock = clock
        self.tilemap = tmx.load('assets/platformerMaps/map1.tmx', screen.get_size())
        self.background = pygame.image.load('assets/platformerbg.png')
#        pygame.mouse.set_visible(0)

        # add a layer for our sprites controlled by the tilemap scrolling
        self.sprites = tmx.SpriteLayer()
        self.tilemap.layers.append(self.sprites)
        # fine the player start cell in the triggers layer
        start_cell = self.tilemap.layers['triggers'].find('player')[0]
        # use the "pixel" x and y coordinates for the player start
        self.player = Player((start_cell.px, start_cell.py), self.sprites)

        # add a separate layer for enemies so we can find them more easily later
        self.enemies = tmx.SpriteLayer()
        self.tilemap.layers.append(self.enemies)
        # add an enemy for each "enemy" trigger in the map
        for enemy in self.tilemap.layers['triggers'].find('enemy'):
            Enemy((enemy.px, enemy.py), self.enemies)

        self.tilemap.set_focus(self.player.rect.x, self.player.rect.y)
コード例 #43
0
ファイル: driving.py プロジェクト: doctordesh/pygame-megaman
def main():
    screen = pygame.display.set_mode((800, 600))

    map = tmx.load('driving-map.tmx', screen.get_size())
    sprites = tmx.SpriteLayer()
    map.layers.append(sprites)
    car = CarSprite(sprites)

    clock = pygame.time.Clock()
    while True:
        dt = clock.tick(30) / 1000.0

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                return
            if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
                return

        screen.fill((50,50,50))
        map.update(dt)
        map.set_focus(*car.rect.center)
        map.draw(screen)
        pygame.display.flip()
コード例 #44
0
ファイル: game.py プロジェクト: jhothi/DBZ-GAME
    def __init__(self, width, height, bg_color):
        pygame.init()
        self.displaySurface = pygame.display.set_mode((width, height))
        self.bgColor = bg_color
        pygame.display.set_caption("GOKU")

        self.tilemap = tmx.load("test.tmx", self.displaySurface.get_size())
        self.players = tmx.SpriteLayer()
        self.enemies = tmx.SpriteLayer()
        self.blasts = tmx.SpriteLayer()
        self.hud = tmx.SpriteLayer()
        self.dragonball = tmx.SpriteLayer()
        self.checkpoints = Checkpoint()
        #self.bg = pygame.image.load('res/Map/dbz_background.jpg')
        player_cell = self.tilemap.layers["triggers"].find("player")[0]
        enemy_cells = self.tilemap.layers["triggers"].find("enemy")
        checkpoint_cells = self.tilemap.layers["triggers"].find("checkpoint")
        finish = self.tilemap.layers["triggers"].find("finish")[0]

        for cell in enemy_cells:
            self.enemies.add(Henchmen2((cell.left, cell.bottom)))

        for checkpoint in checkpoint_cells:
            self.checkpoints.add_checkpoint((checkpoint.px, checkpoint.py))

        self.goku = Goku((player_cell.px, player_cell.py))
        #  self.vegeta = Vegeta((400, 200))
        self.players.add(self.goku)
        self.hud.add(Hud(self.goku))
        self.dragonball.add(Dragonball((finish.px, finish.py)))
        # self.players.add(self.vegeta)
        self.fpsClock = pygame.time.Clock()
        self.tilemap.layers.append(self.players)
        self.tilemap.layers.append(self.enemies)
        self.tilemap.layers.append(self.blasts)
        self.tilemap.layers.append(self.hud)
        self.tilemap.layers.append(self.dragonball)
コード例 #45
0
    def initArea(self, mapFile):  # initArea
        # *** *** ***

        self.tilemap = tmx.load(mapFile, screen.get_size())
        self.mapFile = mapFile

        # These fields are sprite class abstract groups. We will use the tmx API to do remove/kill and parse through the games
        # sprite instantiations

        # Players is for just player class
        self.players = tmx.SpriteLayer()

        # Objects is all things that will be updated
        self.objects = tmx.SpriteLayer()

        # Sub groups used to make code simpler and easier to read
        self.projectiles = tmx.SpriteLayer()
        self.collision = tmx.SpriteLayer()
        self.interactable = tmx.SpriteLayer()
        self.named = tmx.SpriteLayer()
        self.removable = tmx.SpriteLayer()
        self.enemies = tmx.SpriteLayer()
        #self.sprites = []

        startCell = self.tilemap.layers['triggers'].find('playerStart')[0]
        if self.samePlayer == False:

            self.player = Player((startCell.px, startCell.py),
                                 startCell['playerStart'], self.players)
        else:
            hld1 = self.player.hearts
            hld2 = self.player.WOFlevel
            hld3 = self.player.magicPer
            self.player = Player((startCell.px, startCell.py),
                                 startCell['playerStart'], self.players)
            self.player.hearts = hld1
            self.player.WOFlevel = hld2
            self.player.magicPer = hld3

            # self.player.rect = pygame.Rect((startCell.px, startCell.py), (64,64))
            # self.player.orient =  startCell['playerStart']
            # self.players.set_view(self.screen)
            # self.players.draw(self.screen)
            # self.player.setSprite()
            # Initializing other animated sprites
        try:
            for cell in self.tilemap.layers['sprites'].find('src'):
                SpriteLoop((cell.px, cell.py), cell, self.objects)
            for cell in self.tilemap.layers['npcSprites'].find('src'):
                npcSprite((cell.px, cell.py), cell, 'down', self.objects,
                          self.collision, self.interactable, self.named)

            for cell in self.tilemap.layers['statebasedSprites'].find('src'):

                if self.save[cell['saveIndex']] == 'true':
                    statebasedSprite((cell.px, cell.py), cell, self.objects,
                                     self.collision, self.interactable)

            hld = 0

            print(mapFile)

            if mapFile == 'WallsOrFireBalls.tmx':
                self.player.transitionIn = True
                print(self.player.transitionIn)

                for cell in self.tilemap.layers['enemySprites'].find('src'):
                    print(
                        str(self.player.WOFlevel) +
                        "this is the level i should be at")
                    if hld < self.player.WOFlevel + 3:
                        enemySprite((cell.px, cell.py), cell, 'down',
                                    self.objects, self.collision,
                                    self.removable, self.named, self.enemies)
                        hld += 1

            else:
                for cell in self.tilemap.layers['enemySprites'].find('src'):
                    enemySprite((cell.px, cell.py), cell, 'down', self.objects,
                                self.collision, self.removable, self.named)

            hldSprites = self.tilemap.layers['removableSprites'].find('src')

            for cell in hldSprites:

                removableSprite((cell.px, cell.py), cell, self.objects,
                                self.collision, self.removable)

        # In case there is no sprite layer for the current map
        except KeyError:
            print('key error')
            pass
        else:
            self.tilemap.layers.append(self.objects)

        # Initializing player sprite

        self.tilemap.layers.append(self.players)
        self.tilemap.set_focus(self.player.rect.x, self.player.rect.y)
コード例 #46
0
ファイル: game.py プロジェクト: viljums/Grey
    def main (self, screen):
        clock = pygame.time.Clock ()

        self.jump = pygame.mixer.Sound('jump.wav')
        self.explosion = pygame.mixer.Sound ('explosion.wav')

        sprites = ScrolledGroup()
        sprites.camera_x = 0

        self.mapFile = self.mapLib[self.mapNumber]
        self.tilemap = tmx.load (self.mapFile, screen.get_size())

        #self.sprites = tmx.SpriteLayer()




        self.tilemap.layers.append (self.sprites)



        self.enemies = tmx.SpriteLayer()
        self.immortalSprites = tmx.SpriteLayer ()
        for enemy in self.tilemap.layers['triggers'].find('enemy'):
            enemyType = enemy['enemy']
            if 'worm' in enemyType:
                Worm ((enemy.px, enemy.py), self.enemies)
            elif 'spitter' in enemyType:
                Spitter ((enemy.px, enemy.py), self.enemies)
            else:
                Enemy ((enemy.px, enemy.py), self.enemies)

        for cell in self.tilemap.layers['triggers'].find('blockers'):
            blocker = cell['blockers']
            if 'crawler' in blocker:
                Crawler (pygame.Rect (cell.px, cell.py, cell.width, cell.height), self.enemies)
            
        self.tilemap.layers.append(self.enemies)
        self.tilemap.layers.append (self.immortalSprites)


        image_x = 323
        image_y = 369


        while True:
            dt = clock.tick(30)
            for event in pygame.event.get ():
                if event.type == pygame.QUIT:
                    return 'dead'
                if event.type == pygame.KEYDOWN and \
                        event.key == pygame.K_ESCAPE:
                    return 'dead'
                self.player.get_event (event)

            self.tilemap.update (dt / 1000., self) #mechanix
            screen.fill ((255, 255, 255))
            self.tilemap.draw(screen)
            pygame.display.flip()

            if self.player.is_dead:
                return 'dead'
            if self.changeLevel:
                self.changeLevel = False
                return 'next'
コード例 #47
0
    def main(self, screen):
        clock = pygame.time.Clock()

        background = pygame.image.load('background.png')

        self.tilemap = tmx.load('Lvl1redux.tmx', screen.get_size())

        self.sprites = tmx.SpriteLayer()
        self.tilemap.layers.append(self.sprites)

        self.playersprites = tmx.SpriteLayer()
        start_cell = self.tilemap.layers['triggers'].find('player')[0]
        self.player = Player((start_cell.px, start_cell.py),
                             self.playersprites)
        self.tilemap.layers.append(self.playersprites)

        # bliting coin tally
        totalcoins = 0
        font = pygame.font.Font(None, 25)

        self.enemies = tmx.SpriteLayer()

        self.spiders = tmx.SpriteLayer()
        for spider in self.tilemap.layers['triggers'].find('enemy'):
            Spider((spider.px, spider.py), self.enemies)
        self.tilemap.layers.append(self.spiders)

        self.skeletons = tmx.SpriteLayer()
        for skeleton in self.tilemap.layers['triggers'].find('skeleton'):
            Skeleton((skeleton.px, skeleton.py), self.enemies)
        self.tilemap.layers.append(self.skeletons)
        self.tilemap.layers.append(self.enemies)

        self.coins = tmx.SpriteLayer()
        totalcoins = 0
        for coin in self.tilemap.layers['triggers'].find('coin'):
            Coin((coin.px, coin.py), self.coins)
            totalcoins += 1
        self.tilemap.layers.append(self.coins)

        self.mov_plats = tmx.SpriteLayer()
        for mov_plat in self.tilemap.layers['triggers'].find('mov_plat'):
            MovingPlatform((mov_plat.px, mov_plat.py), self.mov_plats)
        self.tilemap.layers.append(self.mov_plats)

        done = False
        while not done:
            dt = clock.tick(30)

            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    done = True
                if self.player.rect.y > 950 and event.type == pygame.MOUSEBUTTONDOWN:
                    self.main(screen)
                if event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_LALT:
                        self.main(screen)

            self.tilemap.update(dt / 1000., self)
            screen.blit(background, (0, 0))
            self.tilemap.draw(screen)

            #blitting coin tally
            coin_text = font.render(
                "Coins: " + str(self.player.coin_tally) + "/" +
                str(totalcoins), True, (255, 255, 255))
            screen.blit(coin_text, [530, 0])

            pygame.display.flip()

        pygame.quit()
コード例 #48
0
ファイル: main.py プロジェクト: arturbalabanov/hacksym
    def main(self, screen):
        clock = pygame.time.Clock()
        sprites = pygame.sprite.Group()

        EVERY_SECOND = pygame.USEREVENT + 1
        EVERY_TEN_SECONDS = pygame.USEREVENT + 2
        second = 1000  # milliseconds
        pygame.time.set_timer(EVERY_SECOND, second)
        pygame.time.set_timer(EVERY_TEN_SECONDS, second*5)

        self.panel = Panel((170, 170, 170))
        self.tilemap = tmx.load('map.tmx', screen.get_size())
        self.sprites = tmx.SpriteLayer()

        start_cell = self.tilemap.layers['triggers'].find('player')[0]
        self.player = Player((start_cell.px, start_cell.py),
                             6, 6, 7, self.sprites)

        mentor_spawn_points = self.tilemap.layers['triggers'].find('mentor')

        self.tilemap.layers.append(self.sprites)

        self.programming_progress = Progressbar(485, 25, 150, 23, self.pr_pr,
                                                (74, 119, 233),
                                                (0, 0, 0), " Programming")
        self.design_progress = Progressbar(485, 75, 150, 23, self.d_pr,
                                           (67, 166, 56),
                                           (0, 0, 0), " Design")
        self.idea_progress = Progressbar(485, 125, 150, 23, self.i_pr,
                                         (255, 128, 0),
                                         (0, 0, 0), " Idea")
        self.player_programming_skill = pygame.Rect(485, 200, 150, 23)

        self.popup = Popup((255, 128, 0), "", show=False)

        mentor_exists = False
        while 1:
            dt = clock.tick(Options.FPS)

            place = 1
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    sys.exit(0)
                if event.type == EVERY_SECOND:
                    self.programming_progress.update(0.3)
                    self.design_progress.update(0.4)
                if event.type == EVERY_SECOND:
                    if random.randint(0, 100) < 80:
                        if not mentor_exists:
                            mc = mentor_spawn_points[random.randint(0, 3)]
                            self.m = Mentor((mc.px, mc.py), mentor_spawn_points,
                                            self.sprites)
                            mentor_exists = True
                        else:
                            self.m.change_to_random_place()
                if event.type == pygame.MOUSEBUTTONDOWN:
                    x, y = event.pos
                    if self.popup.rect.collidepoint(x, y):
                        self.popup.show = False

            if mentor_exists:
                last = self.player.rect.copy()
                new = self.player.rect
                cell = self.m.rect
                if last.colliderect(cell):
                    self.popup = self.m.visited(self.player)

            self.tilemap.update(dt / 1000., self)
            sprites.update(dt / 1000., self)
            screen.fill((100, 100, 100))
            self.panel.draw(screen)
            sprites.draw(screen)
            self.tilemap.draw(screen)
            self.panel.draw(screen)
            self.programming_progress.draw(screen)
            self.design_progress.draw(screen)
            self.idea_progress.draw(screen)
            self.popup.draw(screen)
            pygame.display.flip()
コード例 #49
0
ファイル: Game.py プロジェクト: itsmekaran/zombiekilll
    def main(self, screen, level):
        clock = pygame.time.Clock()
        self.level = level
        if self.level == 1:
            filename = "layer1.tmx"
        elif self.level == 2:
            filename = "layer2.tmx"
        elif self.level == 3:
            filename = "layer3.tmx"
        background = pygame.image.load('background.png')
        self.tilemap = tmx.load(filename, screen.get_size())
        self.sprites = tmx.SpriteLayer()
        self.tilemap.layers.append(self.sprites)
        start_cell = self.tilemap.layers['triggers'].find('player')[0]
        self.player = Player((start_cell.px, start_cell.py), self.sprites)
        self.guns = tmx.SpriteLayer()
        self.tilemap.layers.append(self.guns)
        self.screen = screen
        self.zombie_count = 0

        # add an enemy for each "enemy" trigger in the map
        for gun in self.tilemap.layers['triggers'].find('guns'):
            Gun((gun.px, gun.py), self.guns)

        self.zombies = tmx.SpriteLayer()
        self.tilemap.layers.append(self.zombies)

        for zombie in self.tilemap.layers['triggers'].find('zombie'):
            category = zombie["zombie"]
            zombie_range = zombie["range"]
            zombie_power = int(zombie["power"])
            zombie_damage = float(zombie["damage"])
            zombie_shoot = zombie["can_shoot"]
            Zombie((zombie.px, zombie.py), category, zombie_range,
                   zombie_power, zombie_damage, zombie_shoot, self.zombies)
            self.zombie_count += 1

        self.spikes = tmx.SpriteLayer()
        self.tilemap.layers.append(self.spikes)
        for spike in self.tilemap.layers['triggers'].find('spike'):
            spike_width = spike["width"]
            spike_damage = float(spike["damage"])
            spike_type = spike["spike"]
            Spike((spike.px, spike.py), spike_width, spike_damage, spike_type,
                  self.spikes)

        self.health = tmx.SpriteLayer()
        self.tilemap.layers.append(self.health)
        for life in self.tilemap.layers['triggers'].find('life'):
            life_val = float(life["val"])
            Health((life.px, life.py), life_val, self.health)

        self.bosses = tmx.SpriteLayer()
        self.tilemap.layers.append(self.bosses)

        for boss in self.tilemap.layers['triggers'].find('boss'):
            category = boss["boss"]
            zombie_range = boss["range"]
            zombie_power = int(boss["power"])
            zombie_damage = float(boss["damage"])
            zombie_shoot = boss["can_shoot"]
            boss_object = Boss((boss.px, boss.py), category, zombie_range,
                               zombie_power, zombie_damage, zombie_shoot,
                               self.bosses)
        # sounds
        self.jump = pygame.mixer.Sound('sounds\\jump.wav')
        self.shoot = pygame.mixer.Sound('sounds\\shoot.wav')
        self.boss_shoot = pygame.mixer.Sound('sounds\\boss_shoot.wav')
        global event
        while 1:

            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    pygame.quit()
                    quit()
                    return "quit"
            dt = clock.tick(30)
            self.tilemap.update(dt / 1000., self, event)
            screen.blit(background, (0, 0))
            self.tilemap.draw(screen)
            self.player.draw_strength(screen)
            z_count = self.zombie_count - self.player.zombie_kill
            self.player.draw_progress(screen, self.level, z_count)
            if self.level == 3:
                boss_object.boss_health(screen)
                if boss_object.boss_kill == 1:
                    return "you win"
            pygame.display.flip()
            if self.player.level_end == 1:
                return "next_level"

            if self.player.is_dead:
                return "dead"
コード例 #50
0
ファイル: poke.py プロジェクト: yeonjekim132/gamedev
            self.image = self.image_default.copy()
            self.image.scroll(-1 * self.width * self.frame_count, 0)
            self.time_count = 0
            self.frame_count += 1
            if self.frame_count == self.frames:
                self.frame_count = 0

# initialize pygame
pygame.init()
# initialize sound - remove if you're not using sound
pygame.mixer.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("My Game")
clock = pygame.time.Clock()

tilemap = tmx.load("town.tmx", screen.get_size())
players = tmx.SpriteLayer()
objects = tmx.SpriteLayer()
# animated sprites here
for cell in tilemap.layers['sprites'].find('src'):
    SpriteLoop((cell.px, cell.py), cell, objects)
tilemap.layers.append(objects)
# player sprite
start_cell = tilemap.layers['triggers'].find('playerStart')[0]
player = Player((start_cell.px, start_cell.py), start_cell['playerStart'], players)
tilemap.layers.append(players)
tilemap.set_focus(player.rect.x, player.rect.y)

running = True
while running:
    dt = clock.tick(FPS)
コード例 #51
0
ファイル: map.py プロジェクト: tsao-ethan/ice-emblem
    def __init__(self, map_path, **kwargs):
        """
        
        """
        super().__init__(
            wait=False,
            bg_image=resources.load_image("old-paper.jpg").convert(),
            bg_size='cover',
            layout_width=room.LayoutParams.FILL_PARENT,
            layout_height=room.LayoutParams.FILL_PARENT,
            **kwargs)

        self.tilemap = tmx.load(map_path, self.rect.size, self.rect.topleft)

        self.zoom = self.tilemap.zoom = 2
        self.tw, self.th = (self.tilemap.tile_width, self.tilemap.tile_height)
        self.w, self.h = self.tilemap.width, self.tilemap.height

        self.terrains = {}
        self.sprites = tmx.SpriteLayer()

        yaml_units = utils.parse_yaml(resources.DATA_PATH / 'units.yml', unit)
        yaml_weapons = utils.parse_yaml(resources.DATA_PATH / 'weapons.yml',
                                        item)

        teams = {}

        for layer in self.tilemap.layers:
            if isinstance(
                    layer,
                    tmx.ObjectLayer):  # layer can be an ObjectLayer or a Layer
                c = layer.color
                layer.visible = False  # don't draw squares
                color = (int(c[1:3], base=16), int(c[3:5], base=16),
                         int(c[5:7], base=16))  # from '#RGB' to (R,G,B)
                units = {}
                for obj in layer.objects:
                    if obj.type == 'unit':
                        units[obj.name] = yaml_units[obj.name]
                        units[
                            obj.
                            name].coord = obj.px // self.tw, obj.py // self.th
                        weapon = obj.properties.get('weapon', None)
                        if weapon:
                            try:
                                units[obj.name].give_weapon(
                                    yaml_weapons[weapon])
                            except KeyError:
                                logging.warning("Weapon %s not found", weapon)
                relation = layer.properties['relation']
                boss = yaml_units[layer.properties['boss']]

                def get(key):
                    v = layer.properties.get(key, None)
                    return str(resources.MUSIC_PATH / v) if v else None

                music = {
                    'map': get('map_music'),
                    'battle': get('battle_music')
                }
                if layer.properties.get('AI', None) is None:
                    teams[color] = unit.Team(layer.name, color, relation,
                                             list(units.values()), boss, music)
                else:
                    teams[color] = ai.AI(layer.name, color, relation,
                                         list(units.values()), boss, music)

        for layer in self.tilemap.layers:
            if isinstance(layer, tmx.ObjectLayer):
                for obj in layer.objects:
                    u = yaml_units[obj.name]
                    team = teams[u.team.color]
                    UnitSprite(self.tilemap, u, team, self.sprites)

        self.units_manager = unit.UnitsManager(list(teams.values()))

        for layer in reversed(self.tilemap.layers):
            if isinstance(layer, tmx.Layer):
                for cell in layer:
                    coord = cell.x, cell.y
                    units = self.units_manager.get_units(coord=coord)
                    _unit = units[0] if units else None
                    if coord not in self.terrains and cell.tile is not None:
                        self.terrains[coord] = Terrain(cell.tile, _unit)

        cursor_layer = tmx.SpriteLayer()
        self.cursor = Cursor(self.tilemap, resources.load_image('cursor.png'),
                             cursor_layer)

        arrow_layer = tmx.SpriteLayer()
        self.arrow = Arrow(self.tilemap, resources.load_image('arrow.png'),
                           arrow_layer)

        highlight_layer = tmx.SpriteLayer()
        self.highlight = CellHighlight(self.tilemap, highlight_layer)

        self.tilemap.layers.append(highlight_layer)
        self.tilemap.layers.append(self.sprites)
        self.tilemap.layers.append(arrow_layer)
        self.tilemap.layers.append(cursor_layer)

        self.tilemap.set_focus(self.tilemap.view_w // 2,
                               self.tilemap.view_h // 2)

        self.prev_sel: Union[None, Coord] = None
        self.curr_sel: Union[None, Coord] = None
        self.move_area: List[Coord] = []
        self.attack_area: List[Coord] = []

        # Scroll speed
        self.vx, self.vy = 0, 0

        self.path = Pathfinder(self)
        self.return_path = None  # stores the path to undo a move
コード例 #52
0
# Demo written by RenfredH04
exec(open("importer.py").read())  # Add tmx to path (ignore this)

import pygame
import tmx

# Initialize pygame and create a 500x500 display
pygame.init()
screen = pygame.display.set_mode((500, 500))

# tmx.load parses the myMap.tmx file and returns a tilemap with all of
# the appropriate attributes. Note you must also include the viewport size.
tilemap = tmx.load('simpleDemo.tmx', screen.get_size())

# Set the focus of the tilemap view to an x, y coordinate. Usually this
# would be set to the starting position of the main player's sprite.
tilemap.set_focus(0, 0)
clock = pygame.time.Clock()

while 1:
    dt = clock.tick(30)

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            exit()

    # tilemap.update calls the update method on each layer in the map.
    # The update method can be customized for each layer to include logic
    # for animating sprite positions, and detecting collisions .
    tilemap.update(dt)
    # Fill the screen with an R,G,B color to erase the previous drawings
コード例 #53
0
    def main(self, screen):
        self.screen = screen

        # grab a clock so we can limit and measure the passing of time
        clock = pygame.time.Clock()

        # we draw the background as a static image so we can just load it in the
        # main loop
        background = pygame.image.load('background.png')

        # load our tilemap and set the viewport for rendering to the screen's
        # size
        self.tilemap = tmx.load('scroller.tmx', screen.get_size())

        # add a layer for our sprites controlled by the tilemap scrolling
        self.sprites = tmx.SpriteLayer()
        self.tilemap.layers.append(self.sprites)
        # fine the player start cell in the triggers layer
        start_cell = self.tilemap.layers['triggers'].find('player')[0]
        # use the "pixel" x and y coordinates for the player start
        self.player = Player((start_cell.px, start_cell.py), self.sprites)

        # add a separate layer for enemies so we can find them more easily later
        self.enemies = tmx.SpriteLayer()
        self.tilemap.layers.append(self.enemies)

        # load the sound effects used in playing a level of the game
        self.jump = pygame.mixer.Sound('jump.wav')
        self.shoot = pygame.mixer.Sound('shoot.wav')
        self.explosion = pygame.mixer.Sound('explosion.wav')

        # flag to allow us to detect when the player completes the level
        self.won = False

        # start the view focus at the player spawn point
        view_x = start_cell.px
        while 1:
            # limit updates to 30 times per second and determine how much time
            # passed since the last update; convert the milliseconds value to
            # seconds
            dt = clock.tick(30) / 1000.

            # handle basic game events; terminate this main loop if the window
            # is closed or the escape key is pressed
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    return
                if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
                    return

            # move the view at a fixed rate; round to int so we don't introduce
            # any floating-point accumulation problems
            view_x += int(100 * dt)
            self.tilemap.set_focus(view_x, start_cell.py)

            # update the tilemap and everything in it passing the elapsed time
            # since the last update (in seconds) and this Game object
            self.tilemap.update(dt, self)

            # add an enemy for each "enemy" trigger that has been exposed
            for cell in self.tilemap.layers['triggers'].collide(
                    self.tilemap.viewport, 'enemy'):
                # delete the enemy trigger so we don't make another one
                del cell['enemy']
                Enemy((cell.px + 32, cell.py), self.enemies)

            # construct the scene by drawing the background and then the rest of
            # the game imagery over the top
            screen.blit(background, (0, 0))
            self.tilemap.draw(screen)
            pygame.display.flip()

            # terminate this main loop if the player dies; a simple change here
            # could be to replace the "print" with the invocation of a simple
            # "game over" scene
            if self.player.is_dead:
                print 'YOU DIED'
                return

            # terminate this main loop if the player wins
            if self.won:
                print 'YOU WIN'
                return
コード例 #54
0
import tmx
import sys
import time
from tmx import TileMap

if not pygame.font: print('Warning, fonts disabled')
if not pygame.mixer: print ('Warning, sound disabled')
condition = True
pygame.init()
size = width, height = 640, 480
screen = pygame.display.set_mode(size)
clock = pygame.time.Clock()
black =(0,0,0)
white =(256,256,256)

mariomap = tmx.load("untitled.tmx", screen.get_size())
stand = pygame.image.load("stand.png").convert_alpha()
run = pygame.image.load("run0.png").convert_alpha()
run1 = pygame.image.load("run1.png").convert_alpha()
jump = pygame.image.load("jump.png").convert_alpha()
mario_x =run.get_width()
mario_y =run.get_height()
stand =pygame.transform.scale(stand ,(run.get_width(),run.get_height()))
jump =pygame.transform.scale(jump ,(run.get_width(),run.get_height()))
run1 = pygame.transform.scale(run1,(run.get_width(),run.get_height()))
a = 100
b=100
b_change =0
g = 0.5
s =0
oblay = mariomap.layers["Triggers"]
コード例 #55
0
ファイル: main.py プロジェクト: vavan/OurFirstGame
def load_map(screen):
    tilemap = tmx.load('our_first_map2.tmx', screen.get_size())
    tilemap.set_focus(0, 0)
    return tilemap
コード例 #56
0
    def main(self, screen):
        # grab a clock so we can limit and measure the passing of time
        clock = pygame.time.Clock()

        # we draw the background as a static image so we can just load it in the
        # main loop
        background = pygame.image.load('background.png')

        # load our tilemap and set the viewport for rendering to the screen's
        # size
        self.tilemap = tmx.load('map-enemies.tmx', screen.get_size())

        # add a layer for our sprites controlled by the tilemap scrolling
        self.sprites = tmx.SpriteLayer()
        self.tilemap.layers.append(self.sprites)
        # fine the player start cell in the triggers layer
        start_cell = self.tilemap.layers['triggers'].find('player')[0]
        # use the "pixel" x and y coordinates for the player start
        self.player = Player((start_cell.px, start_cell.py), self.sprites)

        # add a separate layer for enemies so we can find them more easily later
        self.enemies = tmx.SpriteLayer()
        self.tilemap.layers.append(self.enemies)
        # add an enemy for each "enemy" trigger in the map
        for enemy in self.tilemap.layers['triggers'].find('enemy'):
            Enemy((enemy.px, enemy.py), self.enemies)

        # load the sound effects used in playing a level of the game
        self.jump = pygame.mixer.Sound('jump.wav')
        self.shoot = pygame.mixer.Sound('shoot.wav')
        self.explosion = pygame.mixer.Sound('explosion.wav')

        while 1:
            # limit updates to 30 times per second and determine how much time
            # passed since the last update
            dt = clock.tick(30)

            # handle basic game events; terminate this main loop if the window
            # is closed or the escape key is pressed
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    return
                if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
                    return

            # update the tilemap and everything in it passing the elapsed time
            # since the last update (in seconds) and this Game object
            self.tilemap.update(dt / 1000., self)
            # construct the scene by drawing the background and then the rest of
            # the game imagery over the top
            screen.blit(background, (0, 0))
            self.tilemap.draw(screen)
            pygame.display.flip()

            # terminate this main loop if the player dies; a simple change here
            # could be to replace the "print" with the invocation of a simple
            # "game over" scene
            if self.player.is_dead:
                print 'YOU DIED'
                return

            if self.tilemap.layers['triggers'].collide(self.player.rect,
                                                       'exit'):
                print 'YOU WIN'
                return
コード例 #57
0
    def while_kamehouse_in(self):
        """ Boucle sur la map KamehouseIn """
        tilemap = tmx.load('ressources/maps/kamehouse/house/map.tmx',
                           self.screen.get_size())  # Import de la map
        collision_total = tilemap.layers['evenements'].find(
            'collision')  # Récupère toutes les collisions
        exit_lvl = tilemap.layers['evenements'].find(
            'exit')  # Récupère toutes les collisions pour quitter le niveau
        collision_tortue = tilemap.layers['evenements'].find(
            'collision_tortue')  # Récupère les collisions avec le personnage

        move = None  # Aucun déplacement n'est demandé par défaut
        old_pos_sprite = 'Up'  # Position par défaut du personnage (vers le haut)
        img_perso = Sprite(
        )  # Défini la classe s'occupant des images des personnages
        player = Player(tilemap, self.width, self.height, img_perso,
                        old_pos_sprite)  # Appelle la class du joueur
        deplacer = Move(player, self.avancer,
                        collision_total)  # Appelle la class de déplacement
        dialogue = Interact(self.screen)  # Défini la classe de dialogue
        inventory = Inventory(self.screen)  # Défini la classe de l'inventaire
        pygame.time.set_timer(pygame.USEREVENT,
                              300)  # Temps de mise à jour des Sprites (300 ms)

        while self.while_map_kamehouse_in:  # Boucle infinie du jeu
            collide_exit = CollisionController(
                player, exit_lvl)  # Class de collision pour quitter le niveau
            collide_tortue = CollisionController(
                player, collision_tortue
            )  # Class de collision pour parler avec Tortue Géniale

            if collide_exit.collision(
            ):  # Si la collision avec la porte a lieu
                self.while_map_kamehouse_in = False  # Arrête la boucle de la map KamehouseIn
                self.while_map_kamehouse = True  # Permet de lancer la boucle de la map Kamehouse
                Niveau.LVL = 'while_map_kamehouse'  # Nouveau niveau de jeu

            for event in pygame.event.get(
            ):  # Vérifie toutes les actions du joueur
                if event.type == pygame.QUIT:  # Clique pour quitter le jeu
                    self.while_map_kamehouse_in = False  # Quitte le processus python
                    Niveau.WHILE_GAME = False  # Ferme la boucle d'importation
                elif event.type == pygame.USEREVENT:  # Déplacement du joueur
                    player.sprite_player = img_perso.animate_sprite(
                        move, old_pos_sprite)  # Anime le joueur
                elif event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE and collide_tortue.collision(
                ) and not Niveau.DIALOGUE:
                    # Si la touche espace est préssée, qu'il y a une collision et qu'il n'y a pas de boite de dialogue
                    Niveau.DIALOGUE = True  # On défini la variable pour l'afficher
                elif event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE and Niveau.DIALOGUE:
                    # Si la touche espace est préssée et qu'il n'y a une boite de dialogue affichée
                    if Niveau.MISSION_01 == 0:
                        calcul = ceil(
                            len(txt_mission01_01) / 4
                        )  # Calcul le nombre de page en fonction du dialogue
                    elif Niveau.MISSION_01 == 50:
                        calcul = ceil(
                            len(txt_mission01_03) / 4
                        )  # Calcul le nombre de page en fonction du dialogue
                    elif Niveau.MISSION_01 == 100:
                        calcul = ceil(
                            len(txt_mission01_04) / 4
                        )  # Calcul le nombre de page en fonction du dialogue

                    if Niveau.PAGE == calcul:  # Nombre de page maximum des dialogues est atteint
                        Niveau.DIALOGUE = False  # On ferme la boite de dialogue
                        Niveau.PAGE = 1  # Redéfini la page à 1

                        if Niveau.MISSION_01 == 50:  # Si la mission est à 50%
                            Niveau.MISSION_01 = 100  # Évolue l'état de la mission 50 à 100% achevée
                            Niveau.INVENTORY.remove(
                                'boulecristal')  # Retire l'objet obtenu
                    else:  # Pas encore toutes les pages sont lues
                        Niveau.PAGE = Niveau.PAGE + 1  # Ajoute +1 aux pages

            if not Niveau.DIALOGUE:  # Aucune boite de dialogue n'est affichée
                if pygame.key.get_pressed()[pygame.K_DOWN]:
                    # Premier déplacement du personnage : il n'y a pas encore de mouvement ou la touche correspond pas
                    direction_deplacement = 'Down'  # Variable de modification rapide
                    if move is None or move != direction_deplacement:
                        player.sprite_player = img_perso.select_sprite(
                            1, 0)  # Mise à jour première du Sprite
                        move = direction_deplacement  # Actualisation de la variable déplacement
                    if Move.COLLIDED:
                        move = None  # Empêche le déplacement du Sprite s'il y a une collision
                    old_pos_sprite = direction_deplacement  # Ancienne position du joueur pour quand il s'arrêtera
                    deplacer.move_player(player.player.copy(),
                                         [0, self.avancer],
                                         direction_deplacement)  # Déplacement

                elif pygame.key.get_pressed()[pygame.K_UP]:
                    direction_deplacement = 'Up'
                    if move is None or move != direction_deplacement:
                        player.sprite_player = img_perso.select_sprite(1, 3)
                        move = direction_deplacement
                    if Move.COLLIDED:
                        move = None  # Empêche le déplacement du Sprite s'il y a une collision
                    old_pos_sprite = direction_deplacement
                    deplacer.move_player(player.player.copy(),
                                         [0, -self.avancer],
                                         direction_deplacement)

                elif pygame.key.get_pressed()[pygame.K_LEFT]:
                    direction_deplacement = 'Left'
                    if move is None or move != direction_deplacement:
                        player.sprite_player = img_perso.select_sprite(1, 1)
                        move = direction_deplacement
                    if Move.COLLIDED:
                        move = None  # Empêche le déplacement du Sprite s'il y a une collision
                    old_pos_sprite = direction_deplacement
                    deplacer.move_player(player.player.copy(),
                                         [-self.avancer, 0],
                                         direction_deplacement)

                elif pygame.key.get_pressed()[pygame.K_RIGHT]:
                    direction_deplacement = 'Right'
                    if move is None or move != direction_deplacement:
                        player.sprite_player = img_perso.select_sprite(1, 2)
                        move = direction_deplacement
                    if Move.COLLIDED:
                        move = None  # Empêche le déplacement du Sprite s'il y a une collision
                    old_pos_sprite = direction_deplacement
                    deplacer.move_player(player.player.copy(),
                                         [self.avancer, 0],
                                         direction_deplacement)
                else:
                    move = None  # Arrêt de déplacement du personnage
            else:  # Une boite de dialogue est affichée
                move = None  # Arrêt de déplacement du personnage

            self.clock.tick(self.fps)  # Restreint les FPS
            tilemap.set_focus(
                player.player.x,
                player.player.y)  # Coordonnées du joueur par rapport aux bords
            tilemap.draw(self.screen)  # Affiche le fond
            self.screen.blit(
                player.sprite_player,
                (player.x, player.y))  # Affiche le joueur sur le fond

            if Niveau.DIALOGUE:  # Si la variable de dialogue est définie
                if Niveau.MISSION_01 == 0:  # La mission n'a pas encore commencée
                    dialogue.show_box(
                        txt_mission01_01
                    )  # Affiche le dialogue pour la mission 1
                elif Niveau.MISSION_01 == 50:
                    dialogue.show_box(
                        txt_mission01_03
                    )  # Affiche le dialogue pour la mission 1
                elif Niveau.MISSION_01 == 100:
                    dialogue.show_box(
                        txt_mission01_04
                    )  # Affiche le dialogue pour la mission 1

            if Niveau.INVENTORY:  # Si l'inventaire n'est pas vide
                inventory.show_item()  # Affiche l'inventaire du joueur

            pygame.display.flip()  # Met à jour l'écran
コード例 #58
0
ファイル: worldtown.py プロジェクト: Dylan3250/PyDragon
    def while_town(self):
        """ Boucle sur la map WorldTown """
        tilemap = tmx.load('ressources/maps/worldtown/world/map.tmx',
                           self.screen.get_size())  # Import de la map
        collision_total = tilemap.layers['evenements'].find(
            'collision')  # Récupère toutes les collisions

        # Récupère toutes les collisions pour quitter le niveau
        exit_lvl = tilemap.layers['evenements'].find(
            'exit')  # Intérieur de la maison
        goto_kamehouse = tilemap.layers['evenements'].find(
            'exit_gotokamehouse')  # Vers l'île

        move = None  # Aucun déplacement n'est demandé par défaut
        old_pos_sprite = 'Down'  # Position par défaut du personnage (vers le bas)
        img_perso = Sprite(
        )  # Défini la classe s'occupant des images des personnages
        player = Player(tilemap, self.width, self.height, img_perso,
                        old_pos_sprite)  # Appelle la class du joueur
        deplacer = Move(player, self.avancer,
                        collision_total)  # Appelle la class de déplacement
        inventory = Inventory(self.screen)  # Défini la classe de l'inventaire
        pygame.time.set_timer(pygame.USEREVENT,
                              300)  # Temps de mise à jour des Sprites (300 ms)

        if Niveau.COORDONNEE_TOWN:  # S'il y a des données enregistrées (= sort de la maison)
            player.player.x = Niveau.COORDONNEE_TOWN[
                0]  # On défini les nouvelles coordonnées en X
            player.player.y = Niveau.COORDONNEE_TOWN[
                1]  # On défini les nouvelles coordonnées en Y

        while self.while_map_town:  # Boucle infinie du jeu
            collide_exit = CollisionController(
                player, exit_lvl
            )  # Appelle la class de collision pour quitter le niveau
            if collide_exit.collision(
            ):  # Si la collision avec la porte a lieu
                self.while_map_town = False  # Arrête la boucle de la map Kamehouse
                self.while_map_town_in = True  # Permet de lancer la boucle de la map Kamehouse_in
                Niveau.LVL = 'while_map_town_in'  # Nouvelle map appellée
                Niveau.COORDONNEE_TOWN = [
                    1250, 1700
                ]  # Localisation d'apparition après être sorti de la maison

            collide_goto_world = CollisionController(
                player, goto_kamehouse
            )  # Appelle la class de collision pour quitter le niveau
            if collide_goto_world.collision(
            ):  # Si la collision avec la porte a lieu
                self.while_map_town = False  # Arrête la boucle de la map Kamehouse
                self.while_map_kamehouse = True  # Permet de lancer la boucle de la map Kamehouse_in
                Niveau.LVL = 'while_map_kamehouse'  # Nouvelle map appellée
                Niveau.COORDONNEE_TOWN = [
                ]  # Supprime les données pour permettre une apparition par défaut

            for event in pygame.event.get(
            ):  # Vérifie toutes les actions du joueur
                if event.type == pygame.QUIT:  # Clique pour quitter le jeu
                    self.while_map_town = False  # Quitte le processus python
                    Niveau.WHILE_GAME = False  # Ferme la boucle d'importation
                elif event.type == pygame.USEREVENT:  # Déplacement du joueur
                    player.sprite_player = img_perso.animate_sprite(
                        move, old_pos_sprite)

            if pygame.key.get_pressed()[pygame.K_DOWN]:
                # Premier déplacement du personnage : il n'y a pas encore de mouvement ou la touche ne correspond pas
                direction_deplacement = 'Down'  # Variable de modification rapide
                if move is None or move != direction_deplacement:
                    player.sprite_player = img_perso.select_sprite(
                        1, 0)  # Mise à jour première du Sprite
                    move = direction_deplacement  # Actualisation de la variable déplacement
                if Move.COLLIDED:
                    move = None  # Empêche le déplacement du Sprite s'il y a une collision
                old_pos_sprite = direction_deplacement  # Ancienne position du joueur pour quand il s'arrêtera
                deplacer.move_player(player.player.copy(), [0, self.avancer],
                                     direction_deplacement)  # Déplacement

            elif pygame.key.get_pressed()[pygame.K_UP]:
                direction_deplacement = 'Up'
                if move is None or move != direction_deplacement:
                    player.sprite_player = img_perso.select_sprite(1, 3)
                    move = direction_deplacement
                if Move.COLLIDED:
                    move = None  # Empêche le déplacement du Sprite s'il y a une collision
                old_pos_sprite = direction_deplacement
                deplacer.move_player(player.player.copy(), [0, -self.avancer],
                                     direction_deplacement)

            elif pygame.key.get_pressed()[pygame.K_LEFT]:
                direction_deplacement = 'Left'
                if move is None or move != direction_deplacement:
                    player.sprite_player = img_perso.select_sprite(1, 1)
                    move = direction_deplacement
                if Move.COLLIDED:
                    move = None  # Empêche le déplacement du Sprite s'il y a une collision
                old_pos_sprite = direction_deplacement
                deplacer.move_player(player.player.copy(), [-self.avancer, 0],
                                     direction_deplacement)

            elif pygame.key.get_pressed()[pygame.K_RIGHT]:
                direction_deplacement = 'Right'
                if move is None or move != direction_deplacement:
                    player.sprite_player = img_perso.select_sprite(1, 2)
                    move = direction_deplacement
                if Move.COLLIDED:
                    move = None  # Empêche le déplacement du Sprite s'il y a une collision
                old_pos_sprite = direction_deplacement
                deplacer.move_player(player.player.copy(), [self.avancer, 0],
                                     direction_deplacement)
            else:
                move = None  # Arrêt de déplacement du personnage

            self.clock.tick(self.fps)  # Restreint les FPS
            tilemap.set_focus(
                player.player.x,
                player.player.y)  # Coordonnées du joueur par rapport aux bords
            tilemap.draw(self.screen)  # Affiche le fond
            self.screen.blit(
                player.sprite_player,
                (player.x, player.y))  # Affiche le joueur sur le fond

            if Niveau.INVENTORY:  # Si l'inventaire n'est pas vide
                inventory.show_item()  # Affiche l'inventaire du joueur

            pygame.display.flip()  # Met à jour l'écran
コード例 #59
0
ファイル: smb.py プロジェクト: ikcilabd/pySMB
    def main(self, screen):
        clock = pygame.time.Clock()

        players_name = 'mario'

        dt = clock.tick(30)

        self.tilemap = tmx.load('11.tmx', screen.get_size())
        #self.tilemap = tmx.load('11.tmx', (360,240))
        self.sprites = tmx.SpriteLayer()

        start_cell = self.tilemap.layers['triggers'].find('player')[0]
        self.player = Player((start_cell.px, start_cell.py), self.sprites)
        self.tilemap.layers.append(self.sprites)

        initial_blink_surface = self.tilemap.tilesets[4].surface.copy()
        blink_level = 0
        coin_blink = 0

        self.player_lives = 3
        self.player_coins = 0
        self.player_score = 0
        self.game_time = 400
        self.game_world = 1
        self.game_level = 1

        self.enemy_list = []
        for cell in self.tilemap.layers['enemies'].objects:
            self.enemy_list.append(
                Enemy((cell.px, cell.py), cell.properties, self.sprites))

        font_size = 8
        self.set_font_images(font_size)

        self.css = spritesheet.spritesheet('coin_tileset.png')
        coin_image_list = [
            self.css.image_at((64, 0, 8, 8), colorkey=-1),
            self.css.image_at((72, 0, 8, 8), colorkey=-1),
            self.css.image_at((80, 0, 8, 8), colorkey=-1)
        ]

        self.point_list = []
        self.point_float = 40

        self.bumpable_list = []

        n = 0
        while 1:

            clock.tick(30)
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    return
                if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
                    return

            ################Blinking Question Blocks################
            if n % 3 == 0:

                if blink_level < 6:
                    if blink_level < 3:
                        blink_tile = 4 + blink_level
                        coin_blink = blink_level
                    elif blink_level == 3:
                        blink_tile = 5
                        coin_blink = 1
                    else:
                        blink_tile = 4
                        self.tilemap.tilesets[
                            4].surface = initial_blink_surface  ##gotta do this for some reason
                        coin_blink = 0

                    for cell in self.tilemap.layers['changeables'].find(
                            'question_block'):
                        cell.tile.surface = self.tilemap.tilesets[
                            blink_tile].surface

                    blink_level += 1
                else:
                    blink_level = 0
                    coin_blink = 0

            ########################################################
            if n % 10 == 0 and not self.player.player_dead:
                self.game_time -= 1

            self.tilemap.update(dt / 1000., self)
            screen.fill((92, 148, 252))

            name_start_x = 8
            score_start_x = name_start_x
            time_title_start_x = 184
            time_count_start_x = 192
            lives_count_start_x = 88
            world_title_start_x = 128
            world_count_start_x = 144
            for letter in players_name:
                name_start_x += font_size
                screen.blit(self.letter_image_dict[letter],
                            (name_start_x, font_size))
            for number in str(self.player_score).zfill(6):
                score_start_x += font_size
                screen.blit(self.number_image_list[int(number)],
                            (score_start_x, font_size * 2))
            for letter in 'time':
                time_title_start_x += font_size
                screen.blit(self.letter_image_dict[letter],
                            (time_title_start_x, font_size))
            for number in str(self.game_time).zfill(3):
                time_count_start_x += font_size
                screen.blit(self.number_image_list[int(number)],
                            (time_count_start_x, font_size * 2))

            screen.blit(coin_image_list[coin_blink], (80, 16))
            screen.blit(self.letter_image_dict['by'],
                        (lives_count_start_x, 16))
            for number in str(self.player_coins).zfill(2):
                lives_count_start_x += font_size
                screen.blit(self.number_image_list[int(number)],
                            (lives_count_start_x, font_size * 2))
            for letter in 'world':
                world_title_start_x += font_size
                screen.blit(self.letter_image_dict[letter],
                            (world_title_start_x, font_size))
            screen.blit(self.number_image_list[self.game_world],
                        (world_count_start_x, font_size * 2))
            screen.blit(self.letter_image_dict['dash'],
                        (world_count_start_x + font_size, font_size * 2))
            screen.blit(self.number_image_list[self.game_level],
                        (world_count_start_x + (font_size * 2), font_size * 2))

            for point in self.point_list:
                if point[2] < self.point_float:
                    n = 0
                    if point[1] == '1UP':
                        screen.blit(self.point_image_dict['1UP'],
                                    (point[0][0] +
                                     (n * 4), point[0][1] - point[2]))
                        n += 1
                    else:
                        for number in str(point[1]):
                            screen.blit(self.point_image_dict[int(number)],
                                        (point[0][0] +
                                         (n * 4), point[0][1] - point[2]))
                            n += 1
                    point[2] += 1

            self.tilemap.draw(screen)
            pygame.display.flip()

            n += 1