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


Python Snake.update方法代码示例

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


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

示例1: test_update

# 需要导入模块: from snake import Snake [as 别名]
# 或者: from snake.Snake import update [as 别名]
 def test_update(self):
     """Test that the update function returns the correct status"""
     # Status codes
     n, m = 2, 2
     snake = Snake([(0, 1), (0, 0)])
     snake.direction = 'R'
     apple = (1, 1)
     # Normal status = 0
     status = snake.update(n, m, apple)
     self.assertEqual(status, 'normal')
     # Ate apple status = 1
     snake.direction = 'D'
     status = snake.update(n, m, apple)
     self.assertEqual(status, 'ate_apple')
     # Died status = 2
     status = snake.update(n, m, apple)
     self.assertEqual(status, 'died')
开发者ID:akajuvonen,项目名称:test-snake-pygame,代码行数:19,代码来源:test_snake.py

示例2: World

# 需要导入模块: from snake import Snake [as 别名]
# 或者: from snake.Snake import update [as 别名]
class World():

    def __init__(self):
        self.mc = minecraft.Minecraft.create()
        self.apple = None
        self.snake = Snake(self.mc)

    def get_player_pos(self):
        return self.mc.player.getTilePos()

    def get_apple_pos(self):
        return self.apple

    def place_apple(self, x, z):
        self.remove_apple()
        y = self.mc.getHeight(x,z)
        self.mc.setBlock(x, y, z, 35, 14)
        self.apple = Vec3(x,y,z)

    def remove_apple(self):
        if self.apple is None:
            return

        self.mc.setBlock(self.apple.x, self.apple.y, self.apple.z, 0)
        self.apple = None

    def check_collision(self):
        pos = [floor(axis) for axis in self.get_player_pos()]
        center = Vec3(pos[0], pos[1], pos[2])
        for offset in shell:
            block = center + offset
            if (block.x, block.y, block.z) in list(self.snake.body)[3:]:
                return True
        return False

    def move_snake(self):
        new_pos = self.get_player_pos()
        new_pos = tuple([floor(i) for i in new_pos])
        self.snake.update(new_pos)

    def extend_snake(self):
        self.snake.extend()

    def post(self, message):
        self.mc.postToChat(message)
        print(message)
开发者ID:krustevs,项目名称:hot-n-cold-snake,代码行数:48,代码来源:world.py

示例3: Engine

