当前位置: 首页>>代码示例>>Python>>正文


Python Map.draw方法代码示例

本文整理汇总了Python中map.Map.draw方法的典型用法代码示例。如果您正苦于以下问题:Python Map.draw方法的具体用法?Python Map.draw怎么用?Python Map.draw使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在map.Map的用法示例。


在下文中一共展示了Map.draw方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: Game

# 需要导入模块: from map import Map [as 别名]
# 或者: from map.Map import draw [as 别名]
class Game(object):

    def __init__(self):
        pygame.init()
        self.window = pygame.display.set_mode((640, 480))
        self.player = Player(x=100, y=100, width=640, height=480)
        self.plupp = Plupp(window_width=640, window_height=480)
        self.clock = pygame.time.Clock()
        self.map = Map()

        while True:
            CollisionHandler.handle_plupp_collisions(player=self.player, plupp=self.plupp)
            CollisionHandler.handle_player_collisions(player=self.player, map=self.map)

            EventHandler.handle_events(player=self.player, plupp=self.plupp)
            self.clock.tick(15)
            self.update()
            self.draw()

    def update(self):
        self.player.update()

    def draw(self):
        self.window.fill((0, 0, 255))
        self.player.draw(self.window)
        self.plupp.draw(self.window)
        self.map.draw(self.window)
        pygame.display.flip()
开发者ID:itggot,项目名称:Nibbles,代码行数:30,代码来源:nibbles.py

示例2: __init__

# 需要导入模块: from map import Map [as 别名]
# 或者: from map.Map import draw [as 别名]
class PyAction:
    def __init__(self, type=1):
        pygame.init()
        screen = pygame.display.set_mode(SCR_RECT.size)
        pygame.display.set_caption("ROCKMAN WORLD 5")
        
        # load images
        Block.images = split_image(load_image("plute_map.png"), 16, 16, 16)
        Block.image = Block.images[0] #初期化

        # music
#        pygame.mixer.music.load("data/mars.nsf")
#        pygame.mixer.music.play(-1) 
        
        # loading map
        self.map = Map("data/plute.map")
        
        # main loop
        clock = pygame.time.Clock()
        while True:
            clock.tick(60)
            self.update()
            self.draw(screen)
            pygame.display.update()
            self.key_handler()

    def update(self):
        self.map.update()
    
    def draw(self, screen):
        self.map.draw()
        
        # draw part of map by offset
        offsetx, offsety = self.map.calc_offset()
        
        # 端ではスクロールしない
        if offsetx < 0:
            offsetx = 0
        elif offsetx > self.map.width - SCR_RECT.width:
            offsetx = self.map.width - SCR_RECT.width
        
        if offsety < 0:
            offsety = 0
        elif offsety > self.map.height - SCR_RECT.height:
            offsety = self.map.height - SCR_RECT.height
        
        # マップの一部を画面に描画
        screen.blit(self.map.surface, (0,0), (offsetx, offsety, SCR_RECT.width, SCR_RECT.height))
    
    def key_handler(self):
        for event in pygame.event.get():
            if event.type == QUIT:
                pygame.quit()
                sys.exit()
            elif event.type == KEYDOWN and event.key == K_ESCAPE:
                pygame.quit()
                sys.exit()
开发者ID:flameDH,项目名称:Megaman-World-5-in-FC,代码行数:59,代码来源:rockmanwld5.py

示例3: __init__

# 需要导入模块: from map import Map [as 别名]
# 或者: from map.Map import draw [as 别名]
class Game:
    """game Main entry point. handles intialization of game and graphics.    
    members:
        map : map.Map() instance
    """

    done = False

    def __init__(self, width=640, height=480):
        """Initialize PyGame"""
        pygame.init()
        self.width, self.height = width, height
        self.clock = pygame.time.Clock()
        self.screen = pygame.display.set_mode((self.width, self.height))
        pygame.display.set_caption(GAME_TITLE)

        self.map = Map(self)

        print GAME_TITLE
        print GAME_ABOUT
        print GAME_HOTKEYS

    def main_loop(self):
        """Game() main loop"""
        while not self.done:
            # get key input, move, draw.
            self.handle_events()
            self.draw()
            self.clock.tick(60)

    def handle_events(self):
        """handle events."""
        events = pygame.event.get()
        for event in events:
            if event.type == pygame.QUIT:
                sys.exit()
            # event: keydown
            elif event.type == KEYDOWN:
                # exit on Escape
                if event.key == K_ESCAPE:
                    self.done = True
                # toggle bool
                elif event.key == K_s:
                    self.map.scrolling = not self.map.scrolling
                elif event.key == K_SPACE:
                    # random map
                    self.map.randomize()

            elif event.type == MOUSEMOTION:
                self.map.scroll(event.rel)

    def draw(self):
        """render screen"""
        self.screen.fill(Color("black"))
        self.map.draw()
        pygame.display.flip()
