Esempio n. 1
0
    def __init__(self, players, snakes):

        self.players = players
        self.snakes_count = snakes
        ps = PlayerSnakes()
        all_players = []
        all_snakes = []
        colors = ["#fff200", "#b87bba", "#3494e3", "#fa5700"]

        self.game_board = GameBoard()
        timer_frame = TimerFrame()
        self.score_board = ScoreBoard(timer_frame)

        part_width = 15
        part_height = 15


        collision_manager = CollisionManager()
        self.food_manager = FoodManager(collision_manager)
        drawing_manager = DrawingManager(self.game_board, self.score_board)
        movement_manager = MovementManager()
        snake_part_manager = SnakePartManager(part_width, part_height, collision_manager)
        shift_players_manager = ShiftPlayersManager()
        table_width = self.game_board.get_gameboard_width
        table_height = self.game_board.get_gameboard_height

        food = []
        #deus_ex_machina = None

        for i in range(len(players)):
            p_snake = ps.all_snakes[i][:snakes]
            player_snake = []
            for snake_part in p_snake:
                if (i + 1) % 2 == 0:
                    snake = Snake(snake_part, players[i], 10, 0, SnakeDirection.LEFT, colors[i])
                else:
                    snake = Snake(snake_part, players[i], 10, 0, SnakeDirection.RIGHT, colors[i])

                player_snake.append(snake)

            all_players.append(User(player_snake, 0, players[i], colors[i]))
            all_snakes.extend(player_snake)

        for i in range(0, 30):
            food.append(self.food_manager.generate_food(1, 1, all_snakes, food, None, table_width, table_height, 15))

        #deus_ex_machina = self.food_manager.generate_food(0, 0, all_snakes, food, table_width, table_height, 15, True)  # generate superfood

        self.game = Game(all_players, food, collision_manager, drawing_manager, movement_manager, snake_part_manager, self.food_manager, shift_players_manager, table_width, table_height, self)
        self.game.set_active_player(all_players[0])
        self.game.set_active_snake(all_players[0].snakes[0])

        self.score_board.set_active_player_on_button_frame(all_players[0])
        self.score_board.set_active_snake_on_button_frame(all_players[0].snakes[0])

        timer_frame.set_game(self.game)

        self.last_players = copy.deepcopy(all_players)
        self.last_snakes = copy.deepcopy(all_snakes)
Esempio n. 2
0
def move():
    data = bottle.request.json


    turn = data['turn']
    snakes = data['snakes']

    # game = Game(name, turn, snakes, board_data)
    height = data['height']
    width = data['width']
    food = data['food']

    board = Board(height, width, food)

    # logger.info("Board: %s x %s" % (board.width, board.height))
    # logger.info("Food: %s" % board.food)

    our_snake = None
    enemy_snakes = []

    for snake_data in snakes:

        logger.info(snake_data)

        if snake_data['id'] == SNAKE_NAME:
            our_snake_data = snake_data
            logger.info("Got our snake: %s", our_snake_data)

        else:

            enemy_snakes.append(
                Snake(id=snake_data.get('id'),
                      state=snake_data.get('state'),
                      coords=snake_data.get('coords'),
                      turn=turn,
                      board=board,
                      last_eaten=snake_data.get('last_eaten'))
            )

    our_snake = Snake(id=our_snake_data.get('id'),
                      state=our_snake_data.get('state'),
                      coords=our_snake_data.get('coords'),
                      turn=turn,
                      board=board,
                      last_eaten=our_snake_data.get('last_eaten'),
                      enemies=enemy_snakes)

    direction = our_snake.move()

    taunt = ""

    if turn % 2 == 1:
        taunt = random.choice(TAUNTS)

    return {
        'move': direction,
        'taunt': taunt,
    }
Esempio n. 3
0
 def __init__(self, x, y):
     """
     initialize the game state
     :param x: grid x value
     :param y: grid y value
     """
     self.grid_x = x
     self.grid_y = y
     self.snake = Snake(grid_x, grid_y)
