當前位置: 首頁>>代碼示例>>Python>>正文


Python snake.Snake類代碼示例

本文整理匯總了Python中snake.Snake的典型用法代碼示例。如果您正苦於以下問題:Python Snake類的具體用法?Python Snake怎麽用?Python Snake使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


在下文中一共展示了Snake類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: join_player

    def join_player(self, player):
        """
        Join a player to the game.
        @player: A Player instance.
        """
        playerCount = len(self.world.players)
        # build up a snake
        snakeData = self.snakeDatas[playerCount]
        snake = Snake(self.world, player)
        snake.gen_body(*snakeData)
        player.snake = snake
        # let the snake's name same as the player's name
        snake.name = player.name
        # add snake and player to the world
        self.world.snakes.append(snake)
        self.world.players.append(player)
        # emit a SNAKE_BORN event
        self.eventMgr.emit(events.SnakeBorn(snake))
        # bind gameevent handlers
        def handler(event):
            snake = event.snake
            food = event.food
            if snake is player.snake:
                snake.player.score += food.score

        self.eventMgr.bind(EventTypes.SNAKE_EAT, handler)
        return player
開發者ID:Richie12138,項目名稱:sys-analysis,代碼行數:27,代碼來源:game.py

示例2: move

 def move(self):
     if self.travel_points:
         self.x, self.y = self.travel_points.pop(0)
     Snake.move(self, by_dir=False)
     #apple location moved, recalculate path to it
     if self.apple.pos != self.apple_loc:
         self.generate_path()
         self.apple_loc = self.apple.pos
開發者ID:Riamse,項目名稱:cnake,代碼行數:8,代碼來源:ai_py2.py

示例3: __init__

 def __init__(self, width, height):
     Snake.__init__(self, width, height - 5)
     self.travel_points = []
     self.apple_loc = self.apple.pos
     #DEBUG
     #self.f = open('log.out', 'w')
     self.generate_path()
     self.quit = False
     self.start = False
開發者ID:Riamse,項目名稱:cnake,代碼行數:9,代碼來源:ai_py2.py

示例4: Engine

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,代碼行數:56,代碼來源:engine.py

示例5: exportSplineImage

def exportSplineImage(size=500, cps=4):
	from snake import Snake
	size = 500
	rnd = lambda: np.random.randint(0, size)
	image = vigra.RGBImage((size, size), value=4.0)
	snake = Snake(image=image)
	snake.addControlPoints(*[(rnd(), rnd()) for i in range(cps)])
	gs = contourCurvatureGradient(snake.contour, snake.controlpoints, snake.crv_energies)
	for i in range(len(gs)):
		image[snake.contour[i][0]][snake.contour[i][1]] = [125*gs[i], 255 - (125*gs[i]), 0]
	vigra.impex.writeImage(image, '/home/max/Desktop/spline_colours.png')
開發者ID:mamachanko,項目名稱:SnakeIsland,代碼行數:11,代碼來源:utils.py

示例6: main

def main():
  s = Snake()
  clock = pygame.time.Clock()
  signal = [SIG_NOOP] # it's an array to make sure Snake.run() actually modifies THIS, instead of making a copy and discarding it when it goes out of scope
  while 1:
    WINDOW.fill(s.background_color)
    s.run(signal)
    if signal[0]: break
    pygame.display.update()
    clock.tick(FPS)
  if signal[0] == SIG_QUIT:
    pygame.quit()
    exit()
  elif signal[0] == SIG_RESTART:
    main()
開發者ID:bradenbest,項目名稱:snake,代碼行數:15,代碼來源:main.py

示例7: __init__

    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
開發者ID:kecabojan,項目名稱:PySnake,代碼行數:34,代碼來源:pysnake.py

示例8: __init__

 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)
開發者ID:chaotism,項目名稱:python-snake,代碼行數:7,代碼來源:engine.py

示例9: Game

