本文整理汇总了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
示例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
示例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
示例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()
示例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')
示例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()
示例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
示例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)
示例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()
示例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)
示例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)
示例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)]
示例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)
示例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()
示例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)