开发者ID:gbdu,项目名称:ninmonkey,代码行数:58,代码来源:game.py

示例4: Game

# 需要导入模块: from map import Map [as 别名]
# 或者: from map.Map import draw [as 别名]
class Game(object):
    def __init__(self, zombs, vics, huntrs, ticks, map_x=20, map_y=20):
        self.map = Map(zombs, vics, huntrs, ticks, map_x, map_y)
        self.ticks = ticks

    def update(self):
        self.map.update()

    def draw(self):
        self.map.draw()

    def simulate(self):
        for i in xrange(self.ticks):
            self.update()
            self.draw()
开发者ID:jamtot,项目名称:PyProjects,代码行数:17,代码来源:game.py

示例5: previous_map

# 需要导入模块: from map import Map [as 别名]
# 或者: from map.Map import draw [as 别名]
def previous_map(state, player):
	print "\nSee map from which turn? (Current turn is %d) (0 to cancel)" % state.turn_number
	turn = -1
	while turn < 1 or turn > state.turn_number - 1:
		try:
			turn = int(raw_input(": "))
		except:
			pass
		if turn == 0:
			return


	oldmap = Map(state.map.size)
	oldmap.zones = state.map_stack[turn]
	oldmap.draw()
	raw_input()
开发者ID:mansam,项目名称:anachronos,代码行数:18,代码来源:anachronos.py

示例6: MainScene

# 需要导入模块: from map import Map [as 别名]
# 或者: from map.Map import draw [as 别名]

#.........这里部分代码省略.........
        #    collisions = e.getCollisions()
        #    for c in collisions:
        #        if c in self._enemies:
        #            c.destroy()
        #            e.explode()



        for e in self._enemies:
            if e.targetReached():
                self.enemyReachedBase(e)
            else:
                self._player.checkLock(e)
                for p in self._projectiles:
                    if p.collidesWith(e):
                        self._total_kills += 1
                        p.explode()
                        e.explode()
                        self._score += 100
                        self.updateText("kills", "score")



        if not self._game_over:
            p = self._player
            nearby = p.getCloseEntities()
            for n in nearby:
                if isinstance(n,TargetPoint):
                    if p.collidesWith(n):
                        self.reachedTargetPoint(n)

        #  draw -------

        self._map.draw(self)
        self._player.draw(self)

        for e in self._bases: e.draw(self)
        for e in self._target_points: e.draw(self)
        for e in self._projectiles: e.draw(self)
        for e in self._enemies: e.draw(self)


        glDepthMask(False)
        glBlendFunc(GL_SRC_ALPHA, GL_ONE)
        glEnable(GL_BLEND)

        self._particles.draw(self) # very last thing to draw
        for e in self._target_points: e.drawBeacon(self)

        glDisable(GL_BLEND)
        glDepthMask(True)

        # UI ------
        self.updateAlerts(time)

        locking = False
        if not self._game_over:
            lock_pos = self._player.getLockPosition()
            if lock_pos is not None:
                proj = mmult(self._perspective_m, self._modelview_m, N.array((lock_pos[0], lock_pos[1], lock_pos[2], 1), dtype = "f"))

                if proj[3] > 0:
                    px = ((proj[0] / proj[3]) +1.0)* self._vpw*0.5
                    py = (1.0 - (proj[1] / proj[3]))* self._vph*0.5
                    if px > 0 and px < self._vpw and py >0 and py < self._vph:
                        self._sprites.setSpriteTransform(self._lock_sprite, T.translation_matrix((px,py,0)))
开发者ID:Gato-X,项目名称:NotYourData,代码行数:70,代码来源:mainscene.py

示例7: range

# 需要导入模块: from map import Map [as 别名]
# 或者: from map.Map import draw [as 别名]

