コード例 #1
0
class Map:
    def __init__(self, mapName):
        mapRes = ResManager().getMapRes(mapName)
        self.mapCord = mapRes[0]
        self.imgDict = mapRes[1]
        self.respLst = mapRes[2]
        self.left = False
        self.right = False
        self.up = False
        self.entities = pygame.sprite.Group()  # Все объекты
        self.platforms = []  # то, во что мы будем врезаться или опираться

    def start(self, display):
        self.display = display
        n = self.randResp()
        self.player = Player(n[0] * PLATFORM_WIDTH, n[1] * PLATFORM_HEIGHT)
        self.entities.add(self.player)

    def update(self, dt):
        self.player.update(self.left, self.right, self.up, self.platforms)

    def event(self, event):
        for e in event.get():
            if e.type == pygame.KEYDOWN and e.key == pygame.K_LEFT:
                self.left = True
            if e.type == pygame.KEYDOWN and e.key == pygame.K_RIGHT:
                self.right = True

            if e.type == pygame.KEYUP and e.key == pygame.K_RIGHT:
                self.right = False
            if e.type == pygame.KEYUP and e.key == pygame.K_LEFT:
                self.left = False

            if e.type == pygame.KEYDOWN and e.key == pygame.K_SPACE:
                up = True
            if e.type == pygame.KEYUP and e.key == pygame.K_SPACE:
                up = False

    def draw(self):
        x = y = 0  # координаты
        for row in self.mapCord:
            for col in row:
                if col == "-":
                    img = pygame.transform.scale(
                        self.imgDict[col], (PLATFORM_WIDTH, PLATFORM_HEIGHT))
                    pf = Platform(x, y, img)
                    self.entities.add(pf)
                    self.platforms.append(pf)
                x += PLATFORM_WIDTH
            y += PLATFORM_HEIGHT
            x = 0
            self.entities.draw(self.display)

    def randResp(self):
        return self.respLst[randrange(len(self.respLst))]
コード例 #2
0
ファイル: Map.py プロジェクト: l0dom/TeeWorlds
class Map:
    def __init__ (self,mapName):
        mapRes = ResManager().getMapRes(mapName)
        self.mapCord=mapRes[0]
        self.imgDict=mapRes[1]
        self.respLst=mapRes[2]
        self.left=False
        self.right=False
        self.up=False
        self.entities = pygame.sprite.Group() # Все объекты
        self.platforms = [] # то, во что мы будем врезаться или опираться


    def start (self,display):
        self.display=display
        n = self.randResp()
        self.player = Player(n[0]*PLATFORM_WIDTH,n[1]*PLATFORM_HEIGHT)
        self.entities.add(self.player)

    def update (self,dt):
        self.player.update(self.left,self.right,self.up,self.platforms)

    def event(self,event):
        for e in event.get():
            if e.type == pygame.KEYDOWN and e.key == pygame.K_LEFT:
               self.left = True
            if e.type == pygame.KEYDOWN and e.key == pygame.K_RIGHT:
               self.right = True

            if e.type == pygame.KEYUP and e.key == pygame.K_RIGHT:
               self.right = False
            if e.type == pygame.KEYUP and e.key == pygame.K_LEFT:
               self.left = False

            if e.type == pygame.KEYDOWN and e.key == pygame.K_SPACE:
                up = True
            if e.type == pygame.KEYUP and e.key == pygame.K_SPACE:
                up = False

    def draw (self):
        x=y=0 # координаты
        for row in self.mapCord:
            for col in row:
                if col == "-":
                    img=pygame.transform.scale(self.imgDict[col],(PLATFORM_WIDTH,PLATFORM_HEIGHT))
                    pf = Platform(x,y,img)
                    self.entities.add(pf)
                    self.platforms.append(pf)
                x+=PLATFORM_WIDTH
            y+=PLATFORM_HEIGHT
            x=0
            self.entities.draw(self.display)

    def randResp (self):
        return self.respLst[randrange(len(self.respLst))]
