Example #1
0
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)
Example #2
0
    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)
Example #3
0
    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
Example #4
0
            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:
                hero.turn_to(Side.LEFT)
            elif (e.key == pygame.K_w
                  or e.key == pygame.K_UP) and hero.side[-1] != Side.DOWN:
                hero.turn_to(Side.UP)

    screen.fill((5, 5, 5))
    zet.render(surface_to_render=screen)
    hero.move()
    if hero.check_collision(zet):
        zet.x = choice(coordinates)
        zet.y = choice(coordinates)
        hero.len()
    #  TODO: To be moved into snake itself
    for each_cell in hero.tail[1:]:
        if each_cell.x == hero.x and each_cell.y == hero.y:
            hero.length = each_cell.number
    hero.render(surface_to_render=screen)
    window.blit(screen, (0, 0))
    pygame.display.flip()
    pygame.time.delay(300)
    if hero.length <= 1:
        caption = "Hello Pygame"
    else:
Example #5
0
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)
Example #6
0
        # 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)

        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

        if add_data():
            rows += 1
            pbar.update((1 / args.count) * 100)

        snake.move()

    f.close()
Example #7
0
class Game:
    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):
        """
        Initializes and resets the grid.
        Loads a grid from a file.
        """

        # Remove all elements in the grid
        self.grid.clear()

        # Fill the grid
        for i in range(self.size[1]):
            line = list()
            for j in range(self.size[0]):
                box = Box(i, j)
                box.create(self.canvas)
                line.append(box)
            self.grid.append(line)

        # Snake
        self.snake.init()
        i_mid = self.size[1] // 2
        j_mid = self.size[0] // 2
        self.snake.body = [(i_mid, j_mid), (i_mid, j_mid + 1),
                           (i_mid, j_mid + 2)]
        for i, j in self.snake:
            self.grid[i][j].set_state(states.SNAKE, self.canvas)

        self.score = 0
        self.spawn_food()

    # Snake

    def move(self):
        """
        Moves the snake on the grid.
        """

        new_head, old_tail = self.snake.move()
        box = self.grid[new_head[0]][new_head[1]]

        # If there is food, do not remove the tail
        if box.state == states.FOOD:
            self.snake.body.append(old_tail)
            self.score += 1
            self.spawn_food()
        # Remove the tail
        else:
            i, j = old_tail
            self.grid[i][j].set_state(states.EMPTY, self.canvas)

        # Add the head
        box.set_state(states.SNAKE, self.canvas)

        return self.snake.eat_tail()

    # Food

    def spawn_food(self):
        """
        Adds a food in the grid.
        """

        boxes = [box for box in self.gen_boxes() if box.state == states.EMPTY]
        box = random.choice(boxes)
        box.set_state(states.FOOD, self.canvas)

    # Tools

    def gen_boxes(self) -> Box:
        """
        Lists all the boxes in the grid.
        Generator.
        """

        for i in range(self.size[1]):
            for j in range(self.size[0]):
                yield self.grid[i][j]

    # Magics

    def __getitem__(self, index):
        return self.grid[index]