python 贪吃蛇

本例子需要使用已安装pygame的python才能运行

#!/usr/bin/env python
import pygame,sys,time,random
from pygame.locals import *
# 定义颜色变量
redColour = pygame.Color(255,0,0)
blackColour = pygame.Color(0,0,0)
whiteColour = pygame.Color(255,255,255)
greyColour = pygame.Color(150,150,150)

# 定义gameOver函数
def gameOver(playSurface):
    gameOverFont = pygame.font.Font('arial.ttf',72)
    gameOverSurf = gameOverFont.render('Game Over', True, greyColour)
    gameOverRect = gameOverSurf.get_rect()
    gameOverRect.midtop = (320, 10)
    playSurface.blit(gameOverSurf, gameOverRect)
    pygame.display.flip()
    time.sleep(5)
    pygame.quit()
    sys.exit()

# 定义main函数
def main():
    # 初始化pygame
    pygame.init()
    fpsClock = pygame.time.Clock()
    # 创建pygame显示层
    playSurface = pygame.display.set_mode((640,480))
    pygame.display.set_caption('贪吃蛇')

    # 初始化变量
    snakePosition = [100,100]
    snakeSegments = [[100,100],[80,100],[60,100]]
    raspberryPosition = [300,300]
    raspberrySpawned = 1
    direction = 'right'
    changeDirection = direction
    while True:
        # 检测例如按键等pygame事件
        for event in pygame.event.get():
            if event.type == QUIT:
                pygame.quit()
                sys.exit()
            elif event.type == KEYDOWN:
                # 判断键盘事件
                if event.key == K_RIGHT or event.key == ord('d'):
                    changeDirection = 'right'
                if event.key == K_LEFT or event.key == ord('a'):
                    changeDirection = 'left'
                if event.key == K_UP or event.key == ord('w'):
                    changeDirection = 'up'
                if event.key == K_DOWN or event.key == ord('s'):
                    changeDirection = 'down'
                if event.key == K_ESCAPE:
                    pygame.event.post(pygame.event.Event(QUIT))
        # 判断是否输入了反方向
        if changeDirection == 'right' and not direction == 'left':
            direction = changeDirection
        if changeDirection == 'left' and not direction == 'right':
            direction = changeDirection
        if changeDirection == 'up' and not direction == 'down':
            direction = changeDirection
        if changeDirection == 'down' and not direction == 'up':
            direction = changeDirection
        # 根据方向移动蛇头的坐标
        if direction == 'right':
            snakePosition[0] += 20
        if direction == 'left':
            snakePosition[0] -= 20
        if direction == 'up':
            snakePosition[1] -= 20
        if direction == 'down':
            snakePosition[1] += 20
        # 增加蛇的长度
        snakeSegments.insert(0,list(snakePosition))
        # 判断是否吃掉了树莓
        if snakePosition[0] == raspberryPosition[0] and snakePosition[1] == raspberryPosition[1]:
            raspberrySpawned = 0
        else:
            snakeSegments.pop()
        # 如果吃掉树莓,则重新生成树莓
        if raspberrySpawned == 0:
            x = random.randrange(1,32)
            y = random.randrange(1,24)
            raspberryPosition = [int(x*20),int(y*20)]
            raspberrySpawned = 1
        # 绘制pygame显示层
        playSurface.fill(blackColour)
        for position in snakeSegments:
            pygame.draw.rect(playSurface,whiteColour,Rect(position[0],position[1],20,20))
            pygame.draw.rect(playSurface,redColour,Rect(raspberryPosition[0], raspberryPosition[1],20,20))

        # 刷新pygame显示层
        pygame.display.flip()
        # 判断是否死亡
        if snakePosition[0] > 620 or snakePosition[0] < 0:
            gameOver(playSurface)
        if snakePosition[1] > 460 or snakePosition[1] < 0:
            for snakeBody in snakeSegments[1:]:
                if snakePosition[0] == snakeBody[0] and snakePosition[1] == snakeBody[1]:
                    gameOver(playSurface)
        # 控制游戏速度
        fpsClock.tick(5)

if __name__ == "__main__":
    main()