#.........这里部分代码省略.........
                self.DropSpeed = 10
                self.MoveState = self.JUMP

        elif self.JumpTime == 0:
            # self.JumpTime = -1
            self.MoveState = self.JUMP
        elif self.JumpTime == -1:
            self.MoveState = self.CLEAR

        if self.MoveState == self.CLEAR or self.MoveState == self.JUMP:
            if self.GetCharCrash(self.HeroX, (self.HeroY + (self.DropSpeed / 10) * 2 + 48), 0) == 0:
                self.HeroY += self.DropSpeed / 10 * 2
                self.DropSpeed += 1
                self.isjump = True
            else:  #######################
                self.DropSpeed = 10
                self.MoveState = self.CLEAR
                self.JumpTime = -1
                self.isjump = False

        if self.SwitchDetection(self.HeroX, self.HeroY + 52) == 1:
            self.SetSwitch(self.SwitchNo)

        if self.HeroY > 768:
            self.LoadStage(self.map.Stage_number)

        if self.collide(self.HeroX, self.HeroY, self.EndX, self.EndY):
            if self.clearWin == False:
                self.clear_sound.play()
                self.clearWin = True

        pass

    def tutorial_draw(self):
        self.tutorial_image1.draw(252, 500)
        self.tutorial_image2.draw(400, 400)
        self.tutorial_image3.draw(300, 300)

        if self.map.object[8][8] != 14:
            self.tutorial_image4.draw(700, 370)
        pass

    def clear_draw(self):
        self.clearbg.draw(200, 154)
        self.Stageclear_image[self.clear_frames].draw(225, 250)

        pass

    def draw(self):
        self.background.draw()
        self.map.draw()

        if self.map.Stage_number == 0:
            self.tutorial_draw()

        if self.Charview == False:
            self.laser.clip_draw(self.laser_frames * 64, 0, 64, 768, self.HeroX - 17, self.HeroY - 720)
        else:
            if self.CharState == self.LEFT_RUN:
                self.left_run.clip_draw(self.run_frames * 25, 0, 25, 50, self.HeroX, self.HeroY)
            elif self.CharState == self.RIGHT_RUN:
                self.right_run.clip_draw(self.run_frames * 25, 0, 25, 50, self.HeroX, self.HeroY)
            elif self.CharState == self.LEFT_STAND:
                self.left_stand.draw(self.HeroX, self.HeroY)
            elif self.CharState == self.RIGHT_STAND:
                self.right_stand.draw(self.HeroX, self.HeroY)
开发者ID:ricky626,项目名称:2DGP,代码行数:70,代码来源:hero.py

示例8: Level

# 需要导入模块: from map import Map [as 别名]
# 或者: from map.Map import draw [as 别名]

#.........这里部分代码省略.........
                                self.map)
        self._background = Parallax(const.backgrounds)
        self.editor = Editor(self.map,
                             self._surface,
                             enabled=False,
                             inputStream=self.getInputStream())

        self._input = Input(inputStream=self.getInputStream())
        self._input.set(KEYDOWN, self.editor.toggleEnabled, K_e)
        self._input.set(KEYDOWN, self.start, K_r)

        # self._sound = Sound("assets\\music.ogg")
        # self._sound.play(-1)

        try:
            self._healthBar = HealthBar(10, 10, self.get(tid))
        except AssertionError:
            pass

        for (x, y), val in self.map.enemies.items():
            block = self.map.get(x, y)
            self._enemySpawns[block] = EnemySpawn(level=self,
                                                  anchor=Object(pos=(block.x, block.y)),
                                                  maxEmitted=val,
                                                  timeBetween=2)

        self._countdown = CountdownTimer(const.screenSize[0] * const.res - 50, 10,
                                         self.map.getAttr("timeLim"))

    def addEntity(self, register=False, entity=None):
        if not entity:
            raise Exception("Entity must not be None.")

        tid = entity.getId()

        self._entities[tid] = entity
        if register:
            self._registered[tid] = entity

        self._entity_map[tid] = set()
        return tid

    def removeEntity(self, entity):
        del self._entities[entity.id]

    def get(self, entityId):
        return self._entities.get(entityId)

    def process(self):
        for entity in self._entities.values():
            result = entity.tick()

            if not entity.isAlive():
                self._entities.pop(entity.getId())

            # This should generally only apply to playable characters.
            if entity in self._registered.values():
                if Tiles.End in result.keys():
                    self.setFinished()
                if not entity.isAlive():
                    self.setLost()

        for s in self._enemySpawns.values():
            s.tick()

        self._camera.tick()
        self._countdown.tick()
        if self._countdown.isFinished():
            self.setLost()

        if self.editor.enabled():
            self.editor.tick(self._camera)

        if self.isComplete():
            pass
            # self._sound.fadeout(3000)

    def render(self):
        self._surface.fill((0, 0, 0))
        self._background.draw(self._total_surface, self._camera)
        for s in self._enemySpawns.values():
            s.draw(self._total_surface)
        for entity in self._entities.values():
            entity.draw(self._total_surface)

        self.map.draw(self._total_surface)
        if self.editor.enabled():
            self.editor.draw(self._total_surface)

        self._camera.draw(self._surface, self._total_surface)

        self._healthBar.draw(self._surface)
        self._countdown.draw(self._surface)
        if self.editor.enabled():
            self.editor.menu.draw()

    def tick(self):
        self._input()
        self.process()
        self.render()
