python Copy code
import pygame
import random
import sys
# --- Constants ---
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600
GRID_SIZE = 20
GRID_WIDTH = SCREEN_WIDTH // GRID_SIZE
GRID_HEIGHT = SCREEN_HEIGHT // GRID_SIZE
# Colors
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
GREEN_FOOD = (0, 200, 0)
INITIAL_SNAKE_COLOR = (255, 255, 0) # Yellow
# Food types and their colors
FOOD_TYPE_COLORS = {
"NORMAL": GREEN_FOOD,
"SLOW_MO": (0, 150, 255), # Light Blue
"GHOST": (180, 0, 180), # Purple
"PORTAL_SPAWNER": (255, 140, 0), # Orange
"DECOY": (100, 100, 100) # Grey
}
# Food probabilities
FOOD_PROBABILITIES = {
"NORMAL": 0.55,
"SLOW_MO": 0.12,
"GHOST": 0.12,
"PORTAL_SPAWNER": 0.08,
"DECOY": 0.13
}
# Snake speeds
NORMAL_SPEED = 10
SLOW_MO_SPEED = 5
DECOY_FAST_SPEED = 15
# Power-up durations (in milliseconds)
POWER_UP_DURATION = 8000 # 8 seconds
PORTAL_DURATION = 10000 # 10 seconds
REVERSE_CONTROLS_DURATION = 5000 # 5 seconds
# --- Game Classes ---
class Snake:
def __init__(self):
self.length = 1
# Each segment is [[x, y], color]
self.positions = [([GRID_WIDTH // 2, GRID_HEIGHT // 2], INITIAL_SNAKE_COLOR)]
self.direction = random.choice([(0, 1), (0, -1), (1, 0), (-1, 0)])
self.color = INITIAL_SNAKE_COLOR # Current color of the head, new segments get this
self.score = 0
self.ghost_mode = False
self.ghost_mode_timer = 0
self.reverse_controls = False
self.reverse_controls_timer = 0
def get_head_position(self):
return self.positions[0][0]
def turn(self, point):
if self.length > 1 and (point[0] * -1, point[1] * -1) == self.direction:
return # Can't turn back on itself
else:
self.direction = point
def move(self):
cur_x, cur_y = self.get_head_position()
dx, dy = self.direction
if self.reverse_controls:
dx, dy = -dx, -dy
new_x = (cur_x + dx) % GRID_WIDTH
new_y = (cur_y + dy) % GRID_HEIGHT
new_head_pos = [new_x, new_y]
# Check wall collision
# (Handled by modulo arithmetic for wrap-around, or explicitly if hard walls)
# For this version, let's use wrap-around. Game over by self-collision.
# Chameleon Effect: New head segment gets the snake's current primary color
self.positions.insert(0, (new_head_pos, self.color))
if len(self.positions) > self.length:
self.positions.pop()
def grow(self):
self.length += 1
self.score += 10
def shrink(self, amount=1):
if self.length > amount:
self.length -= amount
for _ in range(amount):
if self.positions:
self.positions.pop()
elif self.length > 1: # Ensure snake doesn't disappear if shrink amount is too large
self.length = 1
self.positions = [self.positions[0]]
def check_self_collision(self):
if self.ghost_mode:
return False
head_pos = self.get_head_position()
return any(segment[0] == head_pos for segment in self.positions[1:])
def draw(self, surface):
for pos_color_pair in self.positions:
pos, color = pos_color_pair
r = pygame.Rect(pos[0] * GRID_SIZE, pos[1] * GRID_SIZE, GRID_SIZE, GRID_SIZE)
# Ghost mode transparency
if self.ghost_mode:
s = pygame.Surface((GRID_SIZE, GRID_SIZE), pygame.SRCALPHA)
s.fill((color[0], color[1], color[2], 128)) # 128 for 50% transparency
surface.blit(s, (r.x, r.y))
else:
pygame.draw.rect(surface, color, r)
pygame.draw.rect(surface, BLACK, r, 1) # Border
class Food:
def __init__(self, food_type, position, color):
self.type = food_type
self.position = position # [x, y]
self.color = color
def draw(self, surface):
r = pygame.Rect(self.position[0] * GRID_SIZE, self.position[1] * GRID_SIZE, GRID_SIZE, GRID_SIZE)
pygame.draw.rect(surface, self.color, r)
if self.type == "DECOY": # Special marking for decoy
pygame.draw.circle(surface, RED, r.center, GRID_SIZE // 4)
elif self.type == "PORTAL_SPAWNER":
pygame.draw.line(surface, BLACK, r.topleft, r.bottomright, 2)
pygame.draw.line(surface, BLACK, r.topright, r.bottomleft, 2)
class Portal:
def __init__(self, pos1, pos2):
self.pos1 = pos1
self.pos2 = pos2
self.color1 = (100, 200, 255) # Light blueish
self.color2 = (255, 200, 100) # Light orangeish
self.active_until = pygame.time.get_ticks() + PORTAL_DURATION
def draw(self, surface):
# Portal 1
r1 = pygame.Rect(self.pos1[0] * GRID_SIZE, self.pos1[1] * GRID_SIZE, GRID_SIZE, GRID_SIZE)
pygame.draw.ellipse(surface, self.color1, r1)
pygame.draw.ellipse(surface, BLACK, r1, 2)
# Portal 2
r2 = pygame.Rect(self.pos2[0] * GRID_SIZE, self.pos2[1] * GRID_SIZE, GRID_SIZE, GRID_SIZE)
pygame.draw.ellipse(surface, self.color2, r2)
pygame.draw.ellipse(surface, BLACK, r2, 2)
def is_active(self):
return pygame.time.get_ticks() < self.active_until
# --- Helper Functions ---
def spawn_new_food(snake_positions, existing_portal_positions):
occupied_positions = [tuple(p[0]) for p in snake_positions]
if existing_portal_positions:
occupied_positions.extend(existing_portal_positions)
while True:
pos = [random.randint(0, GRID_WIDTH - 1), random.randint(0, GRID_HEIGHT - 1)]
if tuple(pos) not in occupied_positions:
food_type = random.choices(
list(FOOD_PROBABILITIES.keys()),
weights=list(FOOD_PROBABILITIES.values()),
k=1
)[0]
return Food(food_type, pos, FOOD_TYPE_COLORS[food_type])
def spawn_portals(snake_positions):
occupied_positions = [tuple(p[0]) for p in snake_positions]
pos1, pos2 = None, None
while pos1 is None or tuple(pos1) in occupied_positions:
pos1 = [random.randint(0, GRID_WIDTH - 1), random.randint(0, GRID_HEIGHT - 1)]
occupied_positions.append(tuple(pos1)) # Add pos1 to occupied so pos2 is different
while pos2 is None or tuple(pos2) in occupied_positions:
pos2 = [random.randint(0, GRID_WIDTH - 1), random.randint(0, GRID_HEIGHT - 1)]
return Portal(pos1, pos2)
def display_text(surface, text, position, font, color=WHITE):
text_surface = font.render(text, True, color)
surface.blit(text_surface, position)
# --- Main Game Logic ---
def game_loop():
pygame.init()
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption("Creative Snake")
clock = pygame.time.Clock()
font = pygame.font.SysFont("monospace", 20)
small_font = pygame.font.SysFont("monospace", 16)
snake = Snake()
portals = None # Stores the active Portal object
# Initial food
portal_coords_for_food_spawn = []
if portals and portals.is_active():
portal_coords_for_food_spawn = [tuple(portals.pos1), tuple(portals.pos2)]
current_food = spawn_new_food(snake.positions, portal_coords_for_food_spawn)
current_game_speed = NORMAL_SPEED
slow_mo_active = False
slow_mo_timer = 0
decoy_speed_boost_active = False
decoy_speed_boost_timer = 0
running = True
game_over = False
while running:
current_time = pygame.time.get_ticks()
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.KEYDOWN:
if game_over:
if event.key == pygame.K_r: # Restart game
return game_loop() # Call game_loop again to reset
if event.key == pygame.K_q:
running = False
else:
if event.key == pygame.K_UP:
snake.turn((0, -1))
elif event.key == pygame.K_DOWN:
snake.turn((0, 1))
elif event.key == pygame.K_LEFT:
snake.turn((-1, 0))
elif event.key == pygame.K_RIGHT:
snake.turn((1, 0))
if game_over:
screen.fill(BLACK)
display_text(screen, "GAME OVER!", (SCREEN_WIDTH // 2 - 100, SCREEN_HEIGHT // 2 - 50), font, RED)
display_text(screen, f"Final Score: {snake.score}", (SCREEN_WIDTH // 2 - 100, SCREEN_HEIGHT // 2), font)
display_text(screen, "Press 'R' to Restart or 'Q' to Quit", (SCREEN_WIDTH // 2 - 200, SCREEN_HEIGHT // 2 + 50), font)
pygame.display.flip()
clock.tick(5) # Lower tick rate for game over screen
continue
# --- Update Game State ---
snake.move()
# Power-up timer checks
if slow_mo_active and current_time > slow_mo_timer:
slow_mo_active = False
if snake.ghost_mode and current_time > snake.ghost_mode_timer:
snake.ghost_mode = False
if portals and not portals.is_active():
portals = None
if snake.reverse_controls and current_time > snake.reverse_controls_timer:
snake.reverse_controls = False
if decoy_speed_boost_active and current_time > decoy_speed_boost_timer:
decoy_speed_boost_active = False
# Update game speed based on active effects
if decoy_speed_boost_active:
current_game_speed = DECOY_FAST_SPEED
elif slow_mo_active:
current_game_speed = SLOW_MO_SPEED
else:
current_game_speed = NORMAL_SPEED
# Food collision
if snake.get_head_position() == current_food.position:
snake.grow()
snake.color = current_food.color # Chameleon: Snake head (and new segments) take food color
food_type = current_food.type
if food_type == "SLOW_MO":
slow_mo_active = True
slow_mo_timer = current_time + POWER_UP_DURATION
# If decoy speed boost was active, slow-mo overrides it
decoy_speed_boost_active = False
elif food_type == "GHOST":
snake.ghost_mode = True
snake.ghost_mode_timer = current_time + POWER_UP_DURATION
elif food_type == "PORTAL_SPAWNER":
if portals: # Remove old portals if any
portals = None
portals = spawn_portals(snake.positions)
elif food_type == "DECOY":
snake.score -= 20 # Penalty for decoy
effect = random.choice(["REVERSE_CONTROLS", "SHRINK", "SPEED_UP"])
if effect == "REVERSE_CONTROLS":
snake.reverse_controls = True
snake.reverse_controls_timer = current_time + REVERSE_CONTROLS_DURATION
elif effect == "SHRINK":
snake.shrink(random.randint(1,3)) # Shrink by 1 to 3 segments
elif effect == "SPEED_UP":
decoy_speed_boost_active = True
decoy_speed_boost_timer = current_time + POWER_UP_DURATION
# If slow-mo was active, speed boost overrides it
slow_mo_active = False
portal_coords_for_food_spawn = []
if portals and portals.is_active():
portal_coords_for_food_spawn = [tuple(portals.pos1), tuple(portals.pos2)]
current_food = spawn_new_food(snake.positions, portal_coords_for_food_spawn)
# Portal teleportation
if portals and portals.is_active():
head_pos_tuple = tuple(snake.get_head_position())
teleported = False
if head_pos_tuple == tuple(portals.pos1):
snake.positions[0] = (list(portals.pos2), snake.positions[0][1]) # Teleport head
teleported = True
elif head_pos_tuple == tuple(portals.pos2):
snake.positions[0] = (list(portals.pos1), snake.positions[0][1]) # Teleport head
teleported = True
if teleported:
portals = None # Portals are one-time use after teleport
# After teleport, check for immediate self-collision if not in ghost mode
if not snake.ghost_mode and snake.check_self_collision():
game_over = True
# Check self-collision (primary game over condition)
if not game_over and snake.check_self_collision():
game_over = True
# --- Drawing ---
screen.fill(BLACK)
snake.draw(screen)
current_food.draw(screen)
if portals and portals.is_active():
portals.draw(screen)
# UI Text
display_text(screen, f"Score: {snake.score}", (10, 10), font)
status_y = 35
if slow_mo_active:
display_text(screen, "SLOW-MO ACTIVE!", (10, status_y), small_font, FOOD_TYPE_COLORS["SLOW_MO"])
status_y += 20
if snake.ghost_mode:
display_text(screen, "GHOST MODE!", (10, status_y), small_font, FOOD_TYPE_COLORS["GHOST"])
status_y += 20
if snake.reverse_controls:
display_text(screen, "CONTROLS REVERSED!", (10, status_y), small_font, RED)
status_y += 20
if decoy_speed_boost_active:
display_text(screen, "SPEED BOOST!", (10, status_y), small_font, RED)
status_y += 20
if portals and portals.is_active():
display_text(screen, "PORTALS OPEN!", (10, status_y), small_font, FOOD_TYPE_COLORS["PORTAL_SPAWNER"])
pygame.display.flip()
clock.tick(current_game_speed)
pygame.quit()
sys.exit()
if __name__ == "__main__":
game_loop()