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


Python Snake.eat方法代码示例

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


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

示例1: Game

# 需要导入模块: from snake import Snake [as 别名]
# 或者: from snake.Snake import eat [as 别名]
class Game(object):
    """
    This class represents an instance of the game.
    Works like simple state machine.
    """

    UPDATE_SNAKE = USEREVENT + 1

    def __init__(self):
        self.state = State.RUN

        self.player = Snake()
        self.run_snake_timer()

        self.map = Map(filename=params["DEFAULT_MAP"])

        self.fruit = pygame.sprite.GroupSingle()
        self.fruit.add(self.create_fruit())

    def create_fruit(self):
        free_tiles = self.map.ground_coords - self.player.coords
        new_coords = random.choice(list(free_tiles))
        return Fruit.create(new_coords)

    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
#.........这里部分代码省略.........
开发者ID:Dront,项目名称:snake,代码行数:103,代码来源:game.py

示例2: Game

# 需要导入模块: from snake import Snake [as 别名]
# 或者: from snake.Snake import eat [as 别名]
class Game(object):
    def __init__(self, window):
        self.snake = Snake()
        self.apple = Apple()
        self.window = window
        self.grid = []
        self.score = 0

    def move_snake(self, key):
        """Manual move of snake"""
        if key in [KEY_UP, KEY_DOWN, KEY_LEFT, KEY_RIGHT]:
            self.snake.move(key)
        else:
            self.snake.move(self.snake.last_direction)

        if self.snake.head == self.apple.position:
            self.snake.eat(self.apple, self.grid)
            self.score += 1

        if self.snake.is_collide():
            self.reset()

    def automove(self):
        """Deplace position of the snake with A* algorithm"""
        path = find_path(tuple(self.snake.head), tuple(self.apple.position), self.grid)
        move = path[0] if path else False

        if not move:
            move = self.any_possible_move()

        if move:
            if not self.snake.is_eating:
                self.snake.position.pop(0)

            self.snake.is_eating = False
            self.snake.position.append(move)
            self.snake.head = self.snake.position[-1]
            self.snake.tail = self.snake.position[0]

        if self.snake.head == self.apple.position:
            self.snake.eat(self.apple, self.grid)
            self.score += 1

        if self.snake.is_collide() or not move:
            self.reset()

    def any_possible_move(self):
        """Return any possible position"""
        neighbors = [(0, 1), (0, -1), (1, 0), (-1, 0)]
        for i, j in neighbors:
            neighbor = self.snake.head[0] + i, self.snake.head[1] + j
            if self.grid[neighbor[0]][neighbor[1]] == 0:
                return [neighbor[0], neighbor[1]]
        return False

    def display(self):
        """display game"""
        self.grid[:] = []
        for line in range(HEIGHT):
            self.grid.append([])
            for column in range(WIDTH):
                if column == 0 or line == 0 or column == WIDTH - 1 or line == HEIGHT - 1:
                    self.grid[line].append(1)
                else:
                    self.grid[line].append(0)

        for line, column in self.snake.position:
            self.grid[line][column] = 1
            self.window.addstr(line, column, 's')

        line, column = self.apple.position
        self.window.addstr(line, column, 'a')

    def reset(self):
        """Reset game"""
        self.apple.reset()
        self.snake.reset()
        self.score = 0
开发者ID:marmelab,项目名称:snake_solver_one,代码行数:80,代码来源:game.py

示例3: SnakeGame

# 需要导入模块: from snake import Snake [as 别名]
# 或者: from snake.Snake import eat [as 别名]
class SnakeGame(object):
    def __init__(self, tk, speed):
        self.food = (randint(0, 20), randint(0, 20))
        self.speed = speed
        self.snake = Snake()
        self.tk = tk
        self.button = Button(tk, text="start game!", command=self.run)
        self.canvas = Canvas(tk, width=410, height=410, bg="black")
        self.button.pack()
        self.canvas.pack()
        self.tk.bind("<KeyPress-Up>", self.up_event)
        self.tk.bind("<KeyPress-Down>", self.down_event)
        self.tk.bind("<KeyPress-Right>", self.right_event)
        self.tk.bind("<KeyPress-Left>", self.left_event)

    def run(self):
        if self.snake.eat(self.food):
            eat_flag = 1
            self.food = None
        else:
            eat_flag = 0
        self.snake.move(eat_flag)
        if self.not_over():
            self.canvas.delete("all")
            self.draw_food()
            self.draw_snake()
            self.tk.after(self.speed, self.run)
        else:
            r = tkMessageBox.showinfo("Oh,game over!")
            if r == "ok":
                sys.exit()

    def not_over(self):
        if self.is_rush_wall() or self.is_rush_self():
            return 0
        else:
            return 1

    def draw_snake(self):
        for i in range(0, self.snake.body.__len__()):
            x0, y0 = Api.position_to_pix(self.snake.body[i][0], self.snake.body[i][1])
            x1 = x0+10
            y1 = y0+10
            self.canvas.create_rectangle(x0, y0, x1, y1, fill="white", outline=None, width=0)
            if i != (self.snake.body.__len__()-1):
                x2, y2 = Api.position_to_pix(self.snake.body[i+1][0], self.snake.body[i+1][1])
                x3 = (x0 + x2)/2
                y3 = (y0 + y2)/2
                x4 = x3+10
                y4 = y3+10
                self.canvas.create_rectangle(x3, y3, x4, y4, fill="white", outline=None, width=0)

    def change_snake_direction(self, direction):
        r = self.snake.change_direction(direction)
        if not r:
            print "you can't do that"

    def up_event(self, event):
        self.change_snake_direction("up")
        print "up"

    def down_event(self, event):
        self.change_snake_direction("down")
        print "down"

    def right_event(self, event):
        self.change_snake_direction("right")
        print "right"

    def left_event(self, event):
        self.change_snake_direction("left")
        print "left"

    def food_exist(self):
        if self.food is None:
            return 0
        else:
            return 1

    def draw_food(self):

        if not self.food_exist():
            world = []
            for i in range(0, 21):
                for j in range(0, 21):
                    world.insert(-1, (i, j))
            for item in self.snake.body:
                world.remove(item)
            self.food = world[randint(0, world.__len__()-1)]
        x0, y0 = Api.position_to_pix(self.food[0], self.food[1])
        x1 = x0+10
        y1 = y0+10
        self.canvas.create_rectangle(x0, y0, x1, y1, fill="white", outline=None, width=0)

    def is_rush_wall(self):
        if (self.snake.body[0][0] >= 0) and (self.snake.body[0][0] <= 20):
            if (self.snake.body[0][1] >= 0) and (self.snake.body[0][1] <= 20):
                return 0
            else:
                return 1
#.........这里部分代码省略.........
开发者ID:nishilv2,项目名称:hungry_snake,代码行数:103,代码来源:snake_game.py


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