import pygame
import random
import sys

初始化pygame

pygame.init()

定义颜色

WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
GRAY = (100, 100, 100)

游戏设置

WIDTH, HEIGHT = 600, 600
GRID_SIZE = 20
GRID_WIDTH = WIDTH // GRID_SIZE
GRID_HEIGHT = HEIGHT // GRID_SIZE
SNAKE_SPEED = 10

方向

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

创建游戏窗口

screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption('贪吃蛇')
clock = pygame.time.Clock()

字体

font = pygame.font.SysFont('arial', 30)

class Snake:
def init(self):
self.positions = [(GRID_WIDTH // 2, GRID_HEIGHT // 2)]
self.direction = RIGHT
self.length = 1
self.score = 0
self.color = GREEN

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

def update(self):
    head = self.get_head_position()
    x, y = self.direction
    new_head = ((head[0] + x) % GRID_WIDTH, (head[1] + y) % GRID_HEIGHT)
    
    if new_head in self.positions[1:]:
        return False  # 游戏结束
    
    self.positions.insert(0, new_head)
    if len(self.positions) > self.length:
        self.positions.pop()
    
    return True

def reset(self):
    self.positions = [(GRID_WIDTH // 2, GRID_HEIGHT // 2)]
    self.direction = RIGHT
    self.length = 1
    self.score = 0

def render(self, surface):
    for p in self.positions:
        rect = pygame.Rect((p[0] * GRID_SIZE, p[1] * GRID_SIZE), (GRID_SIZE, GRID_SIZE))
        pygame.draw.rect(surface, self.color, rect)
        pygame.draw.rect(surface, BLACK, rect, 1)

class Food:
def init(self):
self.position = (0, 0)
self.color = RED
self.randomize_position()

def randomize_position(self):
    self.position = (random.randint(0, GRID_WIDTH - 1), random.randint(0, GRID_HEIGHT - 1))

def render(self, surface):
    rect = pygame.Rect((self.position[0] * GRID_SIZE, self.position[1] * GRID_SIZE), (GRID_SIZE, GRID_SIZE))
    pygame.draw.rect(surface, self.color, rect)
    pygame.draw.rect(surface, BLACK, rect, 1)

def draw_grid(surface):
for y in range(0, HEIGHT, GRID_SIZE):
for x in range(0, WIDTH, GRID_SIZE):
rect = pygame.Rect((x, y), (GRID_SIZE, GRID_SIZE))
pygame.draw.rect(surface, GRAY, rect, 1)

def show_game_over(surface, score):
surface.fill(BLACK)
game_over_text = font.render("游戏结束!", True, WHITE)
score_text = font.render(f"得分: {score}", True, WHITE)
restart_text = font.render("按R键重新开始", True, WHITE)
quit_text = font.render("按ESC键退出", True, WHITE)

surface.blit(game_over_text, (WIDTH // 2 - game_over_text.get_width() // 2, HEIGHT // 2 - 60))
surface.blit(score_text, (WIDTH // 2 - score_text.get_width() // 2, HEIGHT // 2 - 20))
surface.blit(restart_text, (WIDTH // 2 - restart_text.get_width() // 2, HEIGHT // 2 + 20))
surface.blit(quit_text, (WIDTH // 2 - quit_text.get_width() // 2, HEIGHT // 2 + 60))

pygame.display.update()

def show_pause(surface):
overlay = pygame.Surface((WIDTH, HEIGHT), pygame.SRCALPHA)
overlay.fill((0, 0, 0, 128))
surface.blit(overlay, (0, 0))

pause_text = font.render("游戏暂停", True, WHITE)
continue_text = font.render("按P键继续游戏", True, WHITE)

surface.blit(pause_text, (WIDTH // 2 - pause_text.get_width() // 2, HEIGHT // 2 - 30))
surface.blit(continue_text, (WIDTH // 2 - continue_text.get_width() // 2, HEIGHT // 2 + 10))

pygame.display.update()

def main():
snake = Snake()
food = Food()
game_over = False
paused = False

while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()
        elif event.type == pygame.KEYDOWN:
            if game_over:
                if event.key == pygame.K_r:  # 重新开始
                    snake.reset()
                    food.randomize_position()
                    game_over = False
                elif event.key == pygame.K_ESCAPE:  # 退出
                    pygame.quit()
                    sys.exit()
            else:
                if event.key == pygame.K_p:  # 暂停/继续
                    paused = not paused
                elif event.key == pygame.K_ESCAPE:  # 退出
                    pygame.quit()
                    sys.exit()
                elif event.key == pygame.K_UP and snake.direction != DOWN:
                    snake.direction = UP
                elif event.key == pygame.K_DOWN and snake.direction != UP:
                    snake.direction = DOWN
                elif event.key == pygame.K_LEFT and snake.direction != RIGHT:
                    snake.direction = LEFT
                elif event.key == pygame.K_RIGHT and snake.direction != LEFT:
                    snake.direction = RIGHT
    
    if game_over:
        show_game_over(screen, snake.score)
        clock.tick(SNAKE_SPEED)
        continue
    
    if paused:
        show_pause(screen)
        clock.tick(SNAKE_SPEED)
        continue
    
    # 更新蛇的位置
    if not snake.update():
        game_over = True
    
    # 检查是否吃到食物
    if snake.get_head_position() == food.position:
        snake.length += 1
        snake.score += 1
        food.randomize_position()
        # 确保食物不会出现在蛇身上
        while food.position in snake.positions:
            food.randomize_position()
    
    # 绘制游戏
    screen.fill(BLACK)
    draw_grid(screen)
    snake.render(screen)
    food.render(screen)
    
    # 显示分数
    score_text = font.render(f"分数: {snake.score}", True, WHITE)
    screen.blit(score_text, (10, 10))
    
    pygame.display.update()
    clock.tick(SNAKE_SPEED)

if name == "main":
main()

posted on 2025-06-17 08:05  雨水啊  阅读(13)  评论(0)    收藏  举报