资讯专栏INFORMATION COLUMN

【Pygame实战】嗷大喵历险记之程序员吸猫指南:真的太上头了~

dreamans / 9436人阅读

摘要:嗷大喵和他的小伙伴们快乐的生活在一起,他们总是能给大家带来欢乐。大家都说嗷大喵真棒。大家要做的就是解救嗷大喵远离恶龙。

导语

哈喽~大家好,我是木子,首先今天木子先给大家讲个小故事

在喵界有这样一只网红——混迹于二次元、表情包界,贱萌活泼,调皮机灵,白色的大圆脸,脖子

上系了个铃铛,年龄不详,传说可于儿童、少年、青年间随意切换。

他的欢乐日常带给了很多人温暖和爆笑,他的乐观积极也是很多人治疗伤心难过空虚寂寞冷综合症

的良方,他就是——嗷大喵

Ps小介绍:

嗷大喵资料:是一位开朗、乐观、热情奔放、温暖人心的喵星人。他静如瘫痪,动如癫痫,喜欢的

事情是吃和睡,他的直率和可爱还经常被人误以为是神经病呢。

嗷大喵和他的小伙伴们快乐的生活在一起,他们总是能给大家带来欢乐。大家都说:“嗷大喵真

棒!”。

...........................................................................................................................................................

介绍到这里就差不多了哈,今天要写的小游戏也跟嗷大喵有关的呢~

利用这个“网红”ip打造出一个独一无二的嗷大喵表情包小游戏给大家解解乏哦~上班摸鱼也可以.jpg

...........................................................................................................................................................

​正文

一、准备中

1.1 素材准备

背景音乐:(可修改)

图片素材:(可修改)

1.2 游戏规则

嗷大喵遇险记:嗷大喵即玩家,遭遇飞机失联,一猫?独自掉落到无人居住的荒岛,好在荒岛上

资源充足,嗷大喵一个猫生存了下来,某一天嗷大喵追赶一只奇奇怪怪的生物,跑到了一个很高的

洞口,好奇心驱使嗷大喵紧张的走进了洞穴,不料想一进洞就遇到了一只传说中的恶龙,嗷大喵吓

得只好赶紧跑出洞外——自此一直被恶龙追赶......

Over ,咳咳咳......儿童故事就听到这里吧。大家要做的就是解救嗷大喵~远离恶龙。

玩法:按住空格躲避恶龙的火焰,击中的话会减速,然后被恶龙吃掉。

二、环境安装

环境:Python3、Pycharm、Pygame以及一些自带模块。

这里模块安装命令:

pip install +模块名   或者豆瓣镜像源 pip install -i https://pypi.douban.com/simple/ +模块名

三、正式敲代码

3.1  定义开始游戏这个按钮

# -*- coding: utf-8 -*-import pygamefrom sys import exitfrom pygame.locals import *pygame.init()screen = pygame.display.set_mode((300,200),0,32)upImageFilename = "game_start_up.png"downImageFilename = "game_start_down.png"class Button(object):    def __init__(self, upimage, downimage,position):        self.imageUp = pygame.image.load(upimage).convert_alpha()        self.imageDown = pygame.image.load(downimage).convert_alpha()        self.position = position            def isOver(self):        point_x,point_y = pygame.mouse.get_pos()        x, y = self. position        w, h = self.imageUp.get_size()        in_x = x - w/2 < point_x < x + w/2        in_y = y - h/2 < point_y < y + h/2        return in_x and in_y    def render(self):        w, h = self.imageUp.get_size()        x, y = self.position                if self.isOver():            screen.blit(self.imageDown, (x-w/2,y-h/2))        else:            screen.blit(self.imageUp, (x-w/2, y-h/2))    def is_start(self):        b1,b2,b3 = pygame.mouse.get_pressed()        if b1 == 1:            return Truebutton = Button(upImageFilename,downImageFilename, (150,100))    while True:    for event in pygame.event.get():        if event.type == pygame.QUIT:            pygame.quit()            exit()    screen.fill((200, 200, 200))    button.render()    if button.is_start():        print ("start")    pygame.display.update()

3.11 附效果截图

