1.前言

记得小时候的六一儿童节,老师会给我们发水果,颁发表扬状,然后送我们去挤公园。但随着年龄的增长,我们离经叛道的思想也渐渐地显露出来,开始追逐更具人格魅力的追求。于是,现在的我们就成了,一群热爱编程,追求科技潮流的程序员。既然是六一儿童节,我们怎么能落下一份程序的儿童节礼物呢?

2.准备 

我们现展示一下效果图

六一儿童节python源码_cocos2d

 

六一儿童节python源码_六一儿童节python源码_02

 我们先下载代码包,代码包里包含了图片和音乐。解压后文件结果应该如下

六一儿童节python源码_python_03

我们代码需要先安装一些第三方库,其每个库的作用如下

 


作用

random

随机数支持

time

提供程序暂停

pygame

提供音乐播放

pyglet

读取图片

cocos

菜单,粒子动画

其中pygame和cocos需要另外安装。我们先windows键+R,打开终端。

终端输入安装pygame

pip install pygame

终端输入安装cocos2d

pip install cocos2d

终端输入安装pyglet

pip install pyglet

最后我们终端输入。来检测安装成功了吗。失败的可以自行百度。

pip list

3.开始写代码

我们先导入相关模块。

from random import randint
from time import sleep

import pygame
from pygame import init
from pygame.mixer import music
from cocos.menu import *
from cocos.director import director
from cocos.scene import Scene
from cocos.actions import *
from cocos.layer import Layer
from cocos.text import Label
from cocos.particle_systems import *
from cocos.sprite import Sprite
from cocos.scenes import *
from pyglet.gl import *
from pyglet import resource
from pyglet.image import Animation

接着我们定义播放音乐的模块

class Music:
    def __init__(self):
        init()

        try:
            music.load("六一快乐.mp3")
        except:
            print("cannot find mp3")

    def play(self):
        music.play()

直接我们来自定义粒子动画(其中的参数可以自己改)

class MySpiral(Spiral):
    def __init__(self):
        super().__init__()

        self.total_particles = randint(300, 500)
        self.size = randint(7, 12)
        self.duration = randint(13, 20)
        self.position = (randint(100, 750), randint(100, 550))


class MyFlower(Flower):
    def __init__(self):
        super().__init__()

        self.total_particles = randint(300, 500)
        self.size = randint(12, 18)
        self.duration = randint(13, 20)
        self.position = (randint(50, 750), randint(50, 550))


class MyFlowerworks(Fireworks):
    def __init__(self):
        super().__init__()

        self.total_particles = randint(300, 500)
        self.size = randint(7, 12)
        self.duration = randint(13, 20)
        self.position = (randint(50, 750), 50)


class MyExplosion(Explosion):
    def __init__(self):
        super().__init__()

        self.total_particles = randint(300, 500)
        self.size = randint(7, 12)
        self.duration = randint(13, 20)
        self.position = (randint(50, 750), randint(50, 550))

然后我们定义背景层(可以自己使用其他的图片做背景)

class BackgroundLayer(Layer):
    def __init__(self):
        super().__init__()

        try:
            self.images = [resource.image("background1.png"),
                           resource.image("background2.png"),
                           resource.image("background3.png")]
        except:
            print("cannot find background image!")
        else:
            self.image = Animation.from_image_sequence(self.images, 2)

        self.idx = randint(0, 2)

    def draw(self):
        glPushMatrix()
        self.transform()
        self.images[self.idx].blit(0, 0)
        glPopMatrix()

接着我们定义菜单层(可以自己调整提示语)

class MenuLayer(Menu):
    def __init__(self):
        super().__init__("六一快乐")

        self.music = Music()
        music.play()

        self.time = 0

        self.font_title["font_size"] = 64
        self.font_title["color"] = (255, 128, 255, 255)

        self.menu_halign = CENTER
        self.menu_valign = CENTER

        self.items = []
        self.items.append(MenuItem("Start", self.on_stats))

        self.create_menu(self.items, shake(), shake_back())

        self.schedule(self.update)

    def on_stats(self):
        director.push(MainScene())

    def update(self, dt):
        self.time += dt

        if self.time >= 15.0:
            director.push(MainScene())

接着我们实例化菜单场景

class MenuScene(Scene):
    def __init__(self):
        super().__init__()

        self.add(MenuLayer(), z=1)
        self.add(BackgroundLayer(), z=-1)

接着我们要定义动画层(可以自己调整各种参数)