开发者ID:DanCardin,项目名称:PyPlatformer,代码行数:104,代码来源:level.py

示例9: int

# 需要导入模块: from map import Map [as 别名]
# 或者: from map.Map import draw [as 别名]
    tend = 1.0
    dT   = 0.5
    h    = 0.05
    N    = int(np.around(tend/h)) + 1
    N2   = int(np.around(tend/dT)) + 1
    x0   = np.array([5,5,0, 2.0,0,0])
    xg   = np.array([120, 120, 0])

    potfield = PotentialFields(a_map, N2)

    vobj = Vessel(x0, xg, h, dT, N, [potfield], is_main_vessel=True, vesseltype='viknes')

    potfield.update(vobj)

    fig = plt.figure(1)
    ax  = fig.add_subplot(111, autoscale_on=False)
    ax.axis('scaled')
    ax.set_xlim((-10, 160))
    ax.set_ylim((-10, 160))
    ax.set_xlabel('x [m]')
    ax.set_ylabel('y [m]')
    ax.grid()

    a_map.draw(ax)

    potfield.draw(ax)

    plt.show()


开发者ID:thomsten,项目名称:project-thesis-simulator,代码行数:30,代码来源:ctrl_PotField.py

示例10: Game

# 需要导入模块: from map import Map [as 别名]
# 或者: from map.Map import draw [as 别名]

#.........这里部分代码省略.........
            hud.cr.identity_matrix()
            hud.cr.translate(30 + hack, 30 + hack)
            hud.text('Player %d' % (self.player+1,), self.font_ui)

            hud.cr.identity_matrix()
            hud.cr.translate(30 + hack, 70 + hack)
            hud.text('Angle: %3.0f' % self.angle[self.player], self.font_ui)

            hud.cr.identity_matrix()
            hud.cr.translate(30 + hack, 100 + hack)
            hud.text('Force: %3.0f' % self.force[self.player], self.font_ui)

    def render_world(self, camera):
        view = Matrix.lookat(
            camera.x + 19, camera.y, 15,
            camera.x + 19, camera.y, 0,
            0,1,0)

        with self.fbo as frame:
            frame.clear(0,0.03,0.15,1)

            Shader.upload_projection_view(self.projection, view)
            Shader.upload_game(None)
            Shader.upload_light(self.ambient_light, self.cull_lights())

            # parallax background
            pm = Matrix.transform(
                0.75 * camera.x, camera.y * 0.5 - 12, 0,
                (19*4) * self.parallax_rep, 19, 0
            )
            self.shader_hud.bind()
            self.parallax.texture_bind()
            Shader.upload_model(pm)
            self.repquad.draw()

            Shader.upload_projection_view(self.projection, view)

            self.shader.bind()
            self.map.draw()

            # entities
            for obj in self.map.obj:
                obj.draw()
            if not self.is_over:
                self.projectile.draw()

    def render(self):
        glClearColor(1,0,1,1)
        glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT)

        camera = self.camera.copy()
        if self.projectile:
            camera.x = min(max(self.projectile.pos.x - 19, 0), self.camera_max)
            self.follow_cam = camera
        elif self.follow_cam:
            camera = self.follow_cam

        self.render_hud(camera)
        self.render_world(camera)

        mat = Matrix.scale(self.size.x, self.size.y)
        Shader.upload_projection_view(self.ortho, Matrix.identity())
        Shader.upload_model(mat)

        self.fbo.bind_texture()
        self.post.bind()
