贪吃蛇
2026-01-11 11:21:50
发布于:浙江
本人创作,盗版必究
import pygame
import random
import sys
import time
# Initialize Pygame
pygame.init()
pygame.mixer.init()
# Constants
GRID_SIZE = 40 # Increased grid size for larger blocks
TILE_COUNT = 20 # Adjusted tile count to fit within the same canvas size
WIDTH, HEIGHT = GRID_SIZE * TILE_COUNT, GRID_SIZE * TILE_COUNT
FPS = 10 # Frame rate
# Colors
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
# Set up display
screen = pygame.display.set_mode((WIDTH, HEIGHT))
'''pygame.display.set_caption("贪吃蛇")
pygame.mixer.music.load("陈奕迅 - 孤勇者.mp3")
pygame.mixer.music.set_volume(10)
pygame.mixer.music.play()'''
# Snake and food initialization
snake = [{'x': 5, 'y': 5}] # Adjusted initial position
direction = {'x': 0, 'y': 0}
food = {'x': 7, 'y': 7} # Adjusted initial food position
score = 1
def draw_rect(x, y, color):
pygame.draw.rect(screen, color, (x * GRID_SIZE, y * GRID_SIZE, GRID_SIZE, GRID_SIZE))
def place_food():
global food
food['x'] = random.randint(0, TILE_COUNT - 1)
food['y'] = random.randint(0, TILE_COUNT - 1)
def check_collision(head):
for segment in snake[:-1]:
if segment['x'] == head['x'] and segment['y'] == head['y']:
return True
return False
def update_game():
global direction, score,f
# Get current head position
head = {'x': snake[0]['x'] + direction['x'], 'y': snake[0]['y'] + direction['y']}
# Check for game over conditions
if head['x'] < 0 or head['x'] >= TILE_COUNT or head['y'] < 0 or head['y'] >= TILE_COUNT or check_collision(head):
print(f"游戏结束,你的蛇有{score}个方块")
time.sleep(5)
pygame.quit()
#quit()
sys.exit()
# Move snake
snake.insert(0, head)
# Check if snake ate the food
if head['x'] == food['x'] and head['y'] == food['y']:
score += 1
place_food()
else:
snake.pop()
# Clear screen
screen.fill(WHITE)
# Draw Snake
for segment in snake:
draw_rect(segment['x'], segment['y'], GREEN)
# Draw Food
draw_rect(food['x'], food['y'], RED)
# Display Score
font = pygame.font.Font(None, 36)
score_text = font.render(f"Score:{score}", True, BLACK)
screen.blit(score_text, (10, HEIGHT - 40))
# Update display
pygame.display.flip()
def change_direction(event):
global direction
if event.key == pygame.K_LEFT and direction != {'x': 1, 'y': 0}:
direction = {'x': -1, 'y': 0}
elif event.key == pygame.K_UP and direction != {'x': 0, 'y': 1}:
direction = {'x': 0, 'y': -1}
elif event.key == pygame.K_RIGHT and direction != {'x': -1, 'y': 0}:
direction = {'x': 1, 'y': 0}
elif event.key == pygame.K_DOWN and direction != {'x': 0, 'y': -1}:
direction = {'x': 0, 'y': 1}
# Main game loop
clock = pygame.time.Clock()
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.KEYDOWN:
change_direction(event)
update_game()
clock.tick(FPS)
pygame.quit()
这里空空如也











有帮助,赞一个