本文整理汇总了Python中snake.Snake类的典型用法代码示例。如果您正苦于以下问题:Python Snake类的具体用法?Python Snake怎么用?Python Snake使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Snake类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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
示例16: 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
开发者ID:nsylv,项目名称:snake,代码行数:10,代码来源:snakegame.py
示例17: move
def move():
data = bottle.request.json
#print "Received move ..." #request:{}".format(data)
my_id = data["you"]
board_width = data['width']
board_height = data['height']
snakes = data["snakes"]
snake = "yo"
for snake in snakes:
if snake["id"] == my_id:
our_snake = snake
me = Snake(my_id, board_height, board_width)
#print "Created snake with id = ", my_id
#blockades = map(lambda x: extend_head(x,me), data["snakes"])
blockades = []
for snake in data["snakes"]:
temp = extend_head(snake, me)
print "Snake coords: {}".format(temp)
blockades.extend(temp)
print "No go before: {}".format(blockades)
#blockades = blockades[0]
print "No go areas: {}".format(blockades)
#TODO limit based to first N food or based on threshold
food = map(tuple, data["food"])
#print "Food @ {}".format(food)
#food.sort(lambda xy: abs(xy[0] - me.head[0]) + abs(xy[1] - me.head[1]))
food.sort(key=lambda xy: abs(xy[0] - me.head[0]) + abs(xy[1] - me.head[1]))
food = food[:3]
#print "Food @ {}".format(food)
move = me.gather_food(food, blockades)
return {
'move': move, #random.choice(directions),
'taunt': random.choice(taunts)
}
开发者ID:tristanp2,项目名称:OldBattlesnake,代码行数:43,代码来源:main.py
示例18: __init__
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())
开发者ID:Dront,项目名称:snake,代码行数:10,代码来源:game.py
示例19: __init__
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,
])
开发者ID:mrpelotazo,项目名称:snake,代码行数:55,代码来源:game.py
示例20: __init__
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)
开发者ID:nishilv2,项目名称:hungry_snake,代码行数:13,代码来源:snake_game.py
注:本文中的snake.Snake类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论