开发者ID:ext,项目名称:nox6_ancient_earth,代码行数:70,代码来源:game.py

示例11: main

# 需要导入模块: from map import Map [as 别名]
# 或者: from map.Map import draw [as 别名]
def main():
  pygame.init()
  pygame.mixer.music.load("rematch.mp3")
  pygame.mixer.music.play(-1)
  screen = pygame.display.set_mode((1000, 1000))
  clock = pygame.time.Clock()
  
  game_map = Map(0)
  player = Character( game_map, 23, 1 )
  
  prevKeys = {}
  
  menu = Menu()
  while True:
    for e in pygame.event.get():
      if e.type == QUIT or (e.type == KEYDOWN and e.key == K_ESCAPE):
        pygame.quit()
        return
    key = pygame.key.get_pressed()
    
    if key[K_DOWN] and not prevKeys[K_DOWN]:
      menu.move(1)
    if key[K_UP] and not prevKeys[K_UP]:
      menu.move(-1)
    if key[K_RETURN] and not prevKeys[K_RETURN]:
      r = menu.select()
      if r == -1:
        pygame.quit()
        return
      elif r == 1:
        break
        
    prevKeys = key
    
    menu.draw(screen)
    pygame.display.flip()
    
  
  while True:
    
    clock.tick(30)
    for e in pygame.event.get():
      if e.type == QUIT or (e.type == KEYDOWN and e.key == K_ESCAPE):
        pygame.quit()
        return
    key = pygame.key.get_pressed()
    
    if key[K_LSHIFT]:
      if key[K_UP] and not prevKeys[K_UP]:
        player.attack_up()
      elif key[K_DOWN] and not prevKeys[K_DOWN]:
        player.attack_down()
      elif key[K_LEFT] and not prevKeys[K_LEFT]:
        player.attack_left()
      elif key[K_RIGHT] and not prevKeys[K_RIGHT]:
        player.attack_right()
    else:
      if key[K_UP] and not prevKeys[K_UP]:
        player.move_up()
      elif key[K_DOWN] and not prevKeys[K_DOWN]:
        player.move_down()
      elif key[K_LEFT] and not prevKeys[K_LEFT]:
        player.move_left()
      elif key[K_RIGHT] and not prevKeys[K_RIGHT]:
        player.move_right()
    
    while game_map.isWin(player.position.real, player.position.imag):
      screen.blit(winScreen,(0,0))
      pygame.display.flip()
      for e in pygame.event.get():
        if e.type == QUIT or (e.type == KEYDOWN and e.key == K_ESCAPE):
          pygame.quit()
          return
    
    prevKeys = key
    game_map.draw(screen)
    player.draw(screen)
    
    
    
    pygame.display.flip()
开发者ID:origamize,项目名称:GameJamFall2011,代码行数:83,代码来源:main.py

示例12: __init__