<think>好的,我现在需要帮助用户解决如何用Python编写贪吃蛇游戏的问题。根据用户提供的引用内容,我需要整合这些信息并生成一个结构清晰的回答,同时遵循系统级指令中的格式要求。 首先,我需要确认用户的需求。用户想要寻找相关的教程和示例代码,并且已经提供了几个引用,其中提到了使用turtle库和pygame库的实现方法。因此,我应该分别介绍这两种方式,并给出示例代码。 接下来,我需要检查每个引用的内容。引用[2]提到使用turtle库分模块编写,引用[4]有一个简单的示例代码,而引用[3]涉及pygame的事件处理。因此,可能需要将这两种方法分开讲解,并分别提供代码示例。 然后,我需要确保回答符合系统级指令,比如行内数学表达式用$...$,独立公式用$$...$$。不过,贪吃蛇游戏可能不涉及数学公式,所以这部分可能不需要。但需要遵守LaTeX语法正确,使用中文回答,生成相关问题,并在引用末尾添加标识。 用户提供的引用中有四个,但有些可能与问题相关度不高,比如引用[1]和引用[3]中的部分内容。需要筛选出有用的部分,例如引用[2]和引用[4]提供了具体的代码结构和示例,而引用[3]中的事件处理代码可以作为pygame实现的参考。 接下来,我需要构建回答的结构。首先介绍使用turtle库的方法,给出分模块的代码示例,然后介绍pygame的实现,再提供一个简单示例。每个部分需要代码块,并确保代码正确。同时,引用需要自然地添加在相关段落末尾。 另外,用户可能需要教程式的指导,分步骤讲解如何实现。例如,初始化窗口、处理键盘事件、蛇的移动逻辑、食物生成、碰撞检测等。每个步骤对应代码中的部分,并进行解释。 还需要注意用户可能对代码的模块化有要求,如引用[2]提到的分为主程序入口、功能模块和配置文件三个文件。因此,在turtle库的例子中可能需要分模块展示,而pygame的示例可能较为简单,直接给出完整代码。 最后,生成相关问题,比如两种库的优缺点、如何添加计分功能、遇到的常见错误等,这些问题可以帮助用户进一步学习。 现在需要整合这些思考,编写符合格式的回答,确保引用正确,代码正确无误,并且结构清晰,分步骤讲解。</think>### Python贪吃蛇游戏实现教程 #### 一、使用turtle库实现(适合初学者) ```python # 配置文件 config.py WIDTH = 600 HEIGHT = 400 SEGMENT_SIZE = 20 DELAY = 100 # 毫秒 COLORS = { "background": "black", "snake": "green", "food": "red" } ``` ```python # 功能模块 snake.py import turtle from config import * class SnakeGame: def __init__(self): self.window = turtle.Screen() self.window.setup(WIDTH, HEIGHT) self.window.bgcolor(COLORS["background"]) self.snake = turtle.Turtle() self.snake.shape("square") self.snake.color(COLORS["snake"]) self.snake.penup() self.food = self.create_food() self.direction = "stop" ``` ```python # 主程序 main.py from snake import SnakeGame import time game = SnakeGame() while True: game.window.update() time.sleep(DELAY/1000) ``` 实现步骤: 1. 初始化游戏窗口和基本参数[^2] 2. 创建蛇和食物的图形对象 3. 实现键盘事件监听(需补充方向控制逻辑) 4. 添加移动逻辑和碰撞检测 5. 实现食物再生机制 #### 二、使用pygame实现(适合进阶) ```python import pygame import random # 初始化配置 WIDTH = 800 HEIGHT = 600 CELL_SIZE = 20 class Snake: def __init__(self): self.body = [(100, 100)] self.direction = 'right' def move(self): x, y = self.body[0] if self.direction == 'right': x += CELL_SIZE elif self.direction == 'left': x -= CELL_SIZE elif self.direction == 'up': y -= CELL_SIZE elif self.direction == 'down': y += CELL_SIZE self.body.insert(0, (x, y)) self.body.pop() ``` 核心功能实现要点: 1. 使用`pygame.K_LEFT`等键位实现方向控制[^3] 2. 通过列表操作实现蛇身移动 3. 食物生成使用随机坐标判断 4. 碰撞检测需比较坐标重合度
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值