import pygame
import random
import sys

# Initialize Pygame
pygame.init()

# Constants
SCREEN_WIDTH, SCREEN_HEIGHT = 600, 400
CELL_SIZE = 20
FPS = 10

# Colors
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
GREEN = (0, 255, 0)
RED = (255, 0, 0)

# Directions
UP = (0, -1)
DOWN = (0, 1)
LEFT = (-1, 0)
RIGHT = (1, 0)

class Snake:
    def __init__(self, color, position):
        self.color = color
        self.body = [position]
        self.direction = RIGHT

    def get_head_position(self):
        return self.body[0]

    def update(self):
        head_x, head_y = self.get_head_position()
        new_head = (head_x + self.direction[0], head_y + self.direction[1])
        self.body.insert(0, new_head)
        self.body.pop()

    def grow(self):
        self.body.append(self.body[-1])  # Grow the snake by adding a new segment

    def change_direction(self, direction):
        # Prevent the snake from reversing
        if (direction[0] * -1, direction[1] * -1) != self.direction:
            self.direction = direction

    def draw(self, surface):
        for segment in self.body:
            pygame.draw.rect(surface, self.color, (segment[0] * CELL_SIZE, segment[1] * CELL_SIZE, CELL_SIZE, CELL_SIZE))

    def check_collision(self, position):
        # Check if the head collides with the position
        return self.get_head_position() == position

    def check_self_collision(self):
        # Check if the head collides with any part of its body
        return self.get_head_position() in self.body[1:]

    def check_wall_collision(self):
        head_x, head_y = self.get_head_position()
        return head_x < 0 or head_x >= (SCREEN_WIDTH // CELL_SIZE) or head_y < 0 or head_y >= (SCREEN_HEIGHT // CELL_SIZE)

class AI_Snake(Snake):
    def __init__(self, color, position):
        super().__init__(color, position)

    def update(self, food_position):
        head_x, head_y = self.get_head_position()
        possible_moves = [UP, DOWN, LEFT, RIGHT]
        valid_moves = []

        # Check for valid moves (not hitting walls)
        for move in possible_moves:
            new_head = (head_x + move[0], head_y + move[1])
            if not self.check_wall_collision_move(new_head) and not self.check_self_collision_move(new_head):
                valid_moves.append(move)

        if valid_moves:
            target_move = self.get_best_move(valid_moves, food_position)
            if target_move and random.random() < 0.8:  # 80% chance to go towards food
                self.change_direction(target_move)
            else:
                self.change_direction(random.choice(valid_moves))

        super().update()


    def check_wall_collision_move(self, position):
        head_x, head_y = position
        return head_x < 0 or head_x >= (SCREEN_WIDTH // CELL_SIZE) or head_y < 0 or head_y >= (SCREEN_HEIGHT // CELL_SIZE)

    def check_self_collision_move(self, position):
        return position in self.body

    def get_best_move(self, valid_moves, food_position):
        best_move = None
        min_distance = float('inf')

        for move in valid_moves:
            new_head = (self.get_head_position()[0] + move[0], self.get_head_position()[1] + move[1])
            distance = self.calculate_distance(new_head, food_position)
            if distance < min_distance:
                min_distance = distance
                best_move = move

        return best_move

    def calculate_distance(self, pos1, pos2):
        return abs(pos1[0] - pos2[0]) + abs(pos1[1] - pos2[1])

def draw_food(surface, position):
    pygame.draw.rect(surface, RED, (position[0] * CELL_SIZE, position[1] * CELL_SIZE, CELL_SIZE, CELL_SIZE))

def main():
    screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
    pygame.display.set_caption("Snake Game with Improved AI Opponent")
    clock = pygame.time.Clock()

    player_snake = Snake(GREEN, (5, 5))
    ai_snake = AI_Snake(WHITE, (10, 10))
    food_position = (random.randint(0, (SCREEN_WIDTH // CELL_SIZE) - 1), random.randint(0, (SCREEN_HEIGHT // CELL_SIZE) - 1))

    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()
            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_UP:
                    player_snake.change_direction(UP)
                elif event.key == pygame.K_DOWN:
                    player_snake.change_direction(DOWN)
                elif event.key == pygame.K_LEFT:
                    player_snake.change_direction(LEFT)
                elif event.key == pygame.K_RIGHT:
                    player_snake.change_direction(RIGHT)

        player_snake.update()
        ai_snake.update(food_position)

        # Check for collisions
        if player_snake.check_wall_collision() or player_snake.check_self_collision():
            print("Game Over! Player collided with the wall or itself.")
            pygame.quit()
            sys.exit()

        if ai_snake.check_wall_collision() or ai_snake.check_self_collision():
            print("Game Over! AI collided with the wall or itself.")
            pygame.quit()
            sys.exit()

        # Check for food collision
        if player_snake.check_collision(food_position):
            player_snake.grow()
            food_position = (random.randint(0, (SCREEN_WIDTH // CELL_SIZE) - 1), random.randint(0, (SCREEN_HEIGHT // CELL_SIZE) - 1))
        if ai_snake.check_collision(food_position):
            ai_snake.grow()
            food_position = (random.randint(0, (SCREEN_WIDTH // CELL_SIZE) - 1), random.randint(0, (SCREEN_HEIGHT // CELL_SIZE) - 1))

        # Clear the screen
        screen.fill(BLACK)

        # Draw everything
        player_snake.draw(screen)
        ai_snake.draw(screen)
        draw_food(screen, food_position)

        pygame.display.flip()
        clock.tick(FPS)

if __name__ == "__main__":
    main()



Massively overhaul.