# 需要导入模块: from map import Map [as 别名]
# 或者: from map.Map import draw [as 别名]
class Engine:
    # Constructor
    # Takes nothing so far.
    # -------------------------------------------------------------------------
    def __init__(self):
        self.actors = []
        self.actor_counter = 0

    # Setup.
    # Stuff that gets done to set up a session of the game.
    def setup(self):
        import actor
        import lightSource as light
        self.player = actor.Actor(const.mapWidth / 2, const.mapHeight / 2)
        self.curMap = Map()
        self.player.ID_ = "player"
        x = actor.Actor(4, 5, '*')
        y = light.LightSource()
        x.addComponent(y)
        x.register()

    # Draw function
    # Takes nothing.
    # -------------------------------------------------------------------------
    def drawFrame(self):
        # Setup some offscreen consoles for each element of the UI (Map,
        # status, messages)
        mapConsole = libtcod.console_new(const.mapWidth, const.mapHeight)

        # Draw the map to screen
        self.curMap.draw(mapConsole)

        # Draw the actors to the mapConsole. Save the player for last.
        # draw dem actors.
        for actor in self.actors:
            actor.draw(mapConsole)

        # Draw the player.
        self.player.draw(mapConsole)

        # Blit all the offscreen consoles to the root
        libtcod.console_blit(mapConsole, 0, 0, 0, 0, const.root, 1, 1)

        # Show dem changes
        libtcod.console_flush()

    # Draws the lines that border the UI.
    # Takes nothing
    # -------------------------------------------------------------------------
    def drawUILines(self):
        # The top and bottom border
        for x in range(const.consoleWidth):
            libtcod.console_put_char_ex(
                const.root, x, 0,
                libtcod.CHAR_HLINE, libtcod.white, libtcod.black)
            libtcod.console_put_char_ex(
                const.root, x, const.consoleHeight - 1,
                libtcod.CHAR_HLINE, libtcod.white, libtcod.black)
            libtcod.console_put_char_ex(
                const.root, x, const.mapHeight + 1,
                libtcod.CHAR_HLINE, libtcod.white, libtcod.black)

        # The left and right border
        for y in range(const.consoleHeight):
            libtcod.console_put_char_ex(
                const.root, 0, y, '|', libtcod.white, libtcod.black)
            libtcod.console_put_char_ex(
                const.root, const.consoleWidth - 1, y, '|', libtcod.white,
                libtcod.black)
            if(y <= const.mapHeight and y > 0):
                libtcod.console_put_char_ex(
                    const.root, const.mapWidth + 1, y, '|', libtcod.white,
                    libtcod.black)

        # The corners
        libtcod.console_put_char_ex(
            const.root, const.consoleWidth - 1, const.consoleHeight - 1, '#',
            libtcod.white, libtcod.black)

        libtcod.console_put_char_ex(
            const.root, 0, const.consoleHeight - 1, '#',
            libtcod.white, libtcod.black)

        libtcod.console_put_char_ex(
            const.root, 0, 0, '#', libtcod.white, libtcod.black)

        libtcod.console_put_char_ex(
            const.root, const.consoleWidth - 1, 0, '#',
            libtcod.white, libtcod.black)

        libtcod.console_flush()

    # Checks that the specified tile is a tile can be walked on.
    # Takes the x,y coord of the tile
    # Returns true if the tile is a valid tile, and could be walked on.
    # -------------------------------------------------------------------------
    def isTileWalkable(self, tileX, tileY):
        if((tileY < const.mapHeight and tileY >= 0) and (tileX < const.mapWidth
                                                         and tileX >= 0)):
            return not self.curMap.curMap[tileX][tileY].blocking
#.........这里部分代码省略.........
开发者ID:dmiller113,项目名称:Stay-in-the-Light,代码行数:103,代码来源:engine.py

示例13: Scene

# 需要导入模块: from map import Map [as 别名]
# 或者: from map.Map import draw [as 别名]
class Scene(object):
	image = None
	def __init__(self, _engine):
		super(Scene, self).__init__()
		self._ais = []
		self._engine = _engine
		self._resx, self._resy = _engine.getResolution()
		self.surface = pygame.Surface((self._resx, self._resy))
		drawText(self.surface, "Wczytywanie mapy...", 48, (255, 255, 255), (self._resx / 2, self._resy / 2))
		self._map = Map(_engine)
		self._hub = Hub(_engine, self._map)
		self._cursor = Cursor(_engine, self._map)
		self._ais.append(AI(_engine, self._map, _engine.players[0], 0))
		self._ais.append(AI(_engine, self._map, _engine.players[1], 1))

	def screenUpdated(self):
		self._resx, self._resy = self._engine.getResolution()
		self.surface = pygame.transform.smoothscale(self.surface, (self._resx, self._resy))
		self._map.screenUpdated()
		self._hub.screenUpdated()
		self._cursor.screenUpdated()

	def show(self):
		try:
			while self._engine.tick():
				for event in pygame.event.get():
					if event.type == QUIT:
						self._engine.quit()

					elif event.type == KEYUP:
						if event.key == K_ESCAPE:
							raise Pause()

						elif event.key == K_TAB:
							for n, tank in enumerate(self._engine.players[0]['tanks']):
								if tank.focus:
									tank.setFocus(False)
									n = (n + 1) % len(self._engine.players[0]['tanks'])
									self._engine.players[0]['tanks'][n].setFocus(True)
									break

				if self._engine.state & engine.STATE_FAIL:
					self.surface.fill((0, 0, 0))
					drawText(self.surface, "Game Over", 50, (140, 0, 0), (self._resx / 2, self._resy / 2))
					self._engine.show(self.surface)
					continue

				if self._engine.state & engine.STATE_WIN:
					self.surface.fill((0, 0, 0))
					drawText(self.surface, "Gratulacje!", 50, (0, 140, 0), (self._resx / 2, self._resy / 2))
					self._engine.show(self.surface)
					continue

				if self._engine.timeLeft() == (0, 0):
					if self._engine.players[0]['score'] > self._engine.players[1]['score']:
						raise GameWin()

					raise GameOver()

				if not len(self._engine.players[0]['tanks']):
					raise GameOver()

				if not len(self._engine.players[1]['tanks']):
					raise GameWin()

				for tank in self._engine.players[0]['tanks']:
					if tank.focus: break

				else:
					self._engine.players[0]['tanks'][0].setFocus(True)

				keys = pygame.key.get_pressed()
				if keys[K_LEFT]:
					self._map.move(map.DIRECTION_LEFT)

				if keys[K_RIGHT]:
					self._map.move(map.DIRECTION_RIGHT)

				if keys[K_UP]:
					self._map.move(map.DIRECTION_UP)

				if keys[K_DOWN]:
					self._map.move(map.DIRECTION_DOWN)

				for ai in self._ais:
					ai.update()

				self._map.update()
				self._hub.update()
				self._cursor.update()
				self._map.draw(self.surface)
				self._hub.draw(self.surface)
				self._cursor.draw(self.surface)
				self._engine.show(self.surface)

		except Pause:
			self._engine.state ^= engine.STATE_GAME | engine.STATE_MENU

		except GameOver:
			self._engine.state |= engine.STATE_FAIL
