def __init__(self): self.started = False self.bg_colour = (240, 160, 212) self.area_info = (0, 0, 450, 450) self.cell_amt = 18 self.back_colour = Color(231, 242, 198) self.cell_colour = Color(200, 200, 227) self.cell_size = (self.area_info[2] // self.cell_amt, self.area_info[3] // self.cell_amt) self.play_rect = Rect(self.area_info) self.play_surf = Surface(self.area_info[2:]) self.play_surf.fill(self.back_colour) self.circ_radius = 25 self.fruit = Collectible(self.cell_size, self.cell_amt) self.score = 0 self.snake = Snake(self.cell_size, self.cell_amt) self.snake_is_dead = False self.draw_checkerboard() self.font = SysFont("Arial", 30) self.text = self.font.render("Score: 0", False, self.back_colour)
def test_up(): mapping = {"right": "up", "left": "up", "up": "up", "down": "down"} for key in DIRECTIONS: snake = Snake() snake.direction = key snake.up() assert snake.direction == mapping[key]
def test_simulate(): snake = Snake() snake.simulate() assert type(snake.head_location[0]) is int assert type(snake.head_location[1]) is int for i, val1 in enumerate(snake.snake_matrix): for j, val2 in enumerate(snake.snake_matrix[i]): assert type(snake.snake_matrix[i][j]) is int
def __init__(self, settings): self.boardWidth = getSetting(settings, "boardWidth", 10) self.boardHeight = getSetting(settings, "boardHeight", 10) self.cellSize = getSetting(settings, "cellSize", 10) self.snake = Snake(settings, self.boardWidth / 2, self.boardHeight / 2) self.isDead = False self.item = Item(settings) self.reinitItem()
def __init__(self, canvas: tk.Canvas): self.canvas = canvas self.grid = list() self.size = [24, 24] self.snake = Snake(self.size) self.score = 0 w = self.size[0] * Box.size + 1 h = self.size[1] * Box.size + 1 self.canvas.configure(width=w, height=h)
def __init__(self, x, y): size = constants.BOARD_SIZE * constants.PIXEL_SIZE border_size = constants.BORDER_SIZE * 2 + size self.border_box = pg.rect.Rect((x, y), (border_size, border_size)) self.box = pg.rect.Rect((x + constants.BORDER_SIZE, y + constants.BORDER_SIZE), (size, size)) self.score = 3 self.score_font = pg.font.Font(Assets.BOXY_FONT, 24) self.snake = Snake(int(constants.BOARD_SIZE / 2), constants.BOARD_SIZE / 2) self.fruit = Fruit() self.clock = pg.time.Clock() self.count = 0
def test(args, env): # load the snake s = Snake(filename=args.load_file) # play the game obs, score, done = env.reset() while not done: time.sleep(1 / args.fps) env.render() action = s.action(obs) obs, score, done = env.step(action) env.render()
class Board(): def __init__(self, settings): self.boardWidth = getSetting(settings, "boardWidth", 10) self.boardHeight = getSetting(settings, "boardHeight", 10) self.cellSize = getSetting(settings, "cellSize", 10) self.snake = Snake(settings, self.boardWidth / 2, self.boardHeight / 2) self.isDead = False self.item = Item(settings) self.reinitItem() def draw(self, screen): self.move() screen.fill(style.BoardFillColor) for row in range(0, self.boardWidth): for column in range(0, self.boardHeight): x = row * self.cellSize y = column * self.cellSize color = style.BoardFloorColor if self.isDead: color = style.BoardDeadColor pygame.draw.rect(screen, color, (x, y, self.cellSize, self.cellSize), 1) self.item.draw(screen) self.snake.draw(screen) def move(self): if self.snake.direction == Direction.Up: self.tryMove(self.snake.x, self.snake.y - 1) elif self.snake.direction == Direction.Right: self.tryMove(self.snake.x + 1, self.snake.y) elif self.snake.direction == Direction.Down: self.tryMove(self.snake.x, self.snake.y + 1) elif self.snake.direction == Direction.Left: self.tryMove(self.snake.x - 1, self.snake.y) def tryMove(self, x, y): self.isDead = ((x < 0) or (x >= self.boardWidth) or (y < 0) or (y >= self.boardHeight) or self.snake.isContains(x, y)) if self.isDead: return isItemEaten = (x == self.item.x) and (y == self.item.y) if isItemEaten: self.item.eatenUpCount = self.item.eatenUpCount + 1 self.reinitItem() self.snake.moveHead(x, y, isItemEaten) def reinitItem(self): self.item.x = random.randint(0, self.boardWidth - 1) self.item.y = random.randint(0, self.boardHeight - 1)
def train(args, env): nn_shape = [args.fov, args.hidden_layers, args.layer_size, 2] # 2 is the action space # the function that will be optimized F = lambda gen: Snake(nn_shape, genotype=gen).get_score( env, args.eval_games) # randomly initialized genotype theta theta = Snake(nn_shape).get_genotype() # instance of evolution strategies es = ES(args.lr, args.std, args.population_size, F, theta) # optimize theta for step in range(args.es_steps): score = es.step() print("Step: ", step + 1, "/", args.es_steps, "Fitness:", "{:.2f}".format(score * 100)) # save theta Snake(nn_shape, genotype=es.theta).save_genotype(args.save_file)
def play(self): global snake, apple snake = Snake(config) apple = Apple(config) clock = pygame.time.Clock() while True: for event in pygame.event.get(): if event.type == pygame.QUIT: exit() # Detect collision with apple if snake.x == apple.x and snake.y == apple.y: snake.eat() apple = Apple(config) snake.x_change_old, snake.y_change_old = snake.x, snake.y with torch.no_grad(): data = get_data() data = data.reshape(1, 20) data = torch.tensor(data) result = model(data) snake.direction = np.argmax(result) snake.move() self.display.fill(self.color) pygame.draw.rect(self.display, Color.black, ((0, 0), (config.game_w, config.game_h)), 10) apple.draw(self.display) snake.draw(self.display) if snake.x < 0 or snake.y < 0 or snake.x > config.game_w or snake.y > config.game_h: self.play() score = self.font.render(f'Score: {snake.score}', True, Color.black) score_rect = score.get_rect(center=(config.game_w / 2, config.game_h - 10)) self.display.blit(score, score_rect) pygame.display.update() clock.tick(30) # fps
def __call__(self, *args: Any, **kwds: Any) -> Any: snake = Snake() thread = threading.Thread(target=snake.gameloop) thread.start() controls = Controls() controls()
def test_board_has_snakes(self): board = self.get_board() assert board.snakes == [ Snake({ "body": [(2, 2), (2, 3), (3, 3)], "health": 10, "id": "asdf1234" }) ]
def __init__(self, util: Util, cfg: Config, sfx: SfxHolder, game_size_tiles: Size2D): self.util = util self.cfg = cfg self.sfx = sfx # Game self.game_size_tiles = game_size_tiles self.game_over = False self.level = STARTING_LEVEL self.paused = False # Snakes initial_speed = self.get_moves_per_ms_by_level() self.live_snakes = [] for p in cfg.players: self.live_snakes.append(Snake(util, p, initial_speed)) self.all_snakes = self.live_snakes # backup list of all snakes # If multiple snakes, make ghosts so that they don't immediately collide for s in self.live_snakes: s.set_ghost(GHOST_TIMER_MS) # Enemies, apple, powerups, bullets self.enemies = [] self.poisons = [] self.apple = None self.pow_shield = None self.pow_ghost = None self.pow_bomb = None self.pow_bullets = None self.fired_bullets = [] # Minus enemies (due to bomb) self.minus_enemies = 0 self.minus_poisons = 0 # Generate first apple self.new_objects()
class GameScene(QGraphicsScene): """Custom QGraphicsScene""" def __init__(self, food_count, update_rate, statistic_list): super().__init__() self.sceneRect = QRectF(0.0, 0.0, 500.0, 500.0) self.setSceneRect(self.sceneRect) self.width = int(self.width()) self.height = int(self.height()) self.snake = None self.timer = QTimer() self.timer_snake = QTimer() self.update_rate = update_rate self.food_count = food_count self.food_items = [] self.score = 0 self.statistic_list = statistic_list self.time = 0 self.game_status = False self.startUpdate() # Signals self.timer.timeout.connect(self.update) self.timer_snake.timeout.connect(self.killSnake) def startUpdate(self): self.timer.start(self.update_rate) self.timer_snake.start(self.update_rate) self.game_status = True def pauseUpdate(self): self.timer.stop() self.timer_snake.stop() def drawGrid(self): self.addRect(0, 0, 500, 500, QPen(QColor('white'), 1), QBrush(QColor('white'))) for row in range(0, self.height + 20, 20): for column in range(0, self.width + 20, 20): self.addLine(0, row, self.width, row, QPen(QColor('black'), 1)) self.addLine(column, 0, column, self.height, QPen(QColor('black'), 1)) def createSnake(self): self.snake = Snake(0.0, 0.0) self.createFood() self.time = time.time() return self.snake def update(self): self.clear() self.drawGrid() self.placeFood() self.updateScore() self.catchFood() self.drawSnake() def killSnake(self): if self.snake.x not in range(0, self.width) or \ self.snake.y not in range(0, self.height) or\ self.snake.pos() in self.snake.positions[2:]: self.time = round(time.time() - self.time, 3) self.statistic_list.addItem('Game finished: {} s. Score: {}'\ .format(self.time, self.score)) self.pauseUpdate() self.game_status = False def createFood(self): for item in range(self.food_count): random_x = abs(round(randint(0, self.width) / 20) * 20 - 20) random_y = abs(round(randint(0, self.height) / 20) * 20 - 20) food_item = QRectF(random_x, random_y, 20, 20) while food_item in self.food_items or food_item in self.snake.positions: random_x = abs(round(randint(0, self.width) / 20) * 20 - 20) random_y = abs(round(randint(0, self.height) / 20) * 20 - 20) food_item = QRectF(random_x, random_y, 20, 20) self.food_items.append(food_item) def placeFood(self): for item in self.food_items: self.addRect(item, QPen(QColor('white'), 1), QBrush(QColor('red'))) def updateScore(self): self.addItem(ScoreText('Score: {}'.format(self.score), -30, -40)) def catchFood(self): for index, item in enumerate(self.food_items): if self.snake.pos() == (item.x(), item.y()): self.score += 10 del self.food_items[index] self.snake.eat() if not self.food_items: self.createFood() def drawSnake(self): for index, pos in enumerate(self.snake.positions): self.addRect(pos[0], pos[1], 20, 20, QPen(QColor('white'), 1), QBrush(QColor('green'))) if index == 0: self.addRect(pos[0] + 8, pos[1] + 8, 4, 4, QPen(QColor('yellow'), 1), QBrush(QColor('yellow'))) def getStatus(self): return self.game_status
def init_snake(self): head = Snake() head.body_part = self.game_board_canvas.create_rectangle( 120, 100, 130, 110, outline='#006400', fill='#008000', tags='S1') head.id = 'S1' body = Snake() body.body_part = self.game_board_canvas.create_rectangle( 110, 100, 120, 110, outline='#006400', fill='#32CD32', tags='S2') body.id = 'S2' tail = Snake() tail.body_part = self.game_board_canvas.create_rectangle( 100, 100, 110, 110, outline='#006400', fill='#32CD32', tags='S3') tail.id = 'S3' self.snake = [head, body, tail]
def play(self): while self.game: level = len(self.snake) // 3 snake_speed = (self.speed - level) / 100 if self.speed <= 0.01: time.sleep(0.01) else: self.update_level_label(level) time.sleep(snake_speed) for trap in self.traps: trap.increase_current_life_time() if trap.can_remove(): trap.remove() self.traps.remove(trap) self.traps.append( Trap(self.game_board_canvas, self.snake, self.prize)) if self.prize is not None: self.prize.increase_current_life_time() if self.prize.can_remove(): self.prize.remove() self.prize = None self.prize = Prize(self.game_board_canvas, self.snake, self.traps) if self.prize is not None: head = self.snake[0] tail = self.snake[len(self.snake) - 1] pc = self.game_board_canvas.coords(self.prize.get()) hc = self.game_board_canvas.coords(head.body_part) tc = self.game_board_canvas.coords(tail.body_part) if pc[0] == hc[0] and pc[1] == hc[1] and pc[2] == hc[2] and pc[ 3] == hc[3]: np = Snake() np.body_part = self.game_board_canvas.create_rectangle( tc[0] - tail.x_pos, tc[1] - tail.y_pos, tc[2] - tail.x_pos, tc[3] - tail.y_pos, outline='#006400', fill='#32CD32', tags=('ss' + str(len(self.snake) + 1))) np.id = 'S' + str(len(self.snake) + 1) np.x_pos = tail.x_pos np.y_pos = tail.y_pos np.moves = [] for m in tail.moves: np.moves.append(m) self.snake.append(np) self.score += self.prize.value self.score_label_text.set('SCORE: ' + str(self.score)) self.snake_length.set('SNAKE LENGTH: ' + str(len(self.snake))) self.prize.remove() self.prize = None self.prize = Prize(self.game_board_canvas, self.snake, self.traps) if len(self.move_positions) > 0: pos = self.move_positions[0] for sp in self.snake: sp.add_move(pos) del self.move_positions[0] for snake_part in self.snake: c = self.game_board_canvas.coords(snake_part.body_part) if len(snake_part.moves) > 0: m = snake_part.moves[0] if c[0] == m[0] and c[1] == m[1] and c[2] == m[2] and c[ 3] == m[3]: snake_part.x_pos = m[4] snake_part.y_pos = m[5] del snake_part.moves[0] self.game_board_canvas.move(snake_part.body_part, snake_part.x_pos, snake_part.y_pos) if c[2] >= 400 and snake_part.x_pos == 10: self.game_board_canvas.coords(snake_part.body_part, [0, c[1], 10, c[3]]) if c[0] <= 0 and snake_part.x_pos == -10: self.game_board_canvas.coords(snake_part.body_part, [390, c[1], 400, c[3]]) if c[3] >= 300 and snake_part.y_pos == 10: self.game_board_canvas.coords(snake_part.body_part, [c[0], 0, c[2], 10]) if c[1] <= 0 and snake_part.y_pos == -10: self.game_board_canvas.coords(snake_part.body_part, [c[0], 290, c[2], 300]) snake_body = copy.copy(self.snake) del snake_body[0] sh_cords = self.str_coords( self.game_board_canvas.coords(self.snake[0].body_part)) for snake_body_part in snake_body: sbp_str_cords = self.str_coords( self.game_board_canvas.coords(snake_body_part.body_part)) if sh_cords == sbp_str_cords: self.game_over_text() self.game = False break if len(self.traps) > 0: head = self.snake[0] hc = self.game_board_canvas.coords(head.body_part) for trap in self.traps: tc = self.game_board_canvas.coords(trap.get()) if tc[0] == hc[0] and tc[1] == hc[1] and tc[2] == hc[ 2] and tc[3] == hc[3]: self.game_over_text() self.game = False break self.game_board.bind('<Key>', lambda event, current_snake=self.snake: self. move_snake(event, current_snake), add='') self.game_board_canvas.update() self.game_board.mainloop()
#!/usr/bin/env python3 import pygame from config import SIZE, WINDOW_NAME, CELL_SIZE from src.food import Food from src.snake import Snake, Side from random import choice window = pygame.display.set_mode((SIZE, SIZE)) pygame.display.set_caption(WINDOW_NAME) screen = pygame.Surface((SIZE, SIZE)) coordinates = range(0, SIZE - CELL_SIZE, CELL_SIZE) hero = Snake(choice(coordinates), choice(coordinates)) zet = Food(choice(coordinates), choice(coordinates)) done = True while done: for e in pygame.event.get(): if e.type == pygame.QUIT: done = False if e.type == pygame.KEYDOWN: if (e.key == pygame.K_d or e.key == pygame.K_RIGHT) and hero.side[-1] != Side.LEFT: hero.turn_to(Side.RIGHT) elif (e.key == pygame.K_s or e.key == pygame.K_DOWN) and hero.side[-1] != Side.UP: hero.turn_to(Side.DOWN) elif (e.key == pygame.K_a or e.key == pygame.K_LEFT) and hero.side[-1] != Side.RIGHT:
def get_snake(self): return Snake({ 'body': [(10, 15), (11, 15), (11, 16), (11, 17)], 'health': 100, 'id': 'abcd1234', })
def test_create_snake(self): assert type(Snake({})).__name__ == 'Snake'
def __init__(self, board, snake): self.directions = ['L', 'R', 'U', 'D'] self.snake = Snake(snake) self.board = Board(board)
def createSnake(x: int, y:int) -> Snake: """returns snake object at coordinates""" return Snake(x, y)
def snakes(self) -> List[Snake]: """Retreive the list of snakes from the board data.""" if self._snakes is None: snakes = [Snake(snake_data) for snake_data in self._data['snakes']] self._snakes = snakes return self._snakes
def test_eat(): snake = Snake() before = snake.length snake.eat() assert before == snake.length - 1
class Game: def __init__(self, x, y): size = constants.BOARD_SIZE * constants.PIXEL_SIZE border_size = constants.BORDER_SIZE * 2 + size self.border_box = pg.rect.Rect((x, y), (border_size, border_size)) self.box = pg.rect.Rect((x + constants.BORDER_SIZE, y + constants.BORDER_SIZE), (size, size)) self.score = 3 self.score_font = pg.font.Font(Assets.BOXY_FONT, 24) self.snake = Snake(int(constants.BOARD_SIZE / 2), constants.BOARD_SIZE / 2) self.fruit = Fruit() self.clock = pg.time.Clock() self.count = 0 def lost(self): return self.snake.lost() def draw(self, window): window.blit(Assets.BACKGROUND, self.border_box) # Draw the score text = self.score_font.render("Score: " + str(self.score), True, Colors.BLACK) window.blit(text, (self.border_box.left + 3, self.border_box.top + 3)) # Draw the snake for part in self.snake.body[1:]: x, y = self.box.left + constants.PIXEL_SIZE * part[0], self.box.top + constants.PIXEL_SIZE * part[1] window.blit(Assets.SNAKE_BODY, (x, y)) # Draw the fruit x, y = self.box.left + constants.PIXEL_SIZE * self.fruit.position[0], self.box.top + constants.PIXEL_SIZE * self.fruit.position[1] head = self.snake.body[0] head_x, head_y = self.box.left + constants.PIXEL_SIZE * head[0], self.box.top + constants.PIXEL_SIZE * head[1] rotated_head = pg.transform.rotate(Assets.SNAKE_HEAD, self.snake.direction) window.blit(rotated_head, (head_x, head_y)) if self.fruit.golden: window.blit(Assets.FRUIT_GOLDEN, (x, y)) else: window.blit(Assets.FRUIT_NORMAL, (x, y)) def update(self, events): self.clock.tick() self.count += self.clock.get_time() if self.count > constants.TICK: self.count %= constants.TICK self.snake.move() if self.snake.body[0] == self.fruit.position: if self.fruit.golden: self.snake.grow += 3 self.score += 3 else: self.snake.grow += 1 self.score += 1 while self.fruit.position in self.snake.body: self.fruit.reposition() for event in events: if event.type == pg.KEYDOWN: if event.key in (pg.K_UP, pg.K_w): self.snake.change_direction(constants.NORTH) elif event.key in (pg.K_RIGHT, pg.K_d): self.snake.change_direction(constants.EAST) elif event.key in (pg.K_DOWN, pg.K_s): self.snake.change_direction(constants.SOUTH) elif event.key in (pg.K_LEFT, pg.K_a): self.snake.change_direction(constants.WEST)
def play(self): global rows snake = Snake(config) apple = Apple(config) clock = pygame.time.Clock() while True: for event in pygame.event.get(): if event.type == pygame.QUIT: exit() # Detect collision with apple if snake.x == apple.x and snake.y == apple.y: snake.eat() apple = Apple(config) # collision with body for part in snake.body: if snake.x == part[0] and snake.y == part[1]: snake = Snake(config) direction = snake.vision(apple) snake.pre_direction = snake.direction snake.decision(direction) # collision with wall if snake.collision_with_wall(snake.direction): direction = (snake.direction + 1) % 4 if snake.collision_with_wall(direction): direction = (snake.direction - 1) % 4 if snake.collision_with_wall(direction): snake = Snake(config) snake.direction = direction snake.move() self.display.fill(self.color) pygame.draw.rect(self.display, Color.black, ((0, 0), (config.game_w, config.game_h)), config.wall_offset) apple.draw(self.display) snake.draw(self.display) score = self.font.render(f'Score: {snake.score}', True, Color.black) score_rect = score.get_rect(center=(config.game_w / 2, config.game_h - 10)) self.display.blit(score, score_rect) pygame.display.update() clock.tick(config.fps)
def check_snake_hits(self, snake: Snake, other_snakes: List[Snake]): # Check if hit itself, apple, power-ups head = snake.head if head in snake.tail and not snake.is_ghost_on: snake.kill() return elif head == self.apple: self.level += 1 snake.grow_by_one() self.update_snakes_moves_per_ms() self.new_objects() self.sfx.apple.play() elif head == self.pow_shield: snake.set_shield(True) self.pow_shield = None self.sfx.powerup.play() elif head == self.pow_ghost: snake.set_ghost(GHOST_TIMER_MS) self.pow_ghost = None self.sfx.powerup.play() elif head == self.pow_bomb: self.minus_enemies += self.no_of_enemies self.minus_poisons += self.no_of_poisons self.enemies.clear() self.poisons.clear() self.pow_shield = self.pow_ghost = self.pow_bomb = None self.sfx.powerup.play() elif head == self.pow_bullets: snake.add_bullets(INIT_NO_OF_BULLETS) self.pow_bullets = None self.sfx.powerup.play() # Check if hit other snake if not snake.is_ghost_on: for s in other_snakes: if head in s: snake.kill() return # Check if hit enemy if not snake.is_ghost_on: try: self.enemies.remove(next(e for e in self.enemies if e == head)) if snake.is_shield_on: snake.set_shield(False) self.sfx.shield_off.play() else: snake.kill() return except StopIteration: pass # Check if hit poison if not snake.is_ghost_on: try: self.poisons.remove(next(e for e in self.poisons if e == head)) if snake.is_shield_on: snake.set_shield(False) self.sfx.shield_off.play() else: snake.shrink(1) if len(snake) < 1: snake.kill() return else: self.sfx.poison.play() except StopIteration: pass
def createSnake(self): self.snake = Snake(0.0, 0.0) self.createFood() self.time = time.time() return self.snake
type=int) parser.add_argument("--dataset", default="./snake_train_dataset.csv", help="dataset path", type=str) args = parser.parse_args() f = open(args.dataset, 'w') f.write( 'w0,w1,w2,w3,a0,a01,a1,a12,a2,a23,a3,a30,b0,b01,b1,b12,b2,b23,b3,b30,direction' + '\n') rows = 0 pbar = tqdm(total=100, position=0, leave=True) snake = Snake(config) apple = Apple(config) while rows < args.count: # Detect collision with apple if snake.x == apple.x and snake.y == apple.y: snake.eat() apple = Apple(config) # collision with body for part in snake.body: if snake.x == part[0] and snake.y == part[1]: snake = Snake(config) direction = snake.vision(apple) snake.pre_direction = snake.direction
class Scene: def __init__(self): self.started = False self.bg_colour = (240, 160, 212) self.area_info = (0, 0, 450, 450) self.cell_amt = 18 self.back_colour = Color(231, 242, 198) self.cell_colour = Color(200, 200, 227) self.cell_size = (self.area_info[2] // self.cell_amt, self.area_info[3] // self.cell_amt) self.play_rect = Rect(self.area_info) self.play_surf = Surface(self.area_info[2:]) self.play_surf.fill(self.back_colour) self.circ_radius = 25 self.fruit = Collectible(self.cell_size, self.cell_amt) self.score = 0 self.snake = Snake(self.cell_size, self.cell_amt) self.snake_is_dead = False self.draw_checkerboard() self.font = SysFont("Arial", 30) self.text = self.font.render("Score: 0", False, self.back_colour) def draw_checkerboard(self): for i in range(self.cell_amt): for j in range(self.cell_amt): if (i % 2 == 0) ^ (j % 2 == 0): cr = Rect((i * self.cell_size[0], j * self.cell_size[1]), self.cell_size) draw_rect(self.play_surf, self.cell_colour, cr) def start(self): self.fruit.start() self.snake.start() self.started = True return self.started def update(self, delta): if not self.snake_is_dead: if get_pressed_keys()[K_SPACE]: self.fruit.reposition() elif get_pressed_keys()[K_p]: self.snake.set_growth() self.handle_collected() self.snake.move() self.fruit.update(delta) self.collect() self.snake.update(delta) if not self.snake.check_alive(): self.snake_is_dead = True self.text = self.font.render(f"Game Over", False, self.back_colour) def render(self, target): target.fill(self.bg_colour) if not self.snake_is_dead: target.blit(self.play_surf, self.play_rect) self.fruit.render(target) self.snake.render(target) target.blit(self.text, (560, 90)) else: target.blit(self.text, (90, 90)) def collect(self): if self.fruit.get_current_cell() == self.snake.get_head(): self.snake.set_growth() snake_pos = self.snake.get_snake() while self.fruit.get_current_cell() in snake_pos: self.fruit.reposition() self.handle_collected() def handle_collected(self): self.score += 1 if self.score % 5 == 0: self.snake.speed_change = True self.text = self.font.render(f"Score: {self.score}", False, self.back_colour)
class Game: def __init__(self, board, snake): self.directions = ['L', 'R', 'U', 'D'] self.snake = Snake(snake) self.board = Board(board) def play(self, move): res = self.does_move_exist(move) if res: self.snake.perform_move(res) return True return False def does_move_exist(self, direction): if direction == 'L': res = self.can_go_left() if direction == 'R': res = self.can_go_right() if direction == 'U': res = self.can_go_up() if direction == 'D': res = self.can_go_down() return res def can_go_left(self): nbr_col = self.board.nbr_col head = self.snake.head position_left = head[0] - 1 if position_left >= 0 and position_left <= nbr_col: new_position = [position_left, head[1]] if self.snake.position_free(new_position): return new_position return False def can_go_right(self): nbr_col = self.board.nbr_col head = self.snake.head position_right = head[0] + 1 if position_right >= 0 and position_right <= nbr_col: new_position = [position_right, head[1]] if self.snake.position_free(new_position): return new_position return False def can_go_down(self): nbr_row = self.board.nbr_row head = self.snake.head position_down = head[1] + 1 if position_down >= 0 and position_down <= nbr_row: new_position = [head[0], position_down] if self.snake.position_free(new_position): return new_position return False def can_go_up(self): nbr_row = self.board.nbr_row head = self.snake.head position_up = head[1] - 1 if position_up >= 0 and position_up <= nbr_row: new_position = [head[0], position_up] if self.snake.position_free(new_position): return new_position return False