菜鸟都收藏了:如何用Pycharm创建Python项目并编写贪吃蛇游戏

一、用Pycharm创建并编写贪吃蛇项目

在这里插入图片描述

1.打开Pycharm

在这里插入图片描述

2.新建Python项目tanchishe

1.>点击菜单File->New Project…

在这里插入图片描述

2.> 设置项目名称目录和运行环境
  • 项目名称填写: tanchishe
  • 运行环境使用:Conda (即 Anaconda,如果没有Anaconda则自己下载安装 )
  • Python version:选择3.6
  • Conda exectable:你自己的 Anaconda 的安装位置
  • 然后点击Create创建项目
    在这里插入图片描述
3.> 项目创建中

在这里插入图片描述
在这里插入图片描述

4.> 设置软件源地址为default

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

5.>在项目中新建tanchishe.py文件

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

6.>在tanchishe.py文件中编写代码
# pip install pygame # 安装pygame 库
# 如果此命令安装失败则尝试使用下面的命令安装
# python3 -m pip install pygame

# 1. 引入所需包
import pygame, sys, random
from pygame.locals import *

# 2. 定义游戏结束的函数
def gameOver():
    pygame.quit()
    sys.exit()

# 3. 获取下一步应该运动的方向(包含获取键盘按下的方向)
def getKeyboardDirection(direction):
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()
        elif event.type == KEYDOWN:
            # 判断键盘事件
            if event.key == K_RIGHT:  # 向右
                # 确定方向,移动蛇头坐标
                if not direction == 'left':
                    return 'right'
            elif event.key == K_LEFT:  # 向左
                # 确定方向,移动蛇头坐标
                if not direction == 'right':
                    return 'left'
            elif event.key == K_UP:  # 向上
                # 确定方向,移动蛇头坐标
                if not direction == 'down':
                    return 'up'
            elif event.key == K_DOWN:  # 向下
                # 确定方向,移动蛇头坐标
                if not direction == 'up':
                    return 'down'
            else:
                return direction
    return direction


# 4. 实现工作方式
def main():

    # 4.1 定义颜色变量
    greenColor = pygame.Color(0, 255, 0)  # 目标方块的颜色 r g b 取值范围 0 -255
    blueColor = pygame.Color(0, 0, 255)  # 贪吃蛇的颜色
    blackColor = pygame.Color(0, 0, 0)  # 背景颜色

    # 4.2 初始化变量

    # 初始化游戏界面尺寸
    wWidth = 640 # 游戏界面窗口宽度
    wHeight = 480 # 游戏界面窗口高度

    # 初始化蛇数据
    snakeBody = [[100, 100], [80, 100], [60, 100]]  # 蛇全身各段的初始位置(像素坐标)
    snakePosition = [100, 100]  # 蛇头的初始位置(像素坐标)
    snakeTail = [60, 100]  # 蛇尾巴

    # 初始化苹果数据
    applePosition = [260, 200]  # 苹果的初始位置(像素坐标)
    blockSize = 20 #方格宽高像素尺寸,蛇身体宽度,苹果宽高与此一至
    direction = 'right'  # 蛇运动的初始方向

    # 初始化爬行速度单位每秒爬行步数
    speed = 6

    # 4.3 初始化Pygame
    pygame.init()

    # 4.4 定义一个变量用来控制游戏的速度
    fpsClock = pygame.time.Clock()

    # 4.5 创建pygame的显示层
    playSurface = pygame.display.set_mode((wWidth, wHeight))
    pygame.display.set_caption('贪吃蛇')

    # 4.6 画苹果
    pygame.draw.rect(playSurface, greenColor, Rect(applePosition[0], applePosition[1], blockSize, blockSize))

    # 4.7 画蛇
    for position in snakeBody:
        # 画蛇
        pygame.draw.rect(playSurface, blueColor, Rect(position[0], position[1], blockSize, blockSize))

    # 4.8 更新界面显示(画的新图像需要重新显示)
    pygame.display.flip()

    # 4.9 pygame 所有的事件要放到 一个循环中完成
    # 每次循环,意味着蛇爬行一步,并且在每次循环中要读取键盘所按方向键,没有按方向则按原来方向继续爬行,如果改变了方向,则调整爬行方向
    while True:

        # 4.9.1 读取蛇运动方向(当键盘按方向键后,direction 值会及时更新)
        direction = getKeyboardDirection(direction)

        # 4.9.2 根据方向修改蛇头的新坐标数据
        if direction == 'right': snakePosition[0] += blockSize
        if direction == 'left': snakePosition[0] -= blockSize
        if direction == 'down': snakePosition[1] += blockSize
        if direction == 'up': snakePosition[1] -= blockSize

        # 4.9.3 新的蛇头数据放入蛇列表数据开头
        snakeBody.insert(0, list(snakePosition))
        # 4.9.4 画新的蛇头(身体不需要重新画)
        pygame.draw.rect(playSurface, blueColor, Rect(snakePosition[0], snakePosition[1], blockSize, blockSize))

        # 4.9.5 画新的苹果
        # 如果我们的贪吃蛇的位置和目标方块重合了,说明吃到了目标方块
        if snakePosition[0] == applePosition[0] and snakePosition[1] == applePosition[1]:
            # 旧的苹果已经变成了蛇头
            # 生成新的苹果
            x = random.randrange(1, wWidth/blockSize) # 新苹果所在方块 水平序号x
            y = random.randrange(1, wHeight/blockSize) # 新苹果所在方块 垂直序号y
            applePosition = [x*blockSize, y*blockSize] # 新苹果像素坐标

            # 画新的苹果
            pygame.draw.rect(playSurface, greenColor, Rect(applePosition[0], applePosition[1], 20, 20))
        # 4.9.6 如果吃到苹果,则由于蛇身体向前移动了,需要把原来尾巴位置的色块清除,尾巴数据需要从列表中删去
        else:
            # 清空蛇尾元素和颜色快
            snakeLen = len(snakeBody) # 获取蛇身列表数据长度
            snakeTail = snakeBody[snakeLen-1]; # 得到蛇尾巴像素坐标
            pygame.draw.rect(playSurface, blackColor, Rect(snakeTail[0], snakeTail[1], 20, 20))  # 把原尾巴的位置的颜色设置为背景色
            snakeBody.pop() # 将原尾巴数据删去

        # 4.9.7 更新显示
        pygame.display.flip()
        # 爬行动作频次时钟控制
        fpsClock.tick(speed)

        # 4.9.8 如果碰到围墙则 gameOver
        if snakePosition[0] > (wWidth - 20) or snakePosition[0] < 0:
            gameOver()
        elif snakePosition[1] > (wHeight - 20) or snakePosition[1] < 0:
            gameOver()

        # 4.9.9 如果碰到了自己的身体则 gameOver
        for s in snakeBody[1:]:# 遍历蛇身,判断蛇头是否与蛇身重合
            if snakePosition[0] == s[0] and snakePosition[1] == s[1]:
                gameOver()