#.........这里部分代码省略.........
开发者ID:Neverous,项目名称:ii-python11,代码行数:103,代码来源:scene.py

示例14: Game

# 需要导入模块: from map import Map [as 别名]
# 或者: from map.Map import draw [as 别名]
class Game(object):

  def __init__(self, font):
    self.di = DI()
    self.register_services()

    self.screen_height = 60
    self.screen_width = 100
    self.gamefont = sys.path[0] + '/data/fonts/' + font
    self.map = Map(80,45)
    self.fov_recompute = True

    self.game_state = "playing"
    self.player_action = None

    #create the root console
    libtcod.console_set_custom_font(self.gamefont.encode('utf-8'), libtcod.FONT_TYPE_GREYSCALE | libtcod.FONT_LAYOUT_ASCII_INROW)
    libtcod.console_init_root(self.screen_width, self.screen_height, 'crogue'.encode('utf-8'), False)

    #Create a console to draw to the screen
    self.con = libtcod.console_new(self.screen_width, self.screen_height)
    self.player = Player(self.map.starting_pos[0], self.map.starting_pos[1])
    self.objects = UserList()
    self.objects.append(self.player)

    self.Messages =  self.di.Request("Console")
    self.Messages.add_message("Game has been started.")

    self.load_monsters()
    self.add_monsters()
    self.add_items()

  def add_object_to_map(self, item):
    while True:
      y = libtcod.random_get_int(0, 0, self.map.height - 1)
      x = libtcod.random_get_int(0, 0, self.map.width - 1)
      if not self.map.is_blocked(x, y):
        break
    item.x = x
    item.y = y
    self.objects.append(item)

  def add_monsters(self):
    maxmonst = len(self.Monsters)  - 1
    for i in range(100):
      ind = libtcod.random_get_int(0,0,maxmonst)
      monster = copy.deepcopy(self.Monsters[ind])
      self.add_object_to_map(monster)

  def add_items(self):
    for i in range(100):
      self.add_object_to_map(Item(0,0))

  def move_player(self, x, y):

    if self.objects.exists(lambda obj: obj.blocks(self.player, x, y)):
      return

    self.player.move(self.map, x, y)
    self.fov_recompute = True

  def handle_keys(self):
    key = libtcod.console_wait_for_keypress(True)
    if key.vk == libtcod.KEY_ENTER and key.lalt:
      #Alt+Enter: toggle fullscreen
      libtcod.console_set_fullscreen(not libtcod.console_is_fullscreen())
    elif key.vk == libtcod.KEY_ESCAPE:
      return "exit"  #exit game
    elif key.vk == libtcod.KEY_F1:
      if self.game_state == "not-playing":
        self.game_state = "playing"
        return "exit-debug-screen"
      self.game_state = "not-playing"
      return "debug-screen"

    if self.game_state != "playing":
      return

    if libtcod.console_is_key_pressed(libtcod.KEY_UP):
      self.move_player(0,-1)
    elif libtcod.console_is_key_pressed(libtcod.KEY_DOWN):
      self.move_player(0,1)
    elif libtcod.console_is_key_pressed(libtcod.KEY_LEFT):
      self.move_player(-1,0)
    elif libtcod.console_is_key_pressed(libtcod.KEY_RIGHT):
      self.move_player(1,0)
    else:
      return "didn't-move"

  def render_all(self):
    self.render_timer1 = libtcod.sys_elapsed_milli()

    for object in self.objects:
      object.draw(self.con, self.map)

    if self.fov_recompute:
      #recompute FOV if needed (the player moved or something)
      self.fov_recompute = False
      self.map.recompute_fov(self.player.x, self.player.y)

