Advertisement
Guest User

Untitled

a guest
May 26th, 2018
65
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.63 KB | None | 0 0
  1. from .field import Field
  2. from .cells import SnakeCell, DeathWallCell, FoodCell, FoodCell_poison
  3.  
  4.  
  5. class SnakeState:
  6. TURNS = {
  7. 'up': (-1, 0),
  8. 'down': (1, 0),
  9. 'left': (0, -1),
  10. 'right': (0, 1),
  11. }
  12.  
  13. def __init__(self, head_position, start_length, direction):
  14. self.head = head_position
  15. self.len = start_length
  16. self.direction = direction
  17.  
  18. def turn(self, direction):
  19. if direction not in self.TURNS.keys():
  20. raise ValueError('{0} is not a valid side' % direction)
  21. self.direction = direction
  22.  
  23. def get_next_position(self):
  24. dy, dx = self.TURNS[self.direction]
  25. return self.head[0] + dy, self.head[1] + dx
  26.  
  27.  
  28. class Game:
  29. def __init__(self, width=20, height=20):
  30. self.field = Field(width, height)
  31. self.snake = SnakeState((1, 2), 2, 'right')
  32.  
  33. self.is_paused = True
  34. self.is_dead = False
  35. self.score = 0
  36.  
  37. self.init_level()
  38.  
  39. def init_level(self):
  40. self.field.set_cell(1, 1, SnakeCell(time_to_live=1))
  41. self.field.set_cell(1, 2, SnakeCell(time_to_live=2))
  42.  
  43. for x in range(self.field.width):
  44. self.field.set_cell(0, x, DeathWallCell())
  45. self.field.set_cell(self.field.width - 1, x, DeathWallCell())
  46.  
  47. for y in range(self.field.height):
  48. self.field.set_cell(y, 0, DeathWallCell())
  49. self.field.set_cell(y, self.field.height - 1, DeathWallCell())
  50.  
  51. self.spawn_food()
  52. self.spawn_food_poison()
  53.  
  54. def spawn_food(self):
  55. y, x = self.field.get_random_empty_cell()
  56. self.field.set_cell(y, x, FoodCell())
  57.  
  58. def spawn_food_poison(self):
  59. y1, x1 = self.field.get_random_empty_cell()
  60. self.field.set_cell(y1, x1, FoodCell_poison())
  61.  
  62. def pause(self):
  63. self.is_paused = not self.is_paused
  64.  
  65. def turn(self, side):
  66. self.snake.turn(side)
  67.  
  68. def update(self):
  69. if self.is_paused or self.is_dead:
  70. return
  71.  
  72. if not self.try_move_head():
  73. self.is_dead = True
  74. return
  75.  
  76. cell = self.field.get_cell(*self.snake.head)
  77. if cell is not None:
  78. cell.on_bump(self)
  79.  
  80. if self.is_dead:
  81. return
  82.  
  83. self.field.update(game=self)
  84.  
  85. self.field.set_cell(*self.snake.head, SnakeCell(time_to_live=self.snake.len))
  86.  
  87. def try_move_head(self):
  88. new_y, new_x = self.snake.get_next_position()
  89.  
  90. if self.field.contains_cell(new_y, new_x):
  91. self.snake.head = new_y, new_x
  92. return True
  93. return False
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement