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


Python Snake.draw方法代码示例

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


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

示例1: __init__

# 需要导入模块: from snake import Snake [as 别名]
# 或者: from snake.Snake import draw [as 别名]
class Game:
    """The main class that makes up the game"""

    def __init__(self):
        """Constructor"""
        self.speed = START_SPEED

        # will increase game speed every 10 times we eat
        self.eaten = 0

        # defining the outer wall blocks
        self.wallblock = pygame.Surface((
            BLOCK_SIZE,
            BLOCK_SIZE,
        ))
        self.wallblock.set_alpha(255)
        self.wallblock.fill(BLUE)

        self.wallblockdark = pygame.Surface((
            BLOCK_SIZE_INNER,
            BLOCK_SIZE_INNER,
        ))
        self.wallblockdark.set_alpha(255)
        self.wallblockdark.fill(BLUE_DARK)

        # initialize pygame, clock for game speed and screen to draw
        pygame.init()

        # initializing mixer, sounds, clock and screen
        pygame.mixer.init()
        self.eatsound = pygame.mixer.Sound("snakeeat.wav")
        self.crashsound = pygame.mixer.Sound("snakecrash.wav")
        self.clock = pygame.time.Clock()
        self.screen = pygame.display.set_mode((
            (WIDTH + 2) * BLOCK_SIZE,
            (HEIGHT + 2) * BLOCK_SIZE,
        ))
        pygame.display.set_caption("snake")
        font = pygame.font.SysFont(pygame.font.get_default_font(), 40)
        self.gameovertext = font.render("GAME OVER", 1, WHITE)
        self.starttext = font.render("PRESS ANY KEY TO START", 1, WHITE)
        self.screen.fill(BLACK)

        # we need a snake and something to eat
        self.snake = Snake(self.screen, WIDTH // 2, HEIGHT // 2)
        self.food = Food(self.screen, 1, HEIGHT + 1, 1, WIDTH + 1)

        # food should not appear where the snake is
        while self.food.get_pos() in self.snake.pos_list:
            self.food = Food(self.screen, 1, HEIGHT + 1, 1, WIDTH + 1)

        # only queue quit and and keydown events
        # pygame.event.set_allowed([pygame.QUIT, pygame.KEYDOWN])
        pygame.event.set_blocked([
            pygame.MOUSEMOTION,
            pygame.MOUSEBUTTONUP,
            pygame.MOUSEBUTTONDOWN,
        ])

    def draw_walls(self):
        """Draw all walls of the game surface"""
        # left and right walls
        for y in range(HEIGHT + 1):  # pylint: disable=invalid-name
            self.screen.blit(self.wallblock, (
                0,
                y * BLOCK_SIZE,
            ))
            self.screen.blit(self.wallblockdark, (
                5,
                y * BLOCK_SIZE + 5,
            ))
            self.screen.blit(self.wallblock, (
                (WIDTH + 1) * BLOCK_SIZE,
                y * BLOCK_SIZE,
            ))
            self.screen.blit(self.wallblockdark, (
                (WIDTH + 1) * BLOCK_SIZE + 5,
                y * BLOCK_SIZE + 5,
            ))

        # upper and bottom walls
        for x in range(WIDTH + 2):  # pylint: disable=invalid-name
            self.screen.blit(self.wallblock, (
                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):
#.........这里部分代码省略.........
开发者ID:mrpelotazo,项目名称:snake,代码行数:103,代码来源:game.py

示例2: SnakeGame

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

示例3: Game

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

#.........这里部分代码省略.........
    def run_snake_timer(self, run=True):
        if run:
            pygame.time.set_timer(self.UPDATE_SNAKE, params['STEP_TIME'])
        else:
            pygame.time.set_timer(self.UPDATE_SNAKE, 0)

    def process_events(self):
        """
        Process all of the events.
        Return True if window must be closed.
        """

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

            if event.type == self.UPDATE_SNAKE:
                self.player.go()

            if event.type == pygame.KEYDOWN:

                # esc pressed - quit
                if event.key == pygame.K_ESCAPE:
                    return True

                if self.state == State.RUN:
                    if event.key == pygame.K_UP:
                        self.player.change_dir('UP')
                    elif event.key == pygame.K_DOWN:
                        self.player.change_dir('DOWN')
                    elif event.key == pygame.K_LEFT:
                        self.player.change_dir('LEFT')
                    elif event.key == pygame.K_RIGHT:
                        self.player.change_dir('RIGHT')

                    elif event.key == pygame.K_q:
                        self.state = State.GAME_OVER
                        self.run_snake_timer(False)

                    elif event.key == pygame.K_p:
                        self.state = State.PAUSE
                        self.run_snake_timer(False)

                elif self.state == State.PAUSE:
                    if event.key == pygame.K_q:
                        self.state = State.GAME_OVER
                    else:
                        self.state = State.RUN
                        self.run_snake_timer()

                elif self.state == State.GAME_OVER:
                    self.__init__()


        return False

    def run_logic(self):
        """
        Updates positions.
        """
        if self.state == State.RUN:

            # collision with wall
            if pygame.sprite.spritecollideany(self.player.head, self.map.obstacles):
                self.state = State.GAME_OVER

            # collision with tail
            elif pygame.sprite.spritecollideany(self.player.head, self.player.body):
                self.state = State.GAME_OVER

            # ate a fruit
            ate = pygame.sprite.spritecollideany(self.player.head, self.fruit.sprites())
            if ate is not None:
                self.player.eat(ate)
                if self.player.score > params['HIGH_SCORE']:
                    params['HIGH_SCORE'] = self.player.score
                    save_params()

                self.fruit.add(self.create_fruit())

    def display_frame(self, screen):
        """ Display everything to the screen. """
        screen.fill(params['BG_COLOR'])
        # screen.blit(self.bg_pic, (0, 0))

        if self.state == State.GAME_OVER:
            utils.draw_screen(screen, params['GAME_OVER_TEXT'])

        elif self.state == State.PAUSE:
            utils.draw_screen(screen, params['GAME_PAUSED_TEXT'])

        elif self.state == State.RUN:
            # utils.draw_grid(screen)
            self.map.draw(screen)
            self.fruit.draw(screen)
            self.player.draw(screen)

        utils.draw_score(screen, self.player.score, params['HIGH_SCORE'])

        pygame.display.flip()
开发者ID:Dront,项目名称:snake,代码行数:104,代码来源:game.py

示例4: Snake

# 需要导入模块: from snake import Snake [as 别名]
# 或者: from snake.Snake import draw [as 别名]
screen = pygame.display.set_mode([640, 480])
# Set the title of the window
pygame.display.set_caption('Python-Snake')
length = 3
direction = 0
locations = []
directions = []

snake = Snake((250, 90), length, direction)

clock = pygame.time.Clock()
done = False

# Clear screen
screen.fill(black)
snake.draw(screen)
# Flip screen
pygame.display.flip()
# Pause
clock.tick(1)

while done == False:
	for event in pygame.event.get():
		if (event.type == pygame.QUIT):
			done = True
		if (event.type == pygame.KEYDOWN):
			if (event.key == pygame.K_LEFT):
				direction = 2
			if (event.key == pygame.K_RIGHT):
				direction = 0
			if (event.key == pygame.K_UP):
开发者ID:Daffie,项目名称:Python-Snake,代码行数:33,代码来源:test.py

示例5: PlayerBase

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

#.........这里部分代码省略.........
            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."""
        if not self.snake:
            return

        self.snake.update(delta_time)

        self.weapons[0].update(delta_time)

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

        if self.boost < BOOST_COST * delta_time:
            self.boosting = False
            self.snake.speed_bonus = 0

        if self.boosting:
            boost = self.boost - BOOST_COST * delta_time
            if boost < BOOST_COST * delta_time:
                self.boost = 0
            else:
                self.boost = boost
        else:
            self.boost = self.boost + BOOST_GAIN * delta_time

    def draw(self, offset):
        """Draw snake and UI."""
        if not self.snake:
            return

        self.snake.draw()

        gfx = self.game.graphics

        gfx.draw_string(add_vecs((2, 2), offset),
                        'Player{0}'.format(self.pid), self.color)

        gfx.draw_string(add_vecs((56, 2), offset),
                        '{0:.2f}'.format(self.snake.speed), WHITE)

        gfx.draw_string(add_vecs((2, 18), offset),
                        'Points: {0}'.format(self.points), WHITE)

        pygame.draw.rect(self.game.screen, ORANGE,
                         pygame.Rect(add_vecs((100, 2), offset),
                                     (104, 20)))

        # Draw life bar. TODO: Make this some kinda class.
        width = int(self.snake.hitpoints / float(MAX_HITPOINTS) * 100)
        rect = pygame.Rect(add_vecs((102, 4), offset), (width, 7))
        pygame.draw.rect(self.game.screen, RED, rect)

        if self.boost_enabled:
            width = int(self.boost / float(MAX_BOOST) * 100)
            rect = pygame.Rect(add_vecs((102, 13), offset), (width, 7))
            pygame.draw.rect(self.game.screen, BLUE, rect)

        gfx.draw_string(add_vecs((208, 2), offset),
                        '{0} {1}'.format(self.weapons[0].wtype,
                                         self.weapons[0].ammo), WHITE)

        for index in range(self.lifes):
            gfx.draw('life16x16', add_vecs((100, 24), offset),
                     gridcoords=False, offset=(index*18, 0))

    def snake_killed(self, killed_by):
        """Snake killed event handler."""
        if self.lifes > 0:
            self.lifes -= 1
            self.boost = MAX_BOOST
            self.snake.respawn(self.tilemap.get_spawnpoint())
        else:
            self.dead_handler()
开发者ID:Phosphenius,项目名称:battle-snakes,代码行数:104,代码来源:player.py

示例6: PlayerBase

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

#.........这里部分代码省略.........
        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

        if self.boost < BOOST_COST * delta_time:
            self.boosting = False
            self.snake.speed_bonus = 0

        if self.boosting:
            boost = self.boost - BOOST_COST * delta_time
            if boost < BOOST_COST * delta_time:
                self.boost = 0
            else:
                self.boost = boost
        else:
            self.boost = self.boost + BOOST_GAIN * delta_time

    def draw(self, offset):
        """Draw snake and UI."""
        self.snake.draw()
        self.game.draw_string('Player{0}'.format(self.pid),
                              add_vecs((2, 2), offset), self.color)
        self.game.draw_string('{0:.2f}'.format(self.snake.speed),
                              add_vecs((56, 2), offset), WHITE)
        self.game.draw_string('Points: {0}'.format(self.points),
                              add_vecs((2, 18), offset), WHITE)

        pygame.draw.rect(self.game.screen, ORANGE,
                         pygame.Rect(add_vecs((100, 2), offset), (104, 20)))

        pygame.draw.rect(self.game.screen, RED,
                         pygame.Rect(add_vecs((102, 4), offset), (int(
                             self.snake.hitpoints /
                             float(MAX_HITPOINTS) * 100), 7)))

        pygame.draw.rect(self.game.screen, BLUE,
                         pygame.Rect(add_vecs((102, 13), offset), (int(
                             self.boost / float(MAX_BOOST) * 100), 7)))

        self.game.draw_string('{0} {1}'.format(self.weapons[0].wtype,
                                               self.weapons[0].ammo),
                              add_vecs((208, 2), offset), WHITE)

        for i in range(self.lifes):
            self.game.graphics.draw('life16x16', add_vecs((100, 24), offset),
                                    gridcoords=False, offset=(i*18, 0))

    def snake_killed(self, killed_by):
        """Snake killed event handler."""
        if self.lifes > 0:
            self.lifes -= 1
            self.boost = MAX_BOOST
            self.snake.respawn(self.game.get_spawnpoint())
开发者ID:YiYiWu,项目名称:battle-snakes,代码行数:104,代码来源:player.py


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