#.........这里部分代码省略.........
开发者ID:CalvinRodo,项目名称:Crogue,代码行数:103,代码来源:crogue.py

示例15: __repr__

# 需要导入模块: from map import Map [as 别名]
# 或者: from map.Map import draw [as 别名]
class State:
    def __repr__(self):
        return "%s" % str(self.map) #.replace("\n", "\\n")
        #return "map.tiles[1][0]: %s, complete: %s" % (self.map.tiles[1][0],self.is_complete())

    def __init__(self,map=None,snakes=None):
        self.move = None
        self.map = map
        self.snakes = snakes
        self.min_moves = -1

    def load_from_json(self,string):
        """FIXME: this happens for all maps on startup"""
        struct = json.loads(string)

        ## load min_moves
        if "min_moves" in struct.keys():
            self.min_moves = struct["min_moves"]
        else:
            self.min_moves = -1

        self.map = Map(coordinates=struct['map'])
        self.snakes = []
        for sj in struct['snakes']:
            snake = Snake(self.map, sj['color'], None)
            snake.elements = Snake.make_elements(sj['elements'],snake)
            snake.assign_to_tiles()
            self.snakes.append(snake)

    def set_surface(self,surface):
        self.map.set_surface(surface)
        for s in self.snakes:
            s.set_surface(surface)

    def load_from_json_file(self,fn):
        fp = open(fn,'r')
        string = "\n".join(fp.readlines())
        self.load_from_json(string)

    # def load_from_file(self,map_name):
    #     coords = Map.load_coords(map_name)
    #     self.map = Map(coordinates=coords['tiles'])#IGNORE:W0622
    #     self.snakes = Snake.make_snakes(self.map,coords['snakes'])

    def __copy__(self):
        s = State()
        s.load_from_json(self.to_json())
        return s

    def __eq__(self,other):
        return str(self.map) == str(other.map)

    def __hash__(self):
        # http://kodeclutz.blogspot.com/2008/08/custom-hash-objects-in-python.html
        # the hash of our string is our unique hash
        #return hash(str(self.map))

        # the above gives just numbers...
        # use this:
        m = hashlib.md5()
        m.update(str(self.map))
        str_md5 = m.hexdigest()
        return str_md5

    def get_neighbour_states(self,exclude=[]):#IGNORE:W0102
        ns = []
        for s in self.snakes:
            for m in s.get_moves():
                newstate = State.apply_move(self,m)
                if newstate not in exclude:
                    ns.append(newstate)
                    #exclude.append(newstate) # hmmm try
        return ns

    def draw(self, arrows=True, resman=None):
        self.map.draw()
        for s in self.snakes:
            s.draw(arrows, resman)

    @staticmethod
    def apply_move(state,m):
        #n = State()
        
        n = copy.copy(state)

        t = n.map.get_tile(m.x1,m.y1)
        if t.se:
            t.se.move(m)
            n.move = m
        return n

    def is_complete(self):
        "a state is complete, when all end tiles are complete"
        return self.map.is_complete()

    # def get_thumbnail(self):
    #     surf = pygame.Surface((self.map.n,self.map.n))
    #     surf.lock()
    #     for x in xrange(self.map.n):
    #         for y in xrange(self.map.n):
#.........这里部分代码省略.........
开发者ID:styts,项目名称:snakes,代码行数:103,代码来源:state.py


注:本文中的map.Map.draw方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。