天天达

贪吃蛇python游戏代码

 

    以下是一个简单的贪吃蛇游戏的Python代码实现示例,使用了pygame库: ```python import pygame import sys import random # 初始化pygame pygame.init() # 设置屏幕大小和标题 screen_width = 600 screen_height = 480 screen = pygame.display.set_mode((screen_width, screen_height)) pygame.display.set_caption('贪吃蛇') # 定义颜色常量 WHITE = (255, 255, 255) BLACK = (0, 0, 0) RED = (255, 0, 0) GREEN = (0, 255, 0) BLUE = (0, 0, 255) # 定义蛇的节点类 class Snake: def __init__(self): self.body = ^[pygame.Rect(250, 240, 20, 20)]^ # 蛇的初始位置 self.direction = 'right' # 蛇的初始方向 self.change_x = 20 self.change_y = 0 def move(self): 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_LEFT or event.key == pygame.K_a) and self.direction != 'right': self.direction = 'left' self.change_x = -20 self.change_y = 0