class MainLayer(Layer):
    is_event_handler = True

    def __init__(self):
        super().__init__()

        self.texts = [list("祝各位六一快乐!"), list("让我们一起欢庆吧!!")]
        self.idx1, self.idx2 = 0, 0
        self.new_text = ["", ""]

        try:
            self.text1 = Label(text=self.new_text[0],
                               font_size=64,
                               font_name="Kristen ITC",
                               color=(255, 128, 255, 255),
                               anchor_x="center",
                               anchor_y="center", )
        except:
            print("cannot find font file!")
        else:
            self.text1.position = (400, 450)
            self.text1.do(reversed(RotateBy(20, 1.5)) +
                          spawn(Repeat(RotateBy(40, 1.5) + reversed(RotateBy(40, 1.5))),
                                ScaleBy(1.25) + reversed(ScaleBy(1.25))))
            self.add(self.text1, z=0)

        try:
            self.text2 = Label(text=self.new_text[1],
                               font_size=64,
                               font_name="Kristen ITC",
                               color=(255, 128, 255, 255),
                               anchor_x="center",
                               anchor_y="center", )
        except:
            print("cannot find font file!")
        else:
            self.text2.position = (400, 300)
            self.text2.do(reversed(RotateBy(20, 1.5)) +
                          spawn(Repeat(RotateBy(40, 1.5) + reversed(RotateBy(40, 1.5))),
                                ScaleBy(1.25) + reversed(ScaleBy(1.25))))
            self.add(self.text2, z=0)

        self.background = Sprite(BackgroundLayer().image)
        self.background.position = (400, 300)
        self.add(self.background, z=-1)

        for i in range(randint(15, 21)):
            self.systems = [MyFlower(), MyFlowerworks(), MyExplosion()]
            for j in range(randint(1, 3)):
                self.add(self.systems[randint(0, 2)], z=randint(3, 8))
        self.add(MySpiral())

        self.time1 = 0
        self.time2 = 0

        self.schedule(self.update_systems)
        self.schedule(self.update_text)

    def update_text(self, dt):
        self.time1 += dt

        if self.time1 >= 1.0:
            if self.idx1 <= len(self.texts[0]) - 1:
                self.new_text[0] += self.texts[0][self.idx1]
                self.text1.element.text = self.new_text[0]
                self.idx1 += 1

            if self.idx2 <= len(self.texts[1]) - 1 and self.idx1 >= 8:
                self.new_text[1] += self.texts[1][self.idx2]
                self.text2.element.text = self.new_text[1]
                self.idx2 += 1
            self.time1 = 0

    def update_systems(self, dt):
        self.time2 += dt

        if self.time2 >= randint(15, 20):
            for i in range(randint(15, 21)):
                self.systems = [MyFlower(), MyFlowerworks(), MyExplosion()]
                for j in range(randint(1, 3)):
                    self.add(self.systems[randint(0, 2)], z=randint(3, 8))
                    self.time2 = 0
            self.add(MySpiral())

我们接着实例化动画场景。

class MainScene(Scene):
    def __init__(self):
        super().__init__()

        self.add(MainLayer(), z=2)
        self.add(BackgroundLayer(), z=0)

最后我们创建窗口,运行场景

if __name__ == '__main__':
    director.init(resizable=True, caption="六一快乐",
                  width=800, height=600)
    director.run(MenuScene())

4.完整代码

最后展示一下完整代码

from random import randint
from time import sleep

import pygame
from pygame import init
from pygame.mixer import music
from cocos.menu import *
from cocos.director import director
from cocos.scene import Scene
from cocos.actions import *
from cocos.layer import Layer
from cocos.text import Label
from cocos.particle_systems import *
from cocos.sprite import Sprite
from cocos.scenes import *
from pyglet.gl import *
from pyglet import resource
from pyglet.image import Animation


class Music:
    def __init__(self):
        init()

        try:
            music.load("六一快乐.mp3")
        except:
            print("cannot find mp3")

    def play(self):
        music.play()


class MySpiral(Spiral):
    def __init__(self):
        super().__init__()

        self.total_particles = randint(300, 500)
        self.size = randint(7, 12)
        self.duration = randint(13, 20)
        self.position = (randint(100, 750), randint(100, 550))


class MyFlower(Flower):
    def __init__(self):
        super().__init__()

        self.total_particles = randint(300, 500)
        self.size = randint(12, 18)
        self.duration = randint(13, 20)
        self.position = (randint(50, 750), randint(50, 550))


class MyFlowerworks(Fireworks):
    def __init__(self):
        super().__init__()

        self.total_particles = randint(300, 500)
        self.size = randint(7, 12)
        self.duration = randint(13, 20)
        self.position = (randint(50, 750), 50)


class MyExplosion(Explosion):
    def __init__(self):
        super().__init__()

        self.total_particles = randint(300, 500)
        self.size = randint(7, 12)
        self.duration = randint(13, 20)
        self.position = (randint(50, 750), randint(50, 550))