# 程序入口
if __name__ == '__main__':
    main()
7.> 排除语法等错误
  • 这里缺少pygame库
    在这里插入图片描述
  • 从控制台执行 pip install pygame
    在这里插入图片描述
  • 执行结果如下(安装完成):
(tanchishe) wdh@wdh:~/PycharmProjects/tanchishe$ pip install pygame
Collecting pygame
  WARNING: Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NewConnectionError('<pip._vendor.urllib3.connection.VerifiedHTTPSConnection object at 0x7f6bc41d8da0>: Failed to establish a new connection: [Errno 101] 网络不可达',)': /packages/8e/24/ede6428359f913ed9cd1643dd5533aefeb5a2699cc95bea089de50ead586/pygame-1.9.6-cp36-cp36m-manylinux1_x86_64.whl
  WARNING: Retrying (Retry(total=3, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NewConnectionError('<pip._vendor.urllib3.connection.VerifiedHTTPSConnection object at 0x7f6bc41e10f0>: Failed to establish a new connection: [Errno 101] 网络不可达',)': /packages/8e/24/ede6428359f913ed9cd1643dd5533aefeb5a2699cc95bea089de50ead586/pygame-1.9.6-cp36-cp36m-manylinux1_x86_64.whl
  WARNING: Retrying (Retry(total=2, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NewConnectionError('<pip._vendor.urllib3.connection.VerifiedHTTPSConnection object at 0x7f6bc41ec780>: Failed to establish a new connection: [Errno 101] 网络不可达',)': /packages/8e/24/ede6428359f913ed9cd1643dd5533aefeb5a2699cc95bea089de50ead586/pygame-1.9.6-cp36-cp36m-manylinux1_x86_64.whl
  WARNING: Retrying (Retry(total=1, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NewConnectionError('<pip._vendor.urllib3.connection.VerifiedHTTPSConnection object at 0x7f6bc41ec2b0>: Failed to establish a new connection: [Errno 101] 网络不可达',)': /packages/8e/24/ede6428359f913ed9cd1643dd5533aefeb5a2699cc95bea089de50ead586/pygame-1.9.6-cp36-cp36m-manylinux1_x86_64.whl
  WARNING: Retrying (Retry(total=0, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NewConnectionError('<pip._vendor.urllib3.connection.VerifiedHTTPSConnection object at 0x7f6bc4174048>: Failed to establish a new connection: [Errno 101] 网络不可达',)': /packages/8e/24/ede6428359f913ed9cd1643dd5533aefeb5a2699cc95bea089de50ead586/pygame-1.9.6-cp36-cp36m-manylinux1_x86_64.whl
  Downloading pygame-1.9.6-cp36-cp36m-manylinux1_x86_64.whl (11.4 MB)
     |████████████████████████████████| 11.4 MB 76 kB/s 
Installing collected packages: pygame
Successfully installed pygame-1.9.6
(tanchishe) wdh@wdh:~/PycharmProjects/tanchishe$ 
  • 可以看到红色下划线消失了
    在这里插入图片描述
8.>开始运行:Run-》Run …

在这里插入图片描述
在这里插入图片描述

9.>运行效果

在这里插入图片描述

发布了118 篇原创文章 · 获赞 17 · 访问量 7万+

猜你喜欢

转载自blog.csdn.net/one312/article/details/105466298
今日推荐