Esempio n. 4
0
def make_new_snake(snake_list, snake_length, food):
    old_snake = snake_list[0]
    if food.x > old_snake.x:
        if food.y > old_snake.y:
            new_snake = Snake(WIDTH, HEIGHT, old_snake.x + old_snake.size,
                              old_snake.y)
        elif food.y == old_snake.y:
            new_snake = Snake(WIDTH, HEIGHT, old_snake.x + old_snake.size,
                              old_snake.y)
        else:
            new_snake = Snake(WIDTH, HEIGHT, old_snake.x + old_snake.size,
                              old_snake.y)

    elif food.x == old_snake.x:
        if food.y > old_snake.y:
            new_snake = Snake(WIDTH, HEIGHT, old_snake.x,
                              old_snake.y + old_snake.size)
        else:
            new_snake = Snake(WIDTH, HEIGHT, old_snake.x,
                              old_snake.y - old_snake.y)

    elif food.x < old_snake.x:
        if food.y > old_snake.y:
            new_snake = Snake(WIDTH, HEIGHT, old_snake.x - old_snake.size,
                              old_snake.y)
        elif food.y == old_snake.y:
            new_snake = Snake(WIDTH, HEIGHT, old_snake.x - old_snake.size,
                              old_snake.y)
        else:
            new_snake = Snake(WIDTH, HEIGHT, old_snake.x - old_snake.size,
                              old_snake.y)

    snake_length += 1
    snake_list.insert(0, new_snake)
    return snake_list, snake_length
Esempio n. 5
0
    def setup_new_game(self, play_mode):
        # play mode: 1 - only snake, 2 - with enemy snake, 3 - only enemy snake
        self.tick = True
        self.play_again = True
        self.direction_chage_flag = False
        self.pause = False
        self.speed = 30
        self.snake = None
        self.enemy_snake = None
        if play_mode == 1 or play_mode == 2:
            self.snake = Snake((300, 400), (100, 200, 250))
        if play_mode == 2 or play_mode == 3:
            self.enemy_snake = EnemySnake((500, 400), (200, 0, 0))
            # for s in range(20):
            #     self.enemy_snake.add_segment((500,400))

        self.food = []
        self.eated_food = []
        for r in range(1):
            self.spawn_food()
Esempio n. 6
0
class Game:
    grid_x = None
    grid_y = None

    cookie = Cookie()
    snake = None
    def __init__(self, x, y):
        """
        initialize the game state
        :param x: grid x value
        :param y: grid y value
        """
        self.grid_x = x
        self.grid_y = y
        self.snake = Snake(grid_x, grid_y)

    def tick(self):
        """
        tick of the clock
        """
        if self.snake.is_alive():
            self.snake.move_snake(self.cookie)
            self.cookie.new_cookie(self.grid_x, self.grid_y)
            self.snake.determine_if_dead(self.grid_x, self.grid_y)
        print("Snake is {} at {} {} heading {}".format(self.snake.is_alive(), self.snake.x_pos, self.snake.y_pos, self.snake.bearing))

    def get_snake_bearing(self):
        return self.snake.bearing

    def set_snake_bearing(self, bearing):
        self.snake.bearing = bearing
    def create_snake_from_drawable_components(self, parts, player):
        snake_parts = []
        for component in parts:
            snake_parts.append(
                SnakePart(component.x_coordinate, component.y_coordinate,
                          component.height, component.width,
                          SnakePartType.BODY))

        first = snake_parts[0]
        second = snake_parts[1]
        first.part_type = SnakePartType.HEAD

        if first.x_coordinate < second.x_coordinate:
            return Snake(snake_parts, player.user_name, len(snake_parts), 0,
                         SnakeDirection.LEFT, player.color)
        elif first.x_coordinate > second.x_coordinate:
            return Snake(snake_parts, player.user_name, len(snake_parts), 0,
                         SnakeDirection.RIGHT, player.color)
        elif first.y_coordinate < second.y_coordinate:
            return Snake(snake_parts, player.user_name, len(snake_parts), 0,
                         SnakeDirection.UP, player.color)
        else:
            return Snake(snake_parts, player.user_name, len(snake_parts), 0,
                         SnakeDirection.DOWN, player.color)
