本文整理汇总了Python中snake.Snake.change_dir方法的典型用法代码示例。如果您正苦于以下问题:Python Snake.change_dir方法的具体用法?Python Snake.change_dir怎么用?Python Snake.change_dir使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类snake.Snake
的用法示例。
在下文中一共展示了Snake.change_dir方法的1个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: Game
# 需要导入模块: from snake import Snake [as 别名]
# 或者: from snake.Snake import change_dir [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
#.........这里部分代码省略.........