class Game(object):

    _gamespeed = 0.6
    _snake = None
    _gameboard = None
    _screen = None

    def __init__(self):
        # Create the screen object
        curses.initscr()
        self._screen = curses.newwin(20, 20, 0, 0) #curses.initscr()
        self._screen.keypad(1)
        self._screen.nodelay(1)
        self._screen.timeout(150)
        self._screen.border(1)


        curses.noecho()
        curses.cbreak()

        self._gameboard = Gameboard((20, 20), self._screen)
        self._snake = Snake(self._gameboard)

    def run(self):
        key = KEY_RIGHT
        try:
            while 1:
                event = self._screen.getch()
                key = key if event == -1 else event
                s = None

                if key == KEY_UP:
                    s = SnakeMoveDirection.up
                elif key == KEY_DOWN:
                    s = SnakeMoveDirection.down
                elif  key == KEY_LEFT:
                    s = SnakeMoveDirection.left
                elif key == KEY_RIGHT:
                    s = SnakeMoveDirection.right

                self._snake.move(s)
                self._gameboard.draw()
        finally:
            curses.echo()
            curses.nocbreak()
            curses.endwin()
開發者ID:tspycher,項目名稱:python-snake,代碼行數:46,代碼來源:game.py

示例10: load_from_json

    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)
開發者ID:styts,項目名稱:snakes,代碼行數:17,代碼來源:state.py

示例11: __init__

 def __init__(self, gridWidth, gridHeight):
     self.gridWidth = gridWidth
     self.gridHeight = gridHeight
     self.food = Space(randint(0, gridWidth - 1), randint(0, gridHeight - 1))
     self.traindata = []
     self.state = None
     self.alive = True
     self.snake = Snake(self)
開發者ID:spafindoople,項目名稱:SpafinDoople.github.io,代碼行數:8,代碼來源:snakegame.py

示例12: __init__

 def __init__(self, parent):
     super(SnakeWidget, self).__init__(parent)
     self.snake = Snake()
     self.newGame()
     self.colors = [QtGui.QColor(255, 0, 0, 255),
                    QtGui.QColor(255, 255, 0, 255),
                    QtGui.QColor(0, 0, 255, 255),
                    QtGui.QColor(0, 255, 0, 255)]
開發者ID:bitterfly,項目名稱:tamagotchi,代碼行數:8,代碼來源:snake_widget.py

示例13: World

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,代碼行數:46,代碼來源:world.py

示例14: reset

 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()
開發者ID:chaotism,項目名稱:python-snake,代碼行數:8,代碼來源:engine.py

示例15: main

def main():
    # ---Initialize Screen---
    screen = pygame.display.set_mode((300, 275), 0, 32)
    pygame.display.set_caption('Snake')

    mainMenu = ('Play Game', 'High Scores', 'Settings', 'Quit')
    backgroundColor = (255, 255, 255)

    settings = {'snakeLength':5, 'fontName':'inconsolata.otf',
                'foodColor':(255,0,0)}

    #List of tuples formatted (user, score)
    highScoreList = []

    readScoresFromFile(highScoreList)
    sortScores(highScoreList)
    mainMenu = SingleColumnMenu(screen, mainMenu, fontName = settings['fontName'])
    while(True):
        choice = mainMenu.run()
        if choice == 'Play Game':
            #Create instance of Snake.py
            snake = Snake(screen)

            displayCountdown(screen, backgroundColor)

            #Runs game and returns player score
            newScore = snake.gameLoop()

            #Prompts user for name
            userName = getUsername(screen, backgroundColor, settings)

            #Adds to high Scores
            highScoreList.append((userName, newScore))
            sortScores(highScoreList)

        elif choice == 'High Scores':
            highScores = ScoreDisplay(screen, highScoreList,
                            fontName = settings['fontName'])
            #highScores.setFont(settings['fontName'])
            highScores.run()
        elif choice == 'Quit':
            break
        choice == ""
    saveScoresToFile(highScoreList)
開發者ID:EvanDHiggins,項目名稱:snake,代碼行數:44,代碼來源:main.py


注:本文中的snake.Snake類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。