Esempio n. 8
0
def one_game():
    pygame.event.pump()
    game_over = False

    # snake will start in the middle of the game window
    lead_x = 70
    lead_y = 70

    # snake default direction is right
    snake = Snake(gameDisplay, display_width, display_height, img, lead_x,
                  lead_y)
    apple = Apple(gameDisplay, display_width, display_height, block_size, img2,
                  snake.snake_list)

    while not game_over:

        # based on the direction, we can work out the x, y changes to update the snake
        x, y = apple.get_apple_pos()
        snake.update_snake_list(x, y)

        # check if snake dies
        if snake.is_alive() is False:
            game_over = True

        gameDisplay.fill(white)

        # if snake eats the apple, make a random new apple
        if snake.eaten is True:
            apple.update_apple_pos(snake.snake_list)

        apple.display()
        snake.eaten = False
        snake.display()
        snake.display_score()
        pygame.display.update()

        # this part is using the snake position and apple
        # position to use the A* method to get the path
        a_x, a_y = apple.get_apple_pos()
        s_x, s_y = snake.get_snake_head()
        visited = snake.snake_list.copy()
        visited.remove([s_x, s_y])
        result = A_star(display_width, display_height, block_size, visited,
                        (a_x, a_y), (s_x, s_y))

        # since the path starts from snake position, the second element will
        # be next move
        next_cell = result[1]

        # update the snake position based on the next move position
        x_diff = next_cell[0] - s_x
        y_diff = next_cell[1] - s_y
        if x_diff > 0:
            snake.direction = "right"
        elif x_diff < 0:
            snake.direction = "left"
        elif y_diff > 0:
            snake.direction = "down"
        elif y_diff < 0:
            snake.direction = "up"

        clock.tick(FPS)
Esempio n. 9
0
icon = pygame.image.load('snake.png')

pygame.display.set_icon(icon)
screen = pygame.display.set_mode((800, 800))
screen.fill(Colors.GREY)
game_area = pygame.Rect((0, 0, 800, 800))

score = 0
font = pygame.font.Font('arial.ttf', 32)
text = font.render(str(score), True, Colors.WHITE)
textrect = text.get_rect()
textrect.right = 780
screen.blit(text, textrect)

draw_grid()
snake = Snake(screen)
apple = Apple(screen, snake)

eat_apple = pygame.USEREVENT + 1
game_over = False

running = True

while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        if event.type == pygame.KEYDOWN:
            if not game_over:
                if event.key == pygame.K_w:
                    snake.turn('-y')
Esempio n. 10
0
def run(window) -> None:
    window.clear()
    curses.curs_set(0)

    # Create playable area
    max_height, max_width = window.getmaxyx()

    padding = [4, 4, 4, 4]  # top, right, bottom, left

    # height = max_height - padding[0] - padding[2]
    # width = max_width - padding[1] - padding[3]
    height = max_height - padding[0] - padding[2]
    width = 20
    logging.info(f"Window sizes: height: {height} \n width: {width}")

    win_left_corner, win_right_corner = ([padding[0], padding[3]], [
        padding[0] + height, padding[1] + width
    ])
    terrain = Terrain(width=width,
                      height=height,
                      max_height=win_right_corner[0],
                      min_height=win_left_corner[0],
                      min_width=win_left_corner[1],
                      max_width=win_right_corner[1],
                      borders=[Direction.UP])
    # draw playable area
    textpad.rectangle(
        window,
        *win_left_corner,
        *win_right_corner,
    )
    center = win_left_corner[0] + height // 2, win_right_corner[1] // 2

    # Create a snake
    snake_body = 4
    snake_coordinates = [center]
    index = 0
    while len(snake_coordinates) != snake_body:
        prev = snake_coordinates[index]
        snake_coordinates.append((prev[0], prev[1] - 1))
        index += 1
    logging.info(snake_coordinates)
    snake = Snake(initial_coordinates=snake_coordinates,
                  body_length=snake_body,
                  terrain=terrain)

    # Draw a snake
    draw_ch_list(window,
                 coordinates=snake.initial_coordinates,
                 ch_list=snake.body)
    # Create and draw food
    food = curses.ACS_PI
    food_y, food_x = get_food_coords(snake, terrain)
    window.addch(food_y, food_x, food)
    # run a game
    direction = Direction.RIGHT

    score = 0
    # draw score
    window.addstr(1, 1, f"Score: {score}")
    while True:
        window.timeout(100)
        key = window.getch()
        movement = {
            curses.KEY_UP: Direction.UP,
            curses.KEY_DOWN: Direction.DOWN,
            curses.KEY_LEFT: Direction.LEFT,
            curses.KEY_RIGHT: Direction.RIGHT
        }
        new_direction = movement.get(key)
        if new_direction:
            direction = new_direction
            logging.info(
                f"Change directions key caught: \n key - {key} \n direction - {direction}"
            )
            logging.info(snake.current_coordinates)

        elif key == 3:
            raise KeyboardInterrupt
        cur_tail_y, cur_tail_x = snake.current_coordinates[-1]

        try:
            snake.move(direction=direction)  # create new coordinates
        except Exception as e:
            logging.exception(f"Exception: {e}")
            window.timeout(0)
            game_over(window, center, e, score)
        draw_ch(window, y=cur_tail_y, x=cur_tail_x,
                ch=" ")  # erase previous tail

        draw_ch_list(window,
                     coordinates=snake.current_coordinates,
                     ch_list=snake.body)  # draw new coords

        if snake.current_coordinates[0] == (food_y, food_x):
            score += 1
            snake.grow()
            food_y, food_x = get_food_coords(snake, terrain)
            window.addch(food_y, food_x, food)
        window.addstr(1, 1, f"Score: {score}")
