天天达

贪吃蛇完整代码

 

    以下是一份使用Python的pygame库实现的贪吃蛇游戏的完整代码: ```python import pygame import sys import random # 初始化pygame pygame.init() # 设置屏幕尺寸和标题 screen_size = (800, 600) screen = pygame.display.set_mode(screen_size) pygame.display.set_caption('贪吃蛇') # 设置颜色 white = (255, 255, 255) black = (0, 0, 0) # 设置蛇和食物的大小 snake_size = 20 food_size = 20 # 设置速度 clock = pygame.time.Clock() speed = 10 snake_pos = [100, 100]^, ^[120, 100]^, ^[140, 100] snake_speed = ^[snake_size, 0]^ food_pos = ^[random.randrange(1, (screen_size // food_size)) * food_size, random.randrange(1, (screen_size // food_size)) * food_size]^ food_spawn = True # 游戏主循环 while True: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() keys = pygame.key.get_pressed() for key in keys: if keys^[pygame.K_UP]^ and snake_speed != snake_size: snake_speed = ^[0, -snake_size]^ if keys^[pygame.K_DOWN]^ and snake_speed != -snake_size: snake_speed = ^[0, snak