# 需要导入模块: from snake import Snake [as 别名]
# 或者: from snake.Snake import update [as 别名]
class Engine(object):

    def __init__(self, world_size=WORLD_SIZE):
        self.world_center = Point((world_size // 2, world_size // 2))
        self.world_size = world_size
        self.snake = Snake(start=self.world_center, start_length=SNAKE_START_LENGTH, growth_pending = GROWTH_PENDING)
        self.level = Level(size=self.world_size, snake=self.snake)
        self.score = 0
        self.controller = Controller(self.level.level_render)

    def reset(self):
        """Start a new game."""
        self.playing = True
        self.score = 0
        self.snake = Snake(start=self.world_center,
                           start_length=SNAKE_START_LENGTH)
        self.level = Level(size=self.world_size, snake=self.snake)
        self.play()

    def update(self, dt):
        """Update the game by dt seconds."""

        self.check_input()
        # time.sleep(dt)
        if self.snake.update():
            self.level.update_level()
            self.level.level_render.draw_text(
                Point((0, 0)), 'Score {}'.format(self.score))
            self.level.show_level()
            head = self.snake.get_head()
            # If snake hits a food block, then consume the food, add new
            # food and grow the snake.
            if head in self.level.food:
                self.eat(head)
            if self.snake.self_intersecting():
                raise GameOver('snake intersecting')
            if head in self.level.blocks:
                raise GameOver('snake try eat block')
        time.sleep(dt)

    def eat(self, head=None):
        print('mmm, tasty')
        self.level.food.remove(head)
        self.snake.grow()
        self.score += len(self.snake) * SEGMENT_SCORE

    def play(self):
        """Play game until the QUIT event is received."""
        while True:
            try:
                self.update(TIME_DELTA)
            except GameOver, err:
                print(str(err))
                print('You score {}'.format(self.score))
                time.sleep(3)
                self.reset()
开发者ID:chaotism,项目名称:python-snake,代码行数:58,代码来源:engine.py

示例4: SnakeGame

# 需要导入模块: from snake import Snake [as 别名]
# 或者: from snake.Snake import update [as 别名]
class SnakeGame(object):
    def __init__(self):
        pygame.init()
        pygame.display.set_caption('Snake')
        self.block_size = BLOCK_SIZE
        self.window = pygame.display.set_mode(WORLD_SIZE*self.block_size)
        self.screen = pygame.display.get_surface()
        self.clock = pygame.time.Clock()
        self.font = pygame.font.SysFont(FONT_TYPE,FONT_SIZE)
        self.world = Rect((0,0),WORLD_SIZE)
        self.reset()

    def reset(self):
        ''' Start a new game
        '''
        self.playing = True
        self.next_direction = DIRECTION_UP
        self.score = 0
        self.snake = Snake(self.world.center, SNAKE_START_LENGTH)
        self.food = set()
        self.add_food()
        return

    def add_food(self):
        ''' Add food, and with a small
            probability add more than
            one
        '''
        while not (self.food and randrange(FOOD_PROBABILITY)):
            food = Position(map(randrange,self.world.bottomright))
            if food not in self.food and food not in self.snake:
                self.food.add(food)
        return

    def inp(self,e):
        ''' Process keyboard event e
        '''
        if e.key in KEY_DIRECTION:
            self.next_direction = KEY_DIRECTION[e.key]
        elif e.key == K_SPACE and not self.playing: # space to reset
            self.reset()
        return

    def update(self,dt):
        ''' Update the game by dt seconds
        '''
        self.snake.update(dt, self.next_direction)

        head = self.snake.head()
        if head in self.food: #if snake hits food with head
            self.food.remove(head) #consume the food
            self.add_food() #add more food
            self.snake.grow() #grow the snake
            self.score += len(self.snake) * SEGMENT_SCORE

        if self.snake.self_intersection() or not self.world.collidepoint(self.snake.head()): #colliding with self of boundaries is game over
            self.playing = False

        return

    def block(self,p):
        ''' Return the screen rectangle
            corresponding to the position
            p
        '''
        return Rect(p*self.block_size, DIRECTION_DR*self.block_size)

    def draw_text(self,text,p):
        ''' Draw text at position p
        '''
        self.screen.blit(self.font.render(text, 1, TEXT_COLOR),p)
        return

    def draw(self):
        ''' Draw the game
        '''
        self.screen.fill(BACKGROUND_COLOR)
        for p in self.snake:
            pygame.draw.rect(self.screen,SNAKE_COLOR, self.block(p))
        for f in self.food:
            pygame.draw.rect(self.screen, FOOD_COLOR,self.block(f))
        self.draw_text('Score: {}'.format(self.score),(20,20))
        return

    def draw_death(self):
        ''' Draw game after game over
        '''
        self.screen.fill(DEATH_COLOR)
        self.draw_text('Game over! Press space to start a new game',(20,150))
        self.draw_text('Your score is {}'.format(self.score),(140,140))
        return

    def process_events(self):
        ''' Process key events and
            return bool saying if
            we should quit
        '''
        for e in pygame.event.get():
            if e.type == QUIT:
                return True
#.........这里部分代码省略.........
开发者ID:nsylv,项目名称:snake,代码行数:103,代码来源:snakegame.py

示例5: Game

# 需要导入模块: from snake import Snake [as 别名]
# 或者: from snake.Snake import update [as 别名]
class Game(object):

    def __init__(self, screen_height, screen_width):
        pygame.init()
        self.screen_height = screen_height
        self.screen_width = screen_width
        self.level_maps = ("./data/level1.map", "./data/level2.map", "./data/level3.map")
        self.current_level_map_index = 0
        self.pause = False
        self.won_grow_rate = 10
        height_width = (self.screen_height, self.screen_width)
        self.screen = pygame.display.set_mode(height_width)
        pygame.display.set_caption("PySnake")
        self.score = Score((0, 500))
        self.reload_game = False
        self.speed = 5

    def init_resources(self):
        self.level = Level(self.level_maps[self.current_level_map_index])
        self.snake = Snake((64, 64))
        self.move_direction = Direction.RIGHT
        self.food = None

    def start(self):
        clock = pygame.time.Clock()
        game_over = False
        won = True
        first_load = True

        while not game_over:
            clock.tick(self.speed)
            for event in pygame.event.get():
                self.event_handler(event)

            if self.reload_game:
                break

            if not self.pause:
                background = self.level.render()
                self.snake.render(background)
                if self.food == None:
                    position = self.generate_free_position()
                    self.food = Food(position, 1)

                background.blit(self.food.image, self.food.rect)
                self.screen.fill((0, 0, 0))
                self.screen.blit(background, (0, 0))
                self.screen.blit(self.score.image, self.score.rect)

                pygame.display.flip()
                if first_load:
                    first_load = False
                    self.pause = True
                    continue

                not_collide = self.snake.update(self.move_direction)
                if not not_collide or self.level.collide(self.snake.position):
                    game_over = True
                    won = False

                if self.food.rect.colliderect(self.snake.head.rect):
                    self.snake.grow(self.food.grow_rate)
                    self.score.add(100)
                    self.food = None

                if self.snake.length() == self.won_grow_rate:
                    game_over = True

        if self.reload_game:
            self.load_game()
        elif won and game_over:
            self.load_next_level()
        elif game_over:
            print("Game over")

    def event_handler(self, event):
        if event.type == QUIT:
            sys.exit(0)
        elif event.type == KEYDOWN:
            key = pygame.key.get_pressed()
            new_direction = self.move_direction
            if key[pygame.K_LEFT]:
                new_direction = Direction.LEFT
            elif key[pygame.K_RIGHT]:
                new_direction = Direction.RIGHT
            elif key[pygame.K_UP]:
                new_direction = Direction.UP
            elif key[pygame.K_DOWN]:
                new_direction = Direction.DOWN
            elif key[pygame.K_p]:
                self.pause = not self.pause
            elif key[pygame.K_s]:
                self.pause = True
                level = self.current_level_map_index
                snake = self.snake.get_snake_coords()
                food = self.food.get_food_position()
                direction = self.move_direction
                SaveGame.save(level, snake, food, direction)
            elif key[pygame.K_l]:
                self.reload_game = True
#.........这里部分代码省略.........
开发者ID:peperon,项目名称:PySnake,代码行数:103,代码来源:game.py

示例6: PlayerBase

# 需要导入模块: from snake import Snake [as 别名]
# 或者: from snake.Snake import update [as 别名]
class PlayerBase(object):

    """
    Player base class.
    """

    def __init__(self, game_mode, dead_handler, **kwargs):
        self.game = game_mode.game
        self.tilemap = game_mode.tilemap
        self.pid = kwargs['id']
        self.color = kwargs['color']
        self.snake_skin = kwargs['skin']
        self.snake = None
        self.snake_config = kwargs.get('snake_config', {})
        self._lifes = kwargs.get('lifes', INIT_LIFES)
        self.points = 0
        self.boost_enabled = kwargs.get('boost_enabled', True)
        self._boost = INIT_BOOST
        self.boosting = False
        self.dead_handler = dead_handler
        # TODO: Add weapons from kwargs
        self.weapons = deque(maxlen=5)
        self.weapons.append(Weapon(game_mode.game, self, DUMMY))
        self.pwrup_targets = {'points': 'points', 'grow': 'snake.grow',
                              'speed': 'snake.speed', 'boost': 'boost',
                              'lifes': 'lifes', 'hp': 'snake.hitpoints'}

    def start(self):
        self.snake = Snake(self.game, self.tilemap.get_spawnpoint(),
                           self.snake_skin, self.pid,
                           self.snake_killed, self.snake_config)

    @property
    def lifes(self):
        """Return lifes."""
        return self._lifes

    @lifes.setter
    def lifes(self, value):
        """Set lifes."""
        if value > MAX_LIFES:
            self._lifes = MAX_LIFES
        elif value < 0:
            self._lifes = 0
        else:
            self._lifes = value

    @property
    def boost(self):
        """Return boost energy."""
        return self._boost

    @boost.setter
    def boost(self, value):
        """Set boost energy."""
        if value > MAX_BOOST:
            self._boost = MAX_BOOST
        elif value < 0:
            self._boost = 0
        else:
            self._boost = value

    def coll_check_head(self, collobjs):
        """Handle collisions for the snake's head."""
        for tag, obj in collobjs:
            if (tag.endswith('-body') or tag.endswith('-head')) and \
                    tag != self.snake.head_tag:
                obj.take_damage(35, self.snake.head_tag, False, True,
                                0.7, shrink=1, slowdown=0.03)
            elif tag == PORTAL_TAG:
                self.snake.heading = obj[1]
                self.snake[0] = add_vecs(obj[0], self.snake.heading)
            elif tag == PWRUP_TAG:
                for action in obj.actions:
                    target = self.pwrup_targets[action['target']]
                    if '.' in target:
                        target1, target2 = target.split('.')
                        attr = getattr(getattr(self, target1), target2)
                        setattr(getattr(self, target1),
                                target2, attr + action['value'])
                    else:
                        attr = getattr(self, target)
                        setattr(self, target, attr + action['value'])
                obj.collect()
            elif tag == SHOT_TAG:
                self.handle_shot(obj)

    def coll_check_body(self, collobjs):
        """Handle collisions for the snakes's body."""
        for tag, obj in collobjs:
            if tag == SHOT_TAG:
                self.handle_shot(obj)

    def handle_shot(self, shot):
        """Handle shot."""
        self.snake.take_damage(shot.damage, shot.tag, False, True, 1.2,
                               slowdown=shot.slowdown, shrink=1)
        shot.hit()

    def update(self, delta_time):
#.........这里部分代码省略.........
开发者ID:Phosphenius,项目名称:battle-snakes,代码行数:103,代码来源:player.py

示例7: PlayerBase

# 需要导入模块: from snake import Snake [as 别名]
# 或者: from snake.Snake import update [as 别名]
class PlayerBase(object):

    """
    Player base class.
    """

    def __init__(self, game, config):
        self.game = game
        self.pid = config['id']
        self.color = config['color']
        self.snake = Snake(game, game.get_spawnpoint(),
                           config['tex'], self.pid, self.snake_killed)
        self._lifes = INIT_LIFES
        self.points = 0
        self._boost = INIT_BOOST
        self.boosting = False
        self.weapons = deque((
            Weapon(self.game, self, STD_MG),
            Weapon(self.game, self, H_GUN),
            Weapon(self.game, self, PLASMA_GUN)))
        self.pwrup_targets = {'points': 'points', 'grow': 'snake.grow',
                              'speed': 'snake.speed', 'boost': 'boost',
                              'lifes': 'lifes', 'hp': 'snake.hitpoints'}

    @property
    def lifes(self):
        """Return lifes."""
        return self._lifes

    @lifes.setter
    def lifes(self, value):
        """Set lifes."""
        if value > MAX_LIFES:
            self._lifes = MAX_LIFES
        elif value < 0:
            self._lifes = 0
        else:
            self._lifes = value

    @property
    def boost(self):
        """Return boost energy."""
        return self._boost

    @boost.setter
    def boost(self, value):
        """Set boost energy."""
        if value > MAX_BOOST:
            self._boost = MAX_BOOST
        elif value < 0:
            self._boost = 0
        else:
            self._boost = value

    def coll_check_head(self, collobjs):
        """Handle collisions for the snake's head."""
        for tag, obj in collobjs:
            if (tag.endswith('-body') or tag.endswith('-head')) and \
                    tag != self.snake.head_tag:
                obj.take_damage(35, self.snake.head_tag, False, True,
                                0.7, shrink=1, slowdown=0.03)
            elif tag == PORTAL_TAG:
                self.snake.heading = obj[1]
                self.snake[0] = add_vecs(obj[0], self.snake.heading)
            elif tag == PWRUP_TAG:
                for action in obj.actions:
                    target = self.pwrup_targets[action['target']]
                    if '.' in target:
                        target1, target2 = target.split('.')
                        attr = getattr(getattr(self, target1), target2)
                        setattr(getattr(self, target1),
                                target2, attr + action['value'])
                    else:
                        attr = getattr(self, target)
                        setattr(self, target, attr + action['value'])
                obj.collect()
            elif tag == SHOT_TAG:
                self.handle_shot(obj)

    def coll_check_body(self, collobjs):
        """Handle collisions for the snakes's body."""
        for tag, obj in collobjs:
            if tag == SHOT_TAG:
                self.handle_shot(obj)

    def handle_shot(self, shot):
        """Handle shot."""
        self.snake.take_damage(shot.damage, shot.tag, False, True, 1.2,
                               slowdown=shot.slowdown, shrink=1)
        shot.hit()

    def update(self, delta_time):
        """Update player, move snake."""
        self.snake.update(delta_time)

        self.weapons[0].update(delta_time)

        if self.snake.heading != self.snake.prev_heading:
            self.snake.ismoving = True

#.........这里部分代码省略.........
开发者ID:YiYiWu,项目名称:battle-snakes,代码行数:103,代码来源:player.py


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