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


Python Snake.grow方法代码示例

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


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

示例1: Engine

# 需要导入模块: from snake import Snake [as 别名]
# 或者: from snake.Snake import grow [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

示例2: SnakeGame

# 需要导入模块: from snake import Snake [as 别名]
# 或者: from snake.Snake import grow [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

示例3: __init__

# 需要导入模块: from snake import Snake [as 别名]
# 或者: from snake.Snake import grow [as 别名]

#.........这里部分代码省略.........
                x * BLOCK_SIZE,
                0,
            ))
            self.screen.blit(self.wallblockdark, (
                x * BLOCK_SIZE + 5,
                5,
            ))
            self.screen.blit(self.wallblock, (
                x * BLOCK_SIZE,
                (HEIGHT + 1) * BLOCK_SIZE,
            ))
            self.screen.blit(self.wallblockdark, (
                x * BLOCK_SIZE + 5,
                (HEIGHT + 1) * BLOCK_SIZE + 5,
            ))

    def loop(self):
        """The game's main loop"""
        while True:
            # check crash or move outside the limits
            if self.snake.outside_limits(WIDTH, HEIGHT) or self.snake.crashed:
                self.crashsound.play()
                return

            # draw screen with snake and foods
            self.food.draw()
            self.snake.draw()
            self.draw_walls()
            pygame.display.flip()

            # check if snake eates
            if self.food.get_pos() == self.snake.get_head_pos():
                self.eatsound.play()
                self.snake.grow()
                # food should not appear where the snake is
                self.food = Food(self.screen, 1, HEIGHT + 1, 1, WIDTH + 1)
                while self.food.get_pos() in self.snake.pos_list:
                    self.food = Food(self.screen, 1, HEIGHT + 1, 1, WIDTH + 1)
                self.eaten += 1
                # increase game speed
                if self.eaten % SPEED_INC == 0:
                    self.speed += SPEED_TICK

            # game speed control
            self.clock.tick(self.speed)

            # get the next event on queue
            event = pygame.event.poll()
            if event.type == pygame.QUIT:
                sys.exit()
            elif event.type == pygame.KEYDOWN:
                actmotdir = self.snake.motion_dir
                if event.key == pygame.K_ESCAPE:
                    sys.exit()
                elif event.key == pygame.K_UP and actmotdir != DOWN:
                    self.snake.motion_dir = UP
                elif event.key == pygame.K_DOWN and actmotdir != UP:
                    self.snake.motion_dir = DOWN
                elif event.key == pygame.K_RIGHT and actmotdir != LEFT:
                    self.snake.motion_dir = RIGHT
                elif event.key == pygame.K_LEFT and actmotdir != RIGHT:
                    self.snake.motion_dir = LEFT

            # remove the snake and make movement
            self.snake.remove()
            self.snake.move()
开发者ID:mrpelotazo,项目名称:snake,代码行数:70,代码来源:game.py

示例4: SnakeGame

# 需要导入模块: from snake import Snake [as 别名]
# 或者: from snake.Snake import grow [as 别名]
class SnakeGame(object):
    """
    Represents game object, handles snake's movement and drawing,
    mice creating, score count, draws everything.
    """

    def __init__(self):
        secure_screen_size()
        pg.init()               # initialize pygame module

        pg.display.set_caption('PySnake Game')

        # height of upper bound line of the drawing frame
        self._snake_width = FRAME_SIZE/FRAME_WIDTH_TO_SNAKE_WIDTH
        # make main screen surface a little bit higher (for score text)
        self._screen = pg.display.set_mode((FRAME_SIZE, FRAME_SIZE + self._snake_width * 2))

        # make a subsurface from screen surface. It will be rectangle where snake will move
        self._frame = self._screen.subsurface([0, self._snake_width*2, FRAME_SIZE, FRAME_SIZE])

        # set of all grid fields: range for x and y go from 0 to SCREEN_WIDTH_TO_SNAKE_WIDTH - 1
        # it will be used to pick a place for draw mouse for snake to chase
        self._grid_field_list = [(x, y) for x in xrange(FRAME_WIDTH_TO_SNAKE_WIDTH) for y in xrange(FRAME_WIDTH_TO_SNAKE_WIDTH)]
        self._grid_field_size = self._screen.get_width() / FRAME_WIDTH_TO_SNAKE_WIDTH   # in pixels

        # initialize font
        self._font = pg.font.SysFont("monospace", self._snake_width*2 - 3)

        # create snake
        self._snake = Snake(self._frame, self._snake_width)

        # Clock object is used to slow down and main loop, it ensures the FPS
        self._clock = pg.time.Clock()

        # default speed of the game
        self._speed = 10
        # default speed increment when snake catches mouse
        self._speed_inc = 3
        # increment score when snake catches the mouse
        self._score = 0

    def run(self):
        # draw the white background onto the surface
        self._frame.fill(BLACK)

        # draw frame for the game
        self._draw_frame_line()
        self._draw_score()
        self._snake.draw(draw_everything=True)
        mouse_pos = self._draw_mouse()
        pg.display.update()

        running = True
        direction = DIR_RIGHT   # initial movement direction
        while self._snake.move(direction) and running:
            self._snake.draw()
            self._draw_frame_line()

            # check if snake's head is on the mouse field
            if self._snake.head() == mouse_pos:
                self._delete_score()
                self._score += 1
                self._snake.grow()
                self._delete_mouse(mouse_pos)   # snake eats mouse -> remove it from field
                mouse_pos = self._draw_mouse()  # re-draw mouse again
                self._speed += self._speed_inc  # increase play speed

            self._draw_score()
            pg.display.flip()

            self._clock.tick(self._speed)   # ensure frame rate of the game: higher the FPS -> snake will be faster

            for event in pg.event.get():
                if event.type is pg.QUIT:
                    running = False
                elif event.type is pg.KEYDOWN:
                    if event.key == pg.K_ESCAPE:
                        running = False
                    elif event.key == pg.K_LEFT:
                        direction = DIR_LEFT
                    elif event.key == pg.K_RIGHT:
                        direction = DIR_RIGHT
                    elif event.key == pg.K_UP:
                        direction = DIR_UP
                    elif event.key == pg.K_DOWN:
                        direction = DIR_DOWN

    def _draw_mouse(self):
        """
        Picks random location and draws mouse
        :return: mouse location -> tuple (x,y)
        """

        pos = self._snake.grid_occupied[0]
        while pos in self._snake.grid_occupied:
            pos = (randint(0, FRAME_WIDTH_TO_SNAKE_WIDTH-1), randint(0, FRAME_WIDTH_TO_SNAKE_WIDTH-1))

        # draw a pink circle onto the surface
        center = (pos[0] * self._grid_field_size + self._grid_field_size / 2,
                  pos[1] * self._grid_field_size + self._grid_field_size / 2)
#.........这里部分代码省略.........
开发者ID:kecabojan,项目名称:PySnake,代码行数:103,代码来源:pysnake.py

示例5: Game

# 需要导入模块: from snake import Snake [as 别名]
# 或者: from snake.Snake import grow [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


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