class BackgroundLayer(Layer):
    def __init__(self):
        super().__init__()

        try:
            self.images = [resource.image("background1.png"),
                           resource.image("background2.png"),
                           resource.image("background3.png")]
        except:
            print("cannot find background image!")
        else:
            self.image = Animation.from_image_sequence(self.images, 2)

        self.idx = randint(0, 2)

    def draw(self):
        glPushMatrix()
        self.transform()
        self.images[self.idx].blit(0, 0)
        glPopMatrix()


class MenuLayer(Menu):
    def __init__(self):
        super().__init__("六一快乐")

        self.music = Music()
        music.play()

        self.time = 0

        self.font_title["font_size"] = 64
        self.font_title["color"] = (255, 128, 255, 255)

        self.menu_halign = CENTER
        self.menu_valign = CENTER

        self.items = []
        self.items.append(MenuItem("Start", self.on_stats))

        self.create_menu(self.items, shake(), shake_back())

        self.schedule(self.update)

    def on_stats(self):
        director.push(MainScene())

    def update(self, dt):
        self.time += dt

        if self.time >= 15.0:
            director.push(MainScene())


class MenuScene(Scene):
    def __init__(self):
        super().__init__()

        self.add(MenuLayer(), z=1)
        self.add(BackgroundLayer(), z=-1)


class MainLayer(Layer):
    is_event_handler = True

    def __init__(self):
        super().__init__()

        self.texts = [list("祝各位六一快乐!"), list("让我们一起欢庆吧!!")]
        self.idx1, self.idx2 = 0, 0
        self.new_text = ["", ""]

        try:
            self.text1 = Label(text=self.new_text[0],
                               font_size=64,
                               font_name="Kristen ITC",
                               color=(255, 128, 255, 255),
                               anchor_x="center",
                               anchor_y="center", )
        except:
            print("cannot find font file!")
        else:
            self.text1.position = (400, 450)
            self.text1.do(reversed(RotateBy(20, 1.5)) +
                          spawn(Repeat(RotateBy(40, 1.5) + reversed(RotateBy(40, 1.5))),
                                ScaleBy(1.25) + reversed(ScaleBy(1.25))))
            self.add(self.text1, z=0)

        try:
            self.text2 = Label(text=self.new_text[1],
                               font_size=64,
                               font_name="Kristen ITC",
                               color=(255, 128, 255, 255),
                               anchor_x="center",
                               anchor_y="center", )
        except:
            print("cannot find font file!")
        else:
            self.text2.position = (400, 300)
            self.text2.do(reversed(RotateBy(20, 1.5)) +
                          spawn(Repeat(RotateBy(40, 1.5) + reversed(RotateBy(40, 1.5))),
                                ScaleBy(1.25) + reversed(ScaleBy(1.25))))
            self.add(self.text2, z=0)

        self.background = Sprite(BackgroundLayer().image)
        self.background.position = (400, 300)
        self.add(self.background, z=-1)

        for i in range(randint(15, 21)):
            self.systems = [MyFlower(), MyFlowerworks(), MyExplosion()]
            for j in range(randint(1, 3)):
                self.add(self.systems[randint(0, 2)], z=randint(3, 8))
        self.add(MySpiral())

        self.time1 = 0
        self.time2 = 0

        self.schedule(self.update_systems)
        self.schedule(self.update_text)

    def update_text(self, dt):
        self.time1 += dt

        if self.time1 >= 1.0:
            if self.idx1 <= len(self.texts[0]) - 1:
                self.new_text[0] += self.texts[0][self.idx1]
                self.text1.element.text = self.new_text[0]
                self.idx1 += 1

            if self.idx2 <= len(self.texts[1]) - 1 and self.idx1 >= 8:
                self.new_text[1] += self.texts[1][self.idx2]
                self.text2.element.text = self.new_text[1]
                self.idx2 += 1
            self.time1 = 0

    def update_systems(self, dt):
        self.time2 += dt

        if self.time2 >= randint(15, 20):
            for i in range(randint(15, 21)):
                self.systems = [MyFlower(), MyFlowerworks(), MyExplosion()]
                for j in range(randint(1, 3)):
                    self.add(self.systems[randint(0, 2)], z=randint(3, 8))
                    self.time2 = 0
            self.add(MySpiral())


class MainScene(Scene):
    def __init__(self):
        super().__init__()

        self.add(MainLayer(), z=2)
        self.add(BackgroundLayer(), z=0)


if __name__ == '__main__':
    director.init(resizable=True, caption="六一快乐",
                  width=800, height=600)
    director.run(MenuScene())

 5.结语

怎么样?一口气写了200多行代码。快去惊艳全场吧!

本人是个新手,如有用词不当请谅解