记一次python游戏编程作业

贪吃蛇

记一次游戏作业

改良老师的贪吃蛇代码

其要求可以是以下的任意一项

  1. 增加音效

    开场背景音乐

    得分音效

    游戏结束音效

  2. 增加游戏玩法

    加速

    增加障碍物

    人机对战

    特殊道具

    总得分

  3. 增加游戏模式

    事件挑战

    闯关模式

    皮肤选择

    双人游戏

老师的意思当然是多多益善 但本人能力有限 只能选几个简单的完成了

于是我选择的是增加背景音效、得分音效以及加速

  1. 背景音效的实现

    在初始化pygame之后 通过load方法加载背景音乐文件

    之后通过其返回的对象 调用混音器进行播放即可

    在主角蛇死亡后游戏结束之前将背景音乐关闭

    代码实现:

    bgm = pygame.mixer.music.load('public/music/backGroundMusic.mp3')
    pygame.mixer.music.play()
    pygame.mixer.music.stop()
    
  2. 得分音效的实现

    当蛇吃到豆子进行得分时 背景音乐是不能停的 如何同时播放两段音乐呢?

    这时候就需要用到Sound方法

    代码实现:

    eat = pygame.mixer.Sound('public/music/eat.wav')
    

    在蛇得分的时候将这段音乐播放

    # 如果贪吃蛇和目标方块的位置重合
    if snakePosition[0] == targetPosition[0] and snakePosition[1] ==targetPosition[1]:    
        # 播放吃豆子的音效    
    	eat.play()    
    	targetflag= 0
    

    值得一提的是 该方法加载的音频文件不能是mp3 否则会报一个 “unable to open file”的错误

  3. 加速

    • 随得分加速

      随着蛇得分越来越高

      蛇的长度会越来越长

      我们可以将蛇的长度处以计算作为蛇的速度

      代码实现:

      # 控制游戏速度
      # 根据蛇的长度控制蛇的速度越来越快
      fps = len(snakeBody) / 2
      fpsClock.tick(fps)
      
    • 用户自定义加速

      根据用户shift键的按下与弹起来决定为蛇加速或还原速度

      • 加速:

        代码实现:

        elif event.type == KEYDOWN:
        # 通过shift为蛇加速    
        	if event.key == K_RSHIFT:        
                fps = len(snakeBody)        
                print(fps)
        
      • 还原

        代码实现:

        # 通过shift键盘抬起事件将蛇的速度还原
        elif event.type == KEYUP:    
            if event.key == K_RSHIFT:        
                fps = len(snakeBody) / 2        
                print(fps)
        

源代码:

# pygame游戏库,sys操控python运行的环境
import pygame ,sys ,random
# 这个模块包含所有pygame所使用的常亮
from  pygame.locals import  *

# 1,定义颜色变量
# 0-255  0黑色  255白色
redColor = pygame.Color(255 ,0 ,0)
# 背景为黑色
blackColor = pygame.Color(0 ,0 ,0)
# 贪吃蛇为白色
whiteColor = pygame.Color(255 ,255 ,255)
# 初始化游戏速度
fps = 2


# 定义游戏结束的函数
def gameover():
    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('贪吃蛇')
    # 初始化变量
    # 贪吃蛇初始坐标位置   (先以100,100为基准)
    snakePosition = [100 ,100]
    # 初始化贪吃蛇的长度列表中有个元素就代表有几段身体
    snakeBody = [[100 ,100] ,[80 ,100] ,[60 ,100]]
    # 初始化目标方向额位置
    targetPosition = [300 ,300]
    # 目标方块的标记 目的:判断是否吃掉了这个目标方块1 就是没有吃 0就是吃掉
    targetflag = 1
    # 初始化方向   --》往右
    direction = 'right'
    # 定义一个方向变量(人为控制  按键)
    changeDirection = direction
    bgm = pygame.mixer.music.load('public/music/backGroundMusic.mp3')
    eat = pygame.mixer.Sound('public/music/eat.wav')
    # death = pygame.mixer.Sound('public/music/death.wav')
    pygame.mixer.music.play()
    while True:

        for event in pygame.event.get():  # 从队列中获取事件
            if event.type == QUIT:
                pygame.quit()
                sys.exit()
            elif event.type == KEYDOWN:
                # 通过shift为蛇加速
                if event.key == K_RSHIFT:
                    fps = len(snakeBody)
                    print(fps)
                if event.key == K_d:
                    changeDirection = 'right'
                if event.key == K_a:
                    changeDirection = 'left'
                if event.key == K_w:
                    changeDirection = 'up'
                if event.key == K_s:
                    changeDirection = 'down'
                    # 对应键盘上的esc文件
                if event.key == K_ESCAPE:
                    pygame.event.post(pygame.event.Event(QUIT))
            # 通过shift键盘抬起事件将蛇的速度还原
            elif event.type == KEYUP:
                if event.key == K_RSHIFT:
                    fps = len(snakeBody) / 2
                    print(fps)

        # 确定方向
        if changeDirection =='left' and not direction =='right':
            direction = changeDirection
        if changeDirection =='right' and not direction =='left':
            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
        # 增加蛇的长度
        snakeBody.insert(0 ,list(snakePosition))
        # 如果贪吃蛇和目标方块的位置重合
        if snakePosition[0] == targetPosition[0] and snakePosition[1] ==targetPosition[1]:
            # 播放吃豆子的音效
            eat.play()
            targetflag= 0
        else:
            snakeBody.pop()
        if targetflag ==0:
            x = random.randrange(1 ,32)
            y = random.randrange(1 ,24)
            targetPosition = [int( x *20) ,int( y *20)]
            targetflag =1
            # 结束吃豆子的音效
            # eat.stop()
        # 填充背景颜色
        playsurface.fill(blackColor)
        for position in snakeBody:
            # 第一个参数serface指定一个serface编辑区,在这个区域内绘制
            # 第二个参数color:颜色
            # 第三个参数:rect:返回一个矩形(xy),(width,height)
            # 第四个参数:width:表示线条的粗细  width0填充  实心
            # 画蛇
            pygame.draw.rect(playsurface, redColor, Rect(position[0], position[1], 20, 20))
            pygame.draw.rect(playsurface, whiteColor, Rect(targetPosition[0], targetPosition[1], 20, 20))

        # 更新显示到屏幕表面
        pygame.display.flip()
        # 判断是否游戏结束
        if snakePosition[0] > 620 or snakePosition[0] < 0:
            # pygame.mixer.music.stop()
            # death.play()
            gameover()
        elif snakePosition[1] > 460 or snakePosition[1] < 0:
            # pygame.mixer.music.stop()
            # death.play()
            gameover()
        # 控制游戏速度
        # 根据蛇的长度控制蛇的速度越来越快
        fps = len(snakeBody) / 2
        fpsClock.tick(fps)


#   启动入口函数
if __name__ == '__main__':
    main()
最后 感谢王老师的指点

猜你喜欢

转载自blog.csdn.net/weixin_44173818/article/details/106740341