引言
贪吃蛇游戏是一款经典的电子游戏,玩家通过控制一条不断增长的蛇在格子内移动,并吃掉随机出现的食物来获得分数。随着分数的增加,蛇的身体也会越来越长,游戏的难度也随之提升。在本文中,我们将详细介绍如何使用Python来制作一个简单的贪吃蛇小游戏,包括游戏的实现过程、使用的工具及关键技术点。****
   
  
# 设置屏幕大小  
screen_width = 640  
screen_height = 480  
screen = pygame.display.set_mode((screen_width, screen_height))  
  
# 设置标题  
pygame.display.set_caption("贪吃蛇小游戏")  
  
# 定义颜色  
black = (0, 0, 0)  
white = (255, 255, 255)  
green = (0, 255, 0)  
red = (255, 0, 0)
 
2. 贪吃蛇类
 接下来,我们定义一个贪吃蛇类,包含蛇的位置、方向、身体等属性,以及移动方法。
class Snake:  
    def __init__(self):  
        self.body = [(100, 50)]  
        self.direction = (0, 1)  # (0, 1)向右, (0, -1)向左, (1, 0)向下, (-1, 0)向上  
  
    def move(self):  
        head = self.body[0]  
        new_head = (head[0] + self.direction[0], head[1] + self.direction[1])  
        self.body.insert(0, new_head)  
  
    def turn(self, direction):  
        # 判断是否可以转向  
        if direction == (0, 1) and self.direction != (0, -1):  
            self.direction = direction  
        elif direction == (0, -1) and self.direction != (0, 1):  
            self.direction = direction  
        elif direction == (1, 0) and self.direction != (-1, 0):  
            self.direction = direction  
        elif direction == (-1, 0) and self.direction != (1, 0):  
            self.direction = direction  
  
    def grow(self):  
        # 当吃到食物时调用  
        self.body.append(self.body[-1])
 
3. 食物类
 定义食物类,用于随机生成食物的位置。
class Food:  
    def __init__(self):  
        self.position = (random.randint(0, screen_width // 10) * 10, random.randint(0, screen_height // 10) * 10)  
  
    def respawn(self):  
        self.position = (random.randint(0, screen_width // 10) * 10, random.randint(0, screen_height // 10) * 10)
 
- 游戏主循环
游戏的主循环处理用户输入、更新游戏状态、绘制游戏元素,并检查游戏是否结束。 
# 创建蛇和食物对象  
snake = Snake()  
food = Food()  
  
running = True  
while running:  
    for event in pygame.event.get():  
        if event.type == pygame.QUIT:  
            running = False  
        # 添加键盘事件处理  
        elif event.type == pygame.KEYDOWN:  
            if event.key == pygame.K_RIGHT:  
                snake.turn((0, 1))  
            elif event.key == pygame.K_LEFT:  
                snake.turn((0, -1))  
            elif event.key == pygame.K_DOWN:  
                snake.turn((1
 
完整源码及素材已经打包好了:


