Esempio n. 11
0
def game():
    speed = 5
    x_movement = speed
    y_movement = 0
    snake_length = 1
    score = 0

    screen.fill(BLACK)
    snake_list = []
    initial_x = random.randint(10, WIDTH - 10)
    initial_y = random.randint(10, HEIGHT - 10)
    snake = Snake(WIDTH, HEIGHT, initial_x, initial_y)
    snake_list.append(snake)

    food = Food(WIDTH, HEIGHT)
    flag = 0

    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                quit()
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_LEFT:
                    flag = 1
                    x_movement = -speed
                    y_movement = 0
                if event.key == pygame.K_UP:
                    flag = 2
                    y_movement = -speed
                    x_movement = 0
                if event.key == pygame.K_RIGHT:
                    flag = 3
                    x_movement = speed
                    y_movement = 0
                if event.key == pygame.K_DOWN:
                    flag = 4
                    y_movement = speed
                    x_movement = 0

        snake_list, food, speed, snake_length, score = handle_collisions(
            snake_list, food, speed, snake_length, score)
        if flag == 1:
            x_movement = -speed
            y_movement = 0
        elif flag == 2:
            y_movement = -speed
            x_movement = 0
        elif flag == 3:
            x_movement = speed
            y_movement = 0
        elif flag == 4:
            y_movement = speed
            x_movement = 0

        draw(snake_list, food)

        snake_list = move_snake(snake_list, x_movement, y_movement)

        # for i in snake_list:
        # 	i.move(x_movement,y_movement)
        pygame.time.delay(30)