コード例 #3
0
    def appStarted(self):
        #Initialize the level
        self.margin = 50
        self.extra = 200
        self.rows = (self.height - 2 * self.margin) // Square.width
        self.cols = (self.width + self.extra - 2 * self.margin) // Square.width
        self.endPiece = Square(self.cols - 1, self.rows // 2, self)
        self.obstacles = self.generateObstacles()
        self.startWall = Wall(-100, 0)
        self.endWall = Wall(self.width + self.extra + 10, 0)

        #Initialize the player and enemies
        x0, y0, x1, y1 = self.getCellBounds(self.rows // 2, 0)
        self.player = Player(1000, (x0 + x1) // 2, (y0 + y1) // 2, self)
        self.scrollX = 0
        self.scrollMargin = 50
        self.enemies = self.generateEnemies()
        self.paused = False
        self.canDrawBullet = False
コード例 #4
0
ファイル: Game.py プロジェクト: benedicteb/outcast
    def __init__(self):
        self.FPS = 30
        self.dt = 1. / self.FPS
        pygame.init()
        self.clock = pygame.time.Clock()
        self.sight_radius = 10
        self.width  = (2*self.sight_radius + 1) * World.METER_SIZE + Game.STATUSBAR_OFFSET
        self.height = (2*self.sight_radius + 1) * World.METER_SIZE
        self.screen = pygame.display.set_mode((
            self.width, self.height
        ))
        pygame.display.set_caption('Testing')
        self.world = World(open(resource_path(
            Game.WORLDS_LOCATION, "real_world.board"
        ), 'r'))
        self.world.game = self

        self.player = Player([11, 11], game=self, world=self.world)
        # self.world.add(self.player)
        # self.world.add(Planet([200,200], 500, 30))

        self.placables = [
            Item("Axe", position=[53, 16]),
            Item("Boat", position=[14, 63]),
            Page(PAGE1, position=[19, 11]),
            Page(PAGE2, position=[26, 16]),
            Page(PAGE3, position=[61, 12]),
        ]

        self.npcs = [
            NPC([72, 58], game=self, world=self.world, dialog="This is a page. Maybe you'll learn something, douche.",
                items=[Page(PAGE4, position=None)]),
            NPC([34, 74], game=self, world=self.world, dialog="This is a page. Maybe you'll learn something, douche.",
                items=[Page(PAGE5, position=None)]),
            NPC([63, 84], game=self, world=self.world, dialog="This is a page. Maybe you'll learn something, douche.",
                items=[Page(PAGE6, position=None)]),
            NPC([25, 32], game=self, world=self.world, dialog="This is a page. Maybe you'll learn something, douche.",
                items=[Page(PAGE7, position=None)]),
            NPC([57, 37], game=self, world=self.world, dialog="This is a page. Maybe you'll learn something, douche.",
                items=[Page(PAGE8, position=None)]),
            NPC([31, 51], game=self, world=self.world, dialog="This is a page. Maybe you'll learn something, douche.",
                items=[Page(PAGE9, position=None)]),
            # NPC([0, 2], game=self, world=self.world, dialog="My my, this is fancy!"),
        ]

        self.text_dialog_queue = []
コード例 #5
0
ファイル: Map.py プロジェクト: l0dom/TeeWorlds
 def start (self,display):
     self.display=display
     n = self.randResp()
     self.player = Player(n[0]*PLATFORM_WIDTH,n[1]*PLATFORM_HEIGHT)
     self.entities.add(self.player)
コード例 #6
0
def main():
    pygame.init()
    pygame.display.set_caption("RPG - Louvain-la-Neuve")
    screen = pygame.display.set_mode((960, 640))
    grid_width = 30
    grid_height = 20
    clock = pygame.time.Clock()

    grid = Grid("level.map", screen, (grid_width, grid_height), (0, 0))
    player = Player("res/trainer_running.png", (10, 10), grid, 1)

    screen.blit(grid.background, grid.view_coord)
    player.blit(screen, 1)
    pygame.display.flip()

    current_direction = [0, 0, 0, 0]
    old_current_direction = current_direction.copy()
    grid_offset_x = grid.view_coord[0] % (screen.get_rect().width / grid_width)
    grid_offset_y = grid.view_coord[1] % (screen.get_rect().height /
                                          grid_height)

    #load button and getting his collide zone
    bouton = pygame.image.load("images/sound_icon.png")
    bouton_rect = bouton.get_rect()

    #sound played
    sound_played = True

    #load music
    pygame.mixer.init()
    pygame.mixer.music.load("sound/lln_sound.wav")
    pygame.mixer.music.play(-1, 0.0)
    running = True

    while running:
        screen.blit(grid.background, grid.view_coord)
        player.blit(screen, player.movement(old_current_direction))
        bouton = pygame.transform.scale(bouton, (32, 32))
        screen.blit(bouton, (0, 0))
        pygame.display.flip()
        clock.tick(60)

        print(grid.view_coord)
        grid_offset_x = grid.view_coord[0] % (screen.get_rect().width /
                                              grid_width)
        grid_offset_y = grid.view_coord[1] % (screen.get_rect().height /
                                              grid_height)

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False
            updateDirection(event, current_direction)

        if grid_offset_y + grid_offset_x == 0:
            grid.view_coord = updateViewCoordinates(grid.view_coord,
                                                    current_direction, player)
            old_current_direction = current_direction.copy()
            #player.updatePos()
        else:
            grid.view_coord = updateViewCoordinates(grid.view_coord,
                                                    old_current_direction,
                                                    player)

        ## Si le focus est sur la fenêtre.
        if pygame.mouse.get_focused():
            ## Trouve position de la souris
            x, y = pygame.mouse.get_pos()
            ## S'il y a collision:
            collide = bouton_rect.collidepoint(x, y)

            ## Détecte les clique de souris.
            pressed = pygame.mouse.get_pressed()
            if pressed[0] and collide:  # 0=gauche, 1=milieu, 2=droite
                if sound_played:
                    bouton = pygame.image.load("images/no_sound_icon.png")
                    pygame.mixer.music.stop()
                    sound_played = False
                else:
                    bouton = pygame.image.load("images/sound_icon.png")
                    pygame.mixer.music.play(-1, 0.0)
                    sound_played = True
コード例 #7
0
 def start(self, display):
     self.display = display
     n = self.randResp()
     self.player = Player(n[0] * PLATFORM_WIDTH, n[1] * PLATFORM_HEIGHT)
     self.entities.add(self.player)
コード例 #8
0
class Level(Mode):

    #Takes the values of the number of enemies, how many of each kind, and
    #the number of obstacles
    def __init__(self, enemies, obstacles):
        super().__init__()
        self.numEnemy = enemies[0]
        self.numRanged = enemies[1]
        self.numMortar = enemies[2]
        self.totalEnemies = enemies[0] + enemies[1] + enemies[2]
        self.totalObstacles = obstacles
        Bullet.number = 0

    def appStarted(self):
        #Initialize the level
        self.margin = 50
        self.extra = 200
        self.rows = (self.height - 2 * self.margin) // Square.width
        self.cols = (self.width + self.extra - 2 * self.margin) // Square.width
        self.endPiece = Square(self.cols - 1, self.rows // 2, self)
        self.obstacles = self.generateObstacles()
        self.startWall = Wall(-100, 0)
        self.endWall = Wall(self.width + self.extra + 10, 0)

        #Initialize the player and enemies
        x0, y0, x1, y1 = self.getCellBounds(self.rows // 2, 0)
        self.player = Player(1000, (x0 + x1) // 2, (y0 + y1) // 2, self)
        self.scrollX = 0
        self.scrollMargin = 50
        self.enemies = self.generateEnemies()
        self.paused = False
        self.canDrawBullet = False

    #Generates each type of enemy
    def generateEnemies(self):
        enemies = []
        self.generateEnemyType(enemies, self.numEnemy, 0)
        self.generateEnemyType(enemies, self.numRanged, 1)
        self.generateEnemyType(enemies, self.numMortar, 2)
        return enemies

    #Places the enemies, given a certain type. The counter specifies which enemy
    # is being created
    def generateEnemyType(self, enemies, number, counter):
        for i in range(number):
            while True:
                position = (random.randint(60, self.width + self.extra - 20),
                            random.randint(60, self.height - 60))
                row, col = self.getCell(position[0], position[1])
                overlap = False
                #Checks if the enemy was placed on an obstacle
                if (row, col) in self.positions:
                    overlap = True
                playerRow, playerCol = self.getCell(Player.x, Player.y)
                if (not overlap):
                    #Make a normal enemy
                    if counter % 3 == 0:
                        health = 250
                        enemy = Enemy(health, position, self)
                        enemies.append(enemy)
                    #Make a ranged enemy
                    elif counter % 3 == 1:
                        health = 200
                        enemy = Ranged(health, position, self)
                        enemies.append(enemy)
                    #Make a mortar enemy
                    else:
                        health = 450
                        enemy = Mortar(health, position, self)
                        enemies.append(enemy)
                    break
                else:
                    #Try placing the enemy again
                    continue

    #citation: https://www.cs.cmu.edu/~112/notes/notes-animations-part3.html#sidescrollerExamples
    # Makes the player be seen to simulate the scrolling
    def makePlayerVisible(self):
        # scroll to make player visible as needed
        if (self.player.x < self.scrollX + self.scrollMargin):
            self.scrollX = self.player.x - self.scrollMargin
        if (self.player.x > self.scrollX + self.width - self.scrollMargin):
            self.scrollX = self.player.x - self.width + self.scrollMargin

    #Changes position given the direction
    def movePlayer(self, dx, dy):
        if not self.paused:
            if not self.player.dead:
                tempx, tempy = Player.x, Player.y
                Player.x += dx
                Player.y += dy
                playerRow, playerCol = self.getCell(Player.x, Player.y)
                #Passed the x bounds
                if Player.x <= self.startWall.x0 + Wall.width or Player.x >= self.endWall.x0:
                    Player.x = tempx
                #Passed the y bounds
                if Player.y <= 0 or Player.y >= self.height:
                    Player.y = tempy
                #Hit an obstacle
                if (playerRow, playerCol) in self.positions:
                    Player.x = tempx
                    Player.y = tempy
                #Change the spritecounter to animate the movement
                self.player.movespriteCounter += 1
                playerRow, playerCol = self.getCell(Player.x, Player.y)
                #Advance to next level if all the enemies are dead and player is at the endPiece
                if playerRow == self.endPiece.ry and playerCol == self.endPiece.rx:
                    if len(self.enemies) == 0:
                        self.player.levelCleared = True
                        self.app.level += 1
                        if self.app.level <= len(self.app.levelList):
                            print(f'loading Level {self.app.level}')
                            Bullet.number = 0
                            self.app.setActiveMode(
                                self.app.levelList[self.app.level - 1])
                        else:
                            self.app.setActiveMode(self.app.endScreen)
                self.makePlayerVisible()

    #citation: https://www.cs.cmu.edu/~112/notes/notes-animations-part1.html#exampleGrids
    def getCell(self, x, y):
        gridWidth = self.width + self.extra - 2 * self.margin
        gridHeight = self.height - 2 * self.margin
        cellWidth = gridWidth / self.cols
        cellHeight = gridHeight / self.rows
        row = int((y - self.margin) / cellHeight)
        col = int((x - self.margin) / cellWidth)

        return (row, col)

    #citation:https://www.cs.cmu.edu/~112/notes/notes-animations-part1.html#exampleGrids
    def getCellBounds(self, row, col):
        gridWidth = self.width + self.extra - 2 * self.margin
        gridHeight = self.height - 2 * self.margin
        x0 = self.margin + gridWidth * col / self.cols
        x1 = self.margin + gridWidth * (col + 1) / self.cols
        y0 = self.margin + gridHeight * row / self.rows
        y1 = self.margin + gridHeight * (row + 1) / self.rows
        return (x0, y0, x1, y1)

    #citation: https://www.cs.cmu.edu/~112/notes/notes-recursion-part2.html#memoization
    def memoized(f):
        import functools
        cachedResults = dict()

        @functools.wraps(f)
        def wrapper(*args):
            if args not in cachedResults:
                cachedResults[args] = f(*args)
            return cachedResults[args]

        return wrapper

    #creates the obstacles and makes sure they aren't overlapping and
    #checks if there is a solution from one end of the level to the other end
    def generateObstacles(self):
        obstacleList = []
        numObstacles = self.totalObstacles
        i = 0
        tries = 0
        while (tries < 1000):
            while (i < numObstacles):
                #Randomly place the obstacle
                rx = random.randint(0, self.cols - 1)
                ry = random.randint(0, self.rows - 1)
                square = Square(rx, ry, self)
                intersects = False
                #Check if the obstacle is overlapping an existing obstacle
                for oSquare in obstacleList:
                    if ((square.rx == oSquare.rx and square.ry == oSquare.ry)
                            or (square.rx == self.endPiece.rx
                                and square.ry == self.endPiece.ry) or
                        (square.rx == 0 and square.ry == self.rows // 2)):
                        intersects = True
                if intersects:
                    #PLace the obstacle again
                    continue
                else:
                    #Add it to the list of all obstacles
                    obstacleList.append(square)
                    i += 1
            #make a list of the positions of the squares
            positions = []
            for square in obstacleList:
                positions.append((square.ry, square.rx))
            self.positions = set(positions)
            #check if you can go from the player start to the endpiece
            path = self.isPath(self.rows // 2, 0, self.endPiece.ry,
                               self.endPiece.rx, self.rows // 2, 0)
            if path:
                return obstacleList
            else:
                #Place all the obstacles in different locations
                tries += 1
                obstacleList = []
                i = 0
                continue
        #If after 999 tries there is no path from start to finish,
        # move the end piece to where the player starts to guarantee a solution
        #This very rarely will run since almost all the time there is a path
        if tries > 999:
            prow, pcol = self.getCell(50, self.app.height // 2)
            self.endPiece.ry = prow
            self.endPiece.rx = pcol
            if (prow, pcol) in self.positions:
                self.positions.remove((prow, pcol))
                obstacleList.remove((prow, pcol))
            return obstacleList

    #Recursively checks if there is a path from a given (row,col) to a target (row,col)
    def isPath(self, row, col, trow, tcol, prow, pcol):
        if (not ((0 <= row <= self.rows - 1) and (0 <= col <= self.cols - 1))
                or (row, col) in self.positions):
            return False
        if row == trow and col == tcol:
            return True
        else:
            dirs = [(0, 1), (1, 0), (-1, 0), (0, -1)]
            for drow, dcol in dirs:
                newRow = row + drow
                newCol = col + dcol
                if newRow == prow and newCol == pcol:
                    return False
                if self.isPath(newRow, newCol, trow, tcol, row, col):
                    return True
            return False

    #Checks if any shortcut keys were pressed or movement keys
    def keyPressed(self, event):
        if event.key == 'p':
            self.paused = not self.paused
        elif event.key == 'd':
            Bullet.number = 0
            self.player.dead = True
        elif event.key == 'e':
            self.app.setActiveMode(self.app.endScreen)
        elif event.key == 's':
            self.app.level += 1
            if self.app.level <= len(self.app.levelList):
                print(f'loading Level {self.app.level}')
                Bullet.number = 0
                self.app.setActiveMode(self.app.levelList[self.app.level - 1])
            else:
                self.app.setActiveMode(self.app.endScreen)

        elif event.key == 'Up':
            if not self.paused:
                self.player.isMoving = True
                self.movePlayer(0, -10)
        elif event.key == 'Down':
            if not self.paused:
                self.player.isMoving = True
                self.movePlayer(0, 10)
        elif event.key == 'Left':
            if not self.paused:
                self.player.isMoving = True
                self.movePlayer(-10, 0)
        elif event.key == 'Right':
            if not self.paused:
                self.player.isMoving = True
                self.movePlayer(10, 0)

    #Moves each enemy
    def moveEnemies(self):
        for enemy in self.enemies:
            enemy.move(self)

    #Allows the player to start attacking again
    def keyReleased(self, event):
        if (event.key == 'Up' or event.key == 'Down' or event.key == 'Right'
                or event.key == 'Left'):
            self.player.isMoving = False

    #Checks if the player clicked the main menu button post death
    def mousePressed(self, event):
        if self.player.dead:
            if (self.app.width // 2 - 100 <= event.x <=
                    self.app.width // 2 + 100 and self.app.height // 2 + 20 <=
                    event.y <= self.app.height // 2 + 60):
                Bullet.number = 0
                #Saves player score
                self.app.saveScore()
                #Resets the app
                self.app.resetApp()

    def timerFired(self):
        if not self.paused:
            if not self.player.dead:
                #If the level is cleared, do not move any  bullets
                if self.player.levelCleared:
                    self.canDrawBullet = False
                #Move the bullet if it exists, otherwise make a bullet
                else:
                    if len(self.enemies) != 0:
                        if Bullet.number == 0:
                            self.bullet = self.player.attack(self)
                            self.bullet.move(self)
                            Bullet.number += 1
                            self.canDrawBullet = True
                        else:
                            self.bullet.move(self)
                            if self.bullet.hitTarget or self.bullet.hitObstacle:
                                Bullet.number -= 1
                                self.canDrawBullet = False
                #Move the enemies
                self.moveEnemies()

    def redrawAll(self, canvas):
        #Draw Pause screen
        if self.paused:
            canvas.create_image(self.app.width // 2,
                                self.app.height // 2,
                                image=ImageTk.PhotoImage(self.app.background))
            canvas.create_text(self.app.width // 2,
                               self.app.height // 2 - 60,
                               text='Game is Paused',
                               font='Arial 30 bold')
            canvas.create_text(self.app.width // 2 - 10,
                               self.app.height // 2 - 20,
                               text='Press p to return to game',
                               font='Arial 20 bold')

        else:
            #Draw the dead screen
            if self.player.dead:
                canvas.create_image(self.app.width // 2,
                                    self.app.height // 2,
                                    image=ImageTk.PhotoImage(
                                        self.app.background))
                canvas.create_text(self.app.width // 2,
                                   self.app.height // 2 - 60,
                                   text='You Lose! :(',
                                   font='Arial 30 bold')
                canvas.create_text(self.app.width // 2 - 10,
                                   self.app.height // 2 - 20,
                                   text=f'Final Score: {self.app.score}',
                                   font='Arial 20 bold')
                canvas.create_rectangle(self.app.width // 2 - 100,
                                        self.app.height // 2 + 20,
                                        self.app.width // 2 + 100,
                                        self.height // 2 + 60,
                                        fill='darkgreen')
                canvas.create_text(self.app.width // 2,
                                   self.app.height // 2 + 40,
                                   text='Main Menu',
                                   font='Arial 20 bold')

            else:

                #draw background
                canvas.create_image(self.app.width // 2,
                                    self.app.height // 2,
                                    image=ImageTk.PhotoImage(
                                        self.app.background))

                canvas.create_text(self.app.width // 2 - self.scrollX,
                                   20,
                                   text=f'Level {self.app.level}',
                                   font='Arial 20 bold')
                canvas.create_text(self.app.width - 30 - self.scrollX,
                                   20,
                                   text=f'Score: {self.app.score}',
                                   font='Arial 20 bold')

                #draw obstacles
                for square in self.obstacles:
                    x0, y0, x1, y1 = self.getCellBounds(square.ry, square.rx)
                    canvas.create_image(
                        (x0 + x1) / 2 - self.scrollX, (y0 + y1) / 2,
                        image=ImageTk.PhotoImage(self.app.obstacle))

                #draw endPiece
                x2, y2, x3, y3 = self.getCellBounds(self.endPiece.ry,
                                                    self.endPiece.rx)
                canvas.create_image(
                    (x2 + x3) / 2 - self.scrollX, (y2 + y3) / 2,
                    image=ImageTk.PhotoImage(self.app.endPiecePicture))

                #draw start Wall
                self.startWall.drawWall(canvas, self)

                #draw the end Wall
                self.endWall.drawWall(canvas, self)

                #draw Enemies
                for enemy in self.enemies:
                    enemy.drawEnemy(canvas, self.scrollX)

                #draw Player
                self.player.drawPlayer(canvas, self.scrollX)

                if self.canDrawBullet:
                    self.bullet.drawBullet(canvas, self.scrollX)
コード例 #9
0
    pygame.draw.rect(surface, pygame.Color(115, 74, 1, 255),
                     (80, 752 // 2 - 200, 40, 230))
    pygame.draw.circle(surface, pygame.Color(2, 132, 32, 255),
                       (100, 752 // 2 - 200), 90)


run = True
#кадрики для неподвижног состояния
idleRight = load_image('0_Golem_Idle_000.png',
                       'images//PNG Sequences_golem1//Idle_//')
idleLeft = pygame.transform.flip(idleRight, True, False)
#когда покраснел
idleRightRed = load_image('0_Golem_Idle_000.png',
                          'images//PNG Sequences_golem1//Idle_Red//')
idleLeftRed = pygame.transform.flip(idleRightRed, True, False)
man1 = Player(200, 610, idleLeft, idleRight, idleLeftRed, idleRightRed,
              player_group)
#кадрики для бега и удара
man1.load_images('0_Golem_Running_0', 'images//PNG Sequences_golem1//Running_',
                 '.png', 12, man1.RightRunFrames, man1.LeftRunFrames)
man1.load_images('0_Golem_Slashing_0',
                 'images//PNG Sequences_golem1//Slashing_', '.png', 12,
                 man1.RightSlashingFrames, man1.LeftSlashingFrames)
#аналогично для id2
idleRight = load_image('0_Golem_Idle_000.png',
                       'images//PNG Sequences_golem3//Idle_//')
idleLeft = pygame.transform.flip(idleRight, True, False)
man2 = Player(600, 610, idleLeft, idleRight, None, None, player_group)
man2.load_images('0_Golem_Running_0', 'images//PNG Sequences_golem3//Running_',
                 '.png', 12, man2.RightRunFrames, man2.LeftRunFrames)
man2.load_images('0_Golem_Slashing_0',
                 'images//PNG Sequences_golem3//Slashing_', '.png', 12,
コード例 #10
0
ファイル: Game.py プロジェクト: benedicteb/outcast
class Game:
    SPRITES_LOCATION = "sprites"
    SPRITES_EXT = ".png"

    FONTS_LOCATION = "fonts"
    CANTERBURY_FONT = "Canterbury.ttf"
    MONOSPACE_FONT = "Monospace.ttf"

    WORLDS_LOCATION = "worlds"

    STATUSBAR_OFFSET = 120
    STATUSBAR_COLOR = (112, 112, 112)
    STATUSBAR_FONTSIZE = 24
    STATUSBAR_MARGIN = 10

    # Inventory
    INV_OFF = 10
    INV_SPACE = 5
    INV_WIDTH = 20
    INV_HEIGHT = 20
    INV_ROWS = 15
    INV_COLS = 4

    def __init__(self):
        self.FPS = 30
        self.dt = 1. / self.FPS
        pygame.init()
        self.clock = pygame.time.Clock()
        self.sight_radius = 10
        self.width  = (2*self.sight_radius + 1) * World.METER_SIZE + Game.STATUSBAR_OFFSET
        self.height = (2*self.sight_radius + 1) * World.METER_SIZE
        self.screen = pygame.display.set_mode((
            self.width, self.height
        ))
        pygame.display.set_caption('Testing')
        self.world = World(open(resource_path(
            Game.WORLDS_LOCATION, "real_world.board"
        ), 'r'))
        self.world.game = self

        self.player = Player([11, 11], game=self, world=self.world)
        # self.world.add(self.player)
        # self.world.add(Planet([200,200], 500, 30))

        self.placables = [
            Item("Axe", position=[53, 16]),
            Item("Boat", position=[14, 63]),
            Page(PAGE1, position=[19, 11]),
            Page(PAGE2, position=[26, 16]),
            Page(PAGE3, position=[61, 12]),
        ]

        self.npcs = [
            NPC([72, 58], game=self, world=self.world, dialog="This is a page. Maybe you'll learn something, douche.",
                items=[Page(PAGE4, position=None)]),
            NPC([34, 74], game=self, world=self.world, dialog="This is a page. Maybe you'll learn something, douche.",
                items=[Page(PAGE5, position=None)]),
            NPC([63, 84], game=self, world=self.world, dialog="This is a page. Maybe you'll learn something, douche.",
                items=[Page(PAGE6, position=None)]),
            NPC([25, 32], game=self, world=self.world, dialog="This is a page. Maybe you'll learn something, douche.",
                items=[Page(PAGE7, position=None)]),
            NPC([57, 37], game=self, world=self.world, dialog="This is a page. Maybe you'll learn something, douche.",
                items=[Page(PAGE8, position=None)]),
            NPC([31, 51], game=self, world=self.world, dialog="This is a page. Maybe you'll learn something, douche.",
                items=[Page(PAGE9, position=None)]),
            # NPC([0, 2], game=self, world=self.world, dialog="My my, this is fancy!"),
        ]

        self.text_dialog_queue = []

    def start(self):
        self._draw()
        while 1:
            self._update()
            self._draw()
            self.dt = self.clock.tick(self.FPS) * 0.001
            # print self.clock.get_fps()

    def _update(self):
        for event in pygame.event.get(): # event handling loop
            if event.type == QUIT:
                pygame.quit()
                sys.exit()
            elif event.type == KEYDOWN:
                if event.key in (K_a, K_d, K_w, K_s):
                    if event.key == K_a:
                        self.player.speed_up([-1, 0])
                    elif event.key == K_d:
                        self.player.speed_up([1, 0])
                    elif event.key == K_w:
                        self.player.speed_up([0, -1])
                    elif event.key == K_s:
                        self.player.speed_up([0, 1])
                if event.key == K_e:
                    if len(self.text_dialog_queue) != 0:
                        if not self.text_dialog_queue[0].next_page():
                            del self.text_dialog_queue[0]

                            if self.player.interacting_with and len(self.text_dialog_queue) == 0:
                                self.player.interacting_with = None
                                continue

                    for npc in self.npcs:
                        for ds in [[1, 0], [-1, 0], [0, 1], [0, -1]]:
                            if (npc.position == self.player.position + ds).all():
                                if not self.player.interacting_with and not len(self.text_dialog_queue) != 0:
                                    npc.interact()
                                    self.player.interacting_with = npc

            elif event.type == KEYUP:
                if event.key in (K_a, K_d, K_w, K_s):
                    if event.key == K_a:
                        self.player.speed_up([1, 0])
                    elif event.key == K_d:
                        self.player.speed_up([-1, 0])
                    elif event.key == K_w:
                        self.player.speed_up([0, 1])
                    elif event.key == K_s:
                        self.player.speed_up([0, -1])

        # If player steps on item, give it to player
        for item in self.placables:
            if (self.player.position == item.position).all():
                self.player.give_item(self.placables.pop(self.placables.index(item)))

        self.player.update()

        for npc in self.npcs:
            npc.update()

    def _draw(self):
        board = self.world.board
        radius = self.sight_radius
        playpos = self.player.position

        self.screen.fill(World.VOID_COLOR)

        for i in xrange(-radius, radius + 1):
            for j in xrange(-radius, radius + 1):
                ij = np.array([i, j])

                try:
                    if (ij + playpos < 0).any():
                        raise IndexError
                    key = board[tuple(ij + playpos)]
                except IndexError:
                    # Outside of board.
                    continue

                self.screen.blit(
                    self.world.sprites[key],
                    (ij + radius) * World.METER_SIZE + [Game.STATUSBAR_OFFSET, 0],
                )


        self.screen.blit(
            self.player.get_sprite(),
            np.array([radius, radius]) * World.METER_SIZE + [Game.STATUSBAR_OFFSET, 0],
        )

        # Draw statusbar
        pygame.draw.rect(self.screen, Game.STATUSBAR_COLOR, (0, 0,
            Game.STATUSBAR_OFFSET, self.height), 0)

        # Text for statusbar
        font = pygame.font.Font(
            resource_path(Game.FONTS_LOCATION, Game.CANTERBURY_FONT),
            Game.STATUSBAR_FONTSIZE,
        )
        label = font.render("Inventory", 1, (0, 0, 0))
        self.screen.blit(label, (Game.STATUSBAR_MARGIN, Game.STATUSBAR_MARGIN))

        # Draw inventory boxes
        for i in range(Game.INV_COLS):
            for j in range(Game.INV_ROWS):
                pygame.draw.rect(self.screen, (0,0,0), (Game.INV_WIDTH*i +\
                    Game.INV_OFF + Game.INV_SPACE*i, Game.STATUSBAR_MARGIN +\
                    label.get_height() + Game.INV_OFF + Game.INV_HEIGHT*j +\
                    Game.INV_SPACE*j, Game.INV_WIDTH,
                    Game.INV_HEIGHT), 0)

        # If player has inventory, fill
        for i in range(len(self.player.inventory)):
            x = i % Game.INV_COLS
            y = i / Game.INV_ROWS

            self.screen.blit(
                    self.player.inventory[i].get_sprite(),
                    [Game.INV_OFF + Game.INV_SPACE*x + Game.INV_WIDTH*x,
                     Game.STATUSBAR_MARGIN + label.get_height() + Game.INV_OFF +\
                     Game.INV_HEIGHT*y + Game.INV_SPACE*y])

        # Draw FPS
        FPS = 1. / self.dt
        font = pygame.font.Font(
            # Game.MONOSPACE_FONT,
            resource_path(Game.FONTS_LOCATION, Game.MONOSPACE_FONT),
            Game.STATUSBAR_FONTSIZE,
        )
        label = font.render("FPS: %d" % FPS, 1, (255, 0, 0))
        self.screen.blit(label, (self.width - label.get_width(), 0))

        # Draw placables
        for item in self.placables:
            self.screen.blit(item.get_sprite(),
                    (item.position - self.player.position + radius) * World.METER_SIZE +\
                    [Game.STATUSBAR_OFFSET, 0])

        # Draw NPCs
        for npc in self.npcs:
            self.screen.blit(npc.get_sprite(),
                    (npc.position - self.player.position + radius) * World.METER_SIZE +\
                    [Game.STATUSBAR_OFFSET, 0])

        # If text dialog, draw it
        if len(self.text_dialog_queue) != 0:
            self.text_dialog_queue[0].render()

        pygame.display.update()