3.2  主程序

# -*- coding: utf-8 -*-import sys, time, random, math, pygame,localefrom pygame.locals import *from MyLibrary import *#重置火箭函数def reset_arrow():    y = random.randint(270,350)    arrow.position = 800,y    bullent_sound.play_sound()#定义一个滚动地图类class MyMap(pygame.sprite.Sprite):        def __init__(self,x,y):        self.x = x        self.y = y        self.bg = pygame.image.load("background.png").convert_alpha()    def map_rolling(self):        if self.x < -600:            self.x = 600        else:            self.x -=5    def map_update(self):        screen.blit(self.bg, (self.x,self.y))    def set_pos(x,y):        self.x =x        self.y =y#定义一个按钮类class Button(object):    def __init__(self, upimage, downimage,position):        self.imageUp = pygame.image.load(upimage).convert_alpha()        self.imageDown = pygame.image.load(downimage).convert_alpha()        self.position = position        self.game_start = False            def isOver(self):        point_x,point_y = pygame.mouse.get_pos()        x, y = self. position        w, h = self.imageUp.get_size()        in_x = x - w/2 < point_x < x + w/2        in_y = y - h/2 < point_y < y + h/2        return in_x and in_y    def render(self):        w, h = self.imageUp.get_size()        x, y = self.position                if self.isOver():            screen.blit(self.imageDown, (x-w/2,y-h/2))        else:            screen.blit(self.imageUp, (x-w/2, y-h/2))    def is_start(self):        if self.isOver():            b1,b2,b3 = pygame.mouse.get_pressed()            if b1 == 1:                self.game_start = True                bg_sound.play_pause()                btn_sound.play_sound()                bg_sound.play_sound()def replay_music():    bg_sound.play_pause()    bg_sound.play_sound()#定义一个数据IO的方法def data_read():    fd_1 = open("data.txt","r")    best_score = fd_1.read()    fd_1.close()    return best_score   #定义一个控制声音的类和初始音频的方法def audio_init():    global hit_au,btn_au,bg_au,bullent_au    pygame.mixer.init()    hit_au = pygame.mixer.Sound("exlposion.wav")    btn_au = pygame.mixer.Sound("button.wav")    bg_au = pygame.mixer.Sound("background.ogg")    bullent_au = pygame.mixer.Sound("bullet.wav")class Music():    def __init__(self,sound):        self.channel = None        self.sound = sound         def play_sound(self):        self.channel = pygame.mixer.find_channel(True)        self.channel.set_volume(0.5)        self.channel.play(self.sound)    def play_pause(self):        self.channel.set_volume(0.0)        self.channel.play(self.sound)      #主程序部分pygame.init()audio_init()screen = pygame.display.set_mode((800,600),0,32)pygame.display.set_caption("嗷大喵快跑!")font = pygame.font.Font(None, 22)font1 = pygame.font.Font(None, 40)framerate = pygame.time.Clock()upImageFilename = "game_start_up.png"downImageFilename = "game_start_down.png"#创建按钮对象button = Button(upImageFilename,downImageFilename, (400,500))interface = pygame.image.load("interface.png")#创建地图对象bg1 = MyMap(0,0)bg2 = MyMap(600,0)#创建一个精灵组group = pygame.sprite.Group()group_exp = pygame.sprite.Group()group_fruit = pygame.sprite.Group()#创建怪物精灵dragon = MySprite()dragon.load("dragon.png", 260, 150, 3)dragon.position = 100, 230group.add(dragon)#创建爆炸动画explosion = MySprite()explosion.load("explosion.png",128,128,6)#创建玩家精灵player = MySprite()player.load("sprite.png", 100, 100, 4)player.position = 400, 270group.add(player)#创建子弹精灵arrow = MySprite()arrow.load("flame.png", 40, 16, 1)arrow.position = 800,320group.add(arrow)#定义一些变量arrow_vel = 10.0game_over = Falseyou_win = Falseplayer_jumping = Falsejump_vel = 0.0player_start_y = player.Yplayer_hit = Falsemonster_hit = Falsep_first = Truem_first = Truebest_score = 0global bg_sound,hit_sound,btn_sound,bullent_soundbg_sound=Music(bg_au)hit_sound=Music(hit_au)btn_sound=Music(btn_au)bullent_sound =Music(bullent_au)game_round = {1:"ROUND ONE",2:"ROUND TWO",3:"ROUND THREE",4:"ROUND FOUR",5:"ROUND FIVE"}game_pause = Trueindex =0current_time = 0start_time = 0music_time = 0score =0replay_flag = True#循环bg_sound.play_sound()best_score = data_read()while True:    framerate.tick(60)    ticks = pygame.time.get_ticks()    for event in pygame.event.get():        if event.type == pygame.QUIT:            pygame.quit()            sys.exit()    keys = pygame.key.get_pressed()    if keys[K_ESCAPE]:        pygame.quit()        sys.exit()            elif keys[K_SPACE]:        if not player_jumping:            player_jumping = True            jump_vel = -12.0                screen.blit(interface,(0,0))    button.render()    button.is_start()    if button.game_start == True:        if game_pause :            index +=1            tmp_x =0            if score >int (best_score):                best_score = score            fd_2 = open("data.txt","w+")            fd_2.write(str(best_score))            fd_2.close()            #判断游戏是否通关            if index == 6:                you_win = True            if you_win:                start_time = time.clock()                current_time =time.clock()-start_time                while current_time<5:                    screen.fill((200, 200, 200))                    print_text(font1, 270, 150,"YOU WIN THE GAME!",(240,20,20))                    current_time =time.clock()-start_time                    print_text(font1, 320, 250, "Best Score:",(120,224,22))                    print_text(font1, 370, 290, str(best_score),(255,0,0))                    print_text(font1, 270, 330, "This Game Score:",(120,224,22))                    print_text(font1, 385, 380, str(score),(255,0,0))                    pygame.display.update()                pygame.quit()                sys.exit()                            for i in range(0,100):                element = MySprite()                element.load("fruit.bmp", 75, 20, 1)                tmp_x +=random.randint(50,120)                element.X = tmp_x+300                element.Y = random.randint(80,200)                group_fruit.add(element)            start_time = time.clock()            current_time =time.clock()-start_time            while current_time<3:                screen.fill((200, 200, 200))                print_text(font1, 320, 250,game_round[index],(240,20,20))                pygame.display.update()                game_pause = False                current_time =time.clock()-start_time                    else:            #更新子弹            if not game_over:                arrow.X -= arrow_vel            if arrow.X < -40: reset_arrow()            #碰撞检测,子弹是否击中玩家            if pygame.sprite.collide_rect(arrow, player):                reset_arrow()                explosion.position =player.X,player.Y                player_hit = True                hit_sound.play_sound()                if p_first:                    group_exp.add(explosion)                    p_first = False                player.X -= 10            #碰撞检测,子弹是否击中怪物            if pygame.sprite.collide_rect(arrow, dragon):                reset_arrow()                explosion.position =dragon.X+50,dragon.Y+50                monster_hit = True                hit_sound.play_sound()                if m_first:                    group_exp.add(explosion)                    m_first = False                dragon.X -= 10            #碰撞检测,玩家是否被怪物追上            if pygame.sprite.collide_rect(player, dragon):                game_over = True            #遍历果实,使果实移动            for e in group_fruit:                e.X -=5            collide_list = pygame.sprite.spritecollide(player,group_fruit,False)            score +=len(collide_list)            #是否通过关卡            if dragon.X < -100:                game_pause = True                reset_arrow()                player.X = 400                dragon.X = 100                                        #检测玩家是否处于跳跃状态            if player_jumping:                if jump_vel <0:                    jump_vel += 0.6                elif jump_vel >= 0:                    jump_vel += 0.8                player.Y += jump_vel                if player.Y > player_start_y:                    player_jumping = False                    player.Y = player_start_y                    jump_vel = 0.0            #绘制背景            bg1.map_update()            bg2.map_update()            bg1.map_rolling()            bg2.map_rolling()                        #更新精灵组            if not game_over:                group.update(ticks, 60)                group_exp.update(ticks,60)                group_fruit.update(ticks,60)            #循环播放背景音乐            music_time = time.clock()            if music_time   > 150 and replay_flag:                replay_music()                replay_flag =False            #绘制精灵组            group.draw(screen)            group_fruit.draw(screen)            if player_hit or monster_hit:                group_exp.draw(screen)            print_text(font, 330, 560, "press SPACE to jump up!")            print_text(font, 200, 20, "You have get Score:",(219,224,22))            print_text(font1, 380, 10, str(score),(255,0,0))            if game_over:                start_time = time.clock()                current_time =time.clock()-start_time                while current_time<5:                    screen.fill((200, 200, 200))                    print_text(font1, 300, 150,"GAME OVER!",(240,20,20))                    current_time =time.clock()-start_time                    print_text(font1, 320, 250, "Best Score:",(120,224,22))                    if score >int (best_score):                        best_score = score                    print_text(font1, 370, 290, str(best_score),(255,0,0))                    print_text(font1, 270, 330, "This Game Score:",(120,224,22))                    print_text(font1, 370, 380, str(score),(255,0,0))                    pygame.display.update()                fd_2 = open("data.txt","w+")                fd_2.write(str(best_score))                fd_2.close()                pygame.quit()                sys.exit()    pygame.display.update()