Esempio n. 12
0
class SnakeGame:
    SPEED_CHANGE = 10

    def __init__(self):
        self._init_pygame()
        self.screen = pygame.display.set_mode((800, 600))
        self.background = pygame.Surface((800, 600))
        self.background.fill((50, 50, 50))
        self.clock = pygame.time.Clock()
        self.wraping = True
        self.play_mode = 3
        self.enemy_snake_grows = True
        self.setup_new_game(self.play_mode)

    def setup_new_game(self, play_mode):
        # play mode: 1 - only snake, 2 - with enemy snake, 3 - only enemy snake
        self.tick = True
        self.play_again = True
        self.direction_chage_flag = False
        self.pause = False
        self.speed = 30
        self.snake = None
        self.enemy_snake = None
        if play_mode == 1 or play_mode == 2:
            self.snake = Snake((300, 400), (100, 200, 250))
        if play_mode == 2 or play_mode == 3:
            self.enemy_snake = EnemySnake((500, 400), (200, 0, 0))
            # for s in range(20):
            #     self.enemy_snake.add_segment((500,400))

        self.food = []
        self.eated_food = []
        for r in range(1):
            self.spawn_food()

    def spawn_food(self, position=0):
        if position == 0:
            while True:
                position = get_random_position(self.screen)
                if self.snake:
                    if not self.snake.collides_with(position):
                        break
                else:
                    break
        self.food.insert(0, Food(position))

    def change_speed(self, speed_change):
        self.speed += speed_change
        if self.speed < 10:
            self.speed = 10

    def main_loop(self):
        while self.play_again == True:
            self._handle_input()
            self._process_game_logic()
            self._draw()

    def _init_pygame(self):
        pygame.init()
        pygame.display.set_caption("Snake")

    def _handle_input(self):
        for event in pygame.event.get():
            if event.type == pygame.QUIT or (event.type == pygame.KEYDOWN
                                             and event.key == pygame.K_ESCAPE):
                quit()

            if event.type == pygame.KEYDOWN and self.snake and not self.direction_chage_flag:
                if event.key == pygame.K_w and self.snake.direction != 2:
                    self.snake.direction = 1
                    self.direction_chage_flag = True
                if event.key == pygame.K_s and self.snake.direction != 1:
                    self.snake.direction = 2
                    self.direction_chage_flag = True
                if event.key == pygame.K_a and self.snake.direction != 4:
                    self.snake.direction = 3
                    self.direction_chage_flag = True
                if event.key == pygame.K_d and self.snake.direction != 3:
                    self.snake.direction = 4
                    self.direction_chage_flag = True

            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_SPACE:
                    self.pause = not self.pause

                if event.key == pygame.K_o:
                    self.change_speed(self.SPEED_CHANGE)
                if event.key == pygame.K_l:
                    self.change_speed(-self.SPEED_CHANGE)
                if event.key == pygame.K_r:
                    self.setup_new_game(self.play_mode)

            if event.type == pygame.MOUSEBUTTONUP:
                print(get_mouse_pos())

    def _process_game_logic(self):
        if not self.pause:
            if self.snake:
                self.snake.move(self.snake.direction, self.screen,
                                self.wraping)

                for s in self.snake.segments:
                    if self.snake.collides_with_itself() or (
                            self.enemy_snake and self.snake.collides_with(
                                self.enemy_snake.segments[0])):
                        self.snake = None
                        break

                for f in self.food:
                    if self.snake.collides_with(f.position):
                        if not f.in_snake:
                            f.in_snake = True
                            self.spawn_food()
                    else:
                        if f.in_snake:
                            self.speed += 0.5
                            self.snake.add_segment(f.position)
                            self.food.remove(f)

                if not self.wraping:
                    if not self.screen.get_rect().collidepoint(
                            self.snake.segments[0]):
                        self.snake = None

                self.direction_chage_flag = False

            ## enemy_snake_handling
            if self.enemy_snake:
                if self.tick:
                    #print("pre")
                    self.enemy_snake.move1(self.food[0].position, self.screen,
                                           self.wraping)
                    #print("past")
                #print(len(self.enemy_snake.segments))
                if self.play_mode != 3:
                    self.tick = not self.tick

                for f in self.food:
                    if self.enemy_snake_grows:
                        if self.enemy_snake.collides_with(f.position):
                            if not f.in_snake:
                                f.in_snake = True
                                self.spawn_food()
                        else:
                            if f.in_snake:
                                self.enemy_snake.add_segment(f.position)
                                self.food.remove(f)
                    else:
                        if self.enemy_snake.collides_with(f.position):
                            self.food.remove(f)
                            self.spawn_food()
                for s in self.enemy_snake.segments:
                    if self.enemy_snake.collides_with_itself():
                        print(len(self.enemy_snake.segments))
                        #print(*self.enemy_snake.segments)
                        self.pause = True
                        #self.setup_new_game(self.play_mode)
                        #self.enemy_snake = None
                        break

                # print(self.enemy_snake.segments[0].distance_to(self.food[0].position))

    def _draw(self):
        if not self.pause:
            #print("frame")
            self.screen.blit(self.background, (0, 0))

            if self.food:
                for f in self.food:
                    f.draw(self.screen)

            if self.snake:
                self.snake.draw(self.screen)

            if self.enemy_snake:
                self.enemy_snake.draw(self.screen)

            #self.clock.tick(self.speed)

            pygame.display.flip()
Esempio n. 13
0
def one_game():
    pygame.event.pump()
    game_over = False
    lead_x = 150
    lead_y = 150
    snake = Snake(showScreen, screenx, screeny, snakeImg, lead_x, lead_y)
    apple = Apple(showScreen, screenx, screeny, b_size, appleImg, snake.snake_list)

    while not game_over:
        x, y = apple.get_apple_pos()
        snake.update_snake_list(x, y)

        if snake.is_alive() is False: game_over = True
        showScreen.fill(white)
        if snake.eaten is True: apple.update_apple_pos(snake.snake_list)

        apple.display()
        snake.eaten = False
        snake.display()
        snake.display_score()
        pygame.display.update()

        a_x, a_y = apple.get_apple_pos()
        s_x, s_y = snake.get_snake_head()

        visited = snake.snake_list.copy()
        visited.remove([s_x, s_y])
        result = BreathFirstSearch(screenx, screeny, b_size, visited, [a_x, a_y], [s_x, s_y])

        next_cell = result[1]

        x_diff = next_cell[0] - s_x
        y_diff = next_cell[1] - s_y

        if x_diff > 0:  snake.direction = "right"
        elif x_diff < 0:  snake.direction = "left"
        elif y_diff > 0:  snake.direction = "down"
        elif y_diff < 0:  snake.direction = "up"

        time.tick(FPS)