四、效果展示

4.1 动态视频展示——

嗷大喵历险记~

4.2 静态截图展示——

总结

萌萌的嗷大喵能不能逃离恶龙的追击,就看你们了哈~

噗~哈哈哈 咋感觉我最近的画风有点儿不对,都是一些奇奇怪怪可可爱爱的儿童画风!

?完整的免费源码领取处:

如需完整的项目源码+素材源码基地见:#私信小编06#或者点击蓝色文字添加即可获取免费的福利!

你们的支持是我最大的动力!!记得三连哦~mua 欢迎大家阅读往期的文章哦~

?往期游戏热门文章推荐:

项目1.8  人机五子棋游戏 

Pygame实战:利用Python实现智能五子棋,实现之后发现我玩不赢它。

项目4.2  我的世界游戏

Pygame实战:方块连接世界,云游大好河山—《我的世界》已上线,确定不进来康康嘛?

项目4.4  剧情版游戏

【Python剧情版游戏】优美精致的画风甜甜的剧情、很难不让人上头啊?你get到了嘛

项目1.1   扫雷

 Pygame实战:据说这是史上最难扫雷游戏,没有之一,你们感受下......

项目1.2   魂斗罗

Pygame实战:多年后“魂斗罗”像素风归来 不止是经典与情怀@全体成员

文章汇总——

Python—2021 |已有文章汇总 | 持续更新,直接看这篇就够了

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/124496.html

相关文章

  • 首次公开,整理12年积累的博客收藏夹,零距离展示《收藏夹吃灰》系列博客

    摘要:时间永远都过得那么快,一晃从年注册,到现在已经过去了年那些被我藏在收藏夹吃灰的文章,已经太多了,是时候把他们整理一下了。那是因为收藏夹太乱,橡皮擦给设置私密了,不收拾不好看呀。 ...

    Harriet666 评论0 收藏0
  • Java开发

    摘要:大多数待遇丰厚的开发职位都要求开发者精通多线程技术并且有丰富的程序开发调试优化经验,所以线程相关的问题在面试中经常会被提到。将对象编码为字节流称之为序列化,反之将字节流重建成对象称之为反序列化。 JVM 内存溢出实例 - 实战 JVM(二) 介绍 JVM 内存溢出产生情况分析 Java - 注解详解 详细介绍 Java 注解的使用,有利于学习编译时注解 Java 程序员快速上手 Kot...

    LuDongWei 评论0 收藏0
  • 从小白序员一路晋升为大厂高级技术专家我看过哪些书籍?(建议收藏)

    摘要:大家好,我是冰河有句话叫做投资啥都不如投资自己的回报率高。马上就十一国庆假期了,给小伙伴们分享下,从小白程序员到大厂高级技术专家我看过哪些技术类书籍。 大家好,我是...

    sf_wangchong 评论0 收藏0

发表评论

0条评论

最新活动
阅读需要支付1元查看
<