Cocos2d python

家族

概念:

1导演

2场景

3层

4精灵

5菜单

标签的锚点:

坐标

层级结构:节点的层次结构--Node,可通过add添加

例子:

import cocos

class hello(cocos.layer.Layer):
    def __init__(self):
        super(hello, self).__init__()
        # 创建标签!!!!!!!
        label = cocos.text.Label('Hello',
                                 font_name='Times New Roman',
                                 font_size=32,
                                 anchor_x='center', anchor_y='center')
        # 获得导演窗口的宽度和高度,是一个二元组
        width, height = cocos.director.director.get_window_size()
        # 设置标签的位置
        label.position = width // 2, height // 2  #    //整数除法 去掉小数部分
        # 添加标签到HelloWorld层
        self.add(label)

if __name__=='__main__':
    #初始化导演
    cocos.director.director.init(width=640,height=480,caption="hello world")
    #创建层   的实例
    layer=hello()
    #创建场景   添加层进来
    main_scence=cocos.scene.Scene(layer)
    #启动场景
    cocos.director.director.run(main_scence)

结果:

 

 

菜单:

 

例子:

import cocos
#自定义菜单类
class main_menu(cocos.menu.Menu):
    def __init__(self):
        super(main_menu, self).__init__()
        #文本菜单项  (文字,回掉函数)
        item1=cocos.menu.MenuItem('开始',self.item1_callback)
        # 开关菜单项  (文字,回掉函数,状态)
        item2 = cocos.menu.ToggleMenuItem('音效', self.item2_callback,False)
        #创建菜单(添加项的列表,选中效果,未选中效果)
        self.create_menu([item1,item2],
                         selected_effect=cocos.menu.shake(),
                         unselected_effect=cocos.menu.shake_back(),
                                    )

        #改变字体
        self.font_item['font_size']=22
        #选中时
        self.font_item_selected['font_size']=33


    def item1_callback(self):
        print('item1')
    def item2_callback(self,value):
        print('item2')
if __name__=='__main__':
    #初始化导演
    cocos.director.director.init(width=640,height=480,caption="hello world")
    #创建层   的实例
    mainmenu=main_menu()
    #创建场景   添加层进来
    main_scence=cocos.scene.Scene(mainmenu)
    #启动场景
    cocos.director.director.run(main_scence)

结果:

图片菜单

import cocos


#背景层
class Game_BG(cocos.layer.Layer):
    def __init__(self):
        super(Game_BG,self).__init__()
        d_width, d_height = cocos.director.director.get_window_size()
        # 创建背景精灵
        background = cocos.sprite.Sprite('images/bg.jpg')
        background.position = d_width // 2, d_height // 2
        self.add(background)


#自定义菜单类
class main_menu(cocos.menu.Menu):
    def __init__(self):
        super(main_menu, self).__init__()

        # 也可以改变图片项的大小
        # 改变字体
        self.font_item['font_size'] = 66
        # 选中时
        self.font_item_selected['font_size'] = 66
        #改变颜色 rgba
        self.font_item['color'] = (255,255,255,25)
        # 选中时
        self.font_item_selected['color'] = (25,255,255,255)

        menu_start=cocos.menu.ImageMenuItem('images/start-up.png',self.menu_start_callback)
        menu_setting= cocos.menu.ImageMenuItem('images/setting-up.png', self.menu_setting_callback)
        help_setting = cocos.menu.ImageMenuItem('images/help-up.png', self.menu_help_callback)
        #创建菜单(添加项的列表,自定义布局位置)
        self.create_menu([menu_start,menu_setting,help_setting],
                         layout_strategy=cocos.menu.fixedPositionMenuLayout([(500,339),(500,220),(500,100)]),
                         selected_effect=cocos.menu.zoom_in(),
                         unselected_effect=cocos.menu.zoom_out())


    def menu_start_callback(self):
        pass
    def menu_help_callback(self):
        pass
    def menu_setting_callback(self):
        pass
if __name__=='__main__':
    #初始化导演
    cocos.director.director.init(width=640,height=480,caption="dog and cat")


    #将背景层  添加到场景
    bg=Game_BG()
    main_scence=cocos.scene.Scene(bg)
    #添加菜单
    mainmenu=main_menu()
    main_scence.add(mainmenu)
    #启动场景
    cocos.director.director.run(main_scence)

键盘事件

 

import cocos
import pyglet


# 背景层
class la(cocos.layer.Layer):
    def __init__(self):
        super(la, self).__init__()
        # 开启事件处理层 有事件发生 就要写
        # !!!!!!!!!!!!!!!!!!!!
        cocos.layer.Layer.is_event_handler = True

        self.label = cocos.text.Label('Hello',
                                      font_name='Times New Roman',
                                      font_size=32,
                                      anchor_x='center', anchor_y='center')
        # 获得导演窗口的宽度和高度,是一个二元组
        width, height = cocos.director.director.get_window_size()
        # 设置标签的位置
        self.label.position = width // 2, height // 2  # //整数除法 去掉小数部分
        # 添加标签到HelloWorld层
        self.add(self.label)

    def on_key_press(self, ke, modifiiers):#修改方法

        if ke == pyglet.window.key.SPACE:# 空格键
            self.label.element.text = '空格键按下'

    def on_key_release(self, ke, modifiiers):
        if ke == pyglet.window.key.SPACE:
            self.label.element.text = '空格键势放'


if __name__ == '__main__':
    # 初始化导演
    cocos.director.director.init(width=640, height=480, caption="dog and cat")

    lay = la()
    main_scence = cocos.scene.Scene(lay)
    # 添加菜单

    # 启动场景
    cocos.director.director.run(main_scence)

鼠标事件

import cocos
import pyglet


# 背景层
class la(cocos.layer.Layer):
    def __init__(self):
        super(la, self).__init__()
        # 开启事件处理层
        # !!!!!!!!!!!!!!!!!!!!
        cocos.layer.Layer.is_event_handler = True

        self.label = cocos.text.Label('Hello',
                                      font_name='Times New Roman',
                                      font_size=32,
                                      anchor_x='center', anchor_y='center')
        # 获得导演窗口的宽度和高度,是一个二元组
        width, height = cocos.director.director.get_window_size()
        # 设置标签的位置
        self.label.position = width // 2, height // 2  # //整数除法 去掉小数部分
        # 添加标签到HelloWorld层
        self.add(self.label)

    def on_mouse_press(self, x,y,button, modifiiers):
        if button==pyglet.window.mouse.LEFT:
            self.label.element.text='鼠标左键按下'

    def on_mouse_release(self, x, y, button, modifiiers):
        if button == pyglet.window.mouse.LEFT:
            self.label.element.text = '鼠标左键释放'
    def on_mouse_drag(self, x, y, dx,dy,button, modifiiers):
        #使用modifiiers
        if modifiiers & pyglet.window.key.MOD_CTRL:
            self.label.element.text = 'ctrl+鼠标左键拖拽'

if __name__ == '__main__':
    # 初始化导演
    cocos.director.director.init(width=640, height=480, caption="dog and cat")

    lay = la()
    main_scence = cocos.scene.Scene(lay)
    # 添加菜单

    # 启动场景
    cocos.director.director.run(main_scence)

 

精灵

 

import cocos
import pyglet


# 背景层
class la(cocos.layer.Layer):
    def __init__(self):
        super(la, self).__init__()
        #获得尺寸
        self.width,self.height=cocos.director.director.get_window_size()
        #背景精灵
        background=cocos.sprite.Sprite('images/background.png')
        background.position=self.width//2,self.height//2
        self.add(background,z=-1)#z=前后顺序 小的往屏里
        #山
        mountain1=cocos.sprite.Sprite('images/mountain1.png',position=(360,500),scale=0.6)#scale缩放
        self.add(mountain1,1)
        mountain2 = cocos.sprite.Sprite('images/mountain2.png', position=(800, 500), scale=0.6)  # scale缩放
        self.add(mountain2,1)
        #hero
        hero = cocos.sprite.Sprite('images/hero.png', position=(800, 160), scale=0.6)  # scale缩放
        self.add(hero, 2)
if __name__ == '__main__':
    # 初始化导演
    cocos.director.director.init(width=1024, height=680, caption="hero")

    lay = la()
    main_scence = cocos.scene.Scene(lay)
    # 添加菜单

    # 启动场景
    cocos.director.director.run(main_scence)

效果:

场景切换

过度动画

 

 

open.py

import cocos
from cocos.scenes.transitions import *

import setting_sence
#背景层
class Game_BG(cocos.layer.Layer):
    def __init__(self):
        super(Game_BG,self).__init__()
        d_width, d_height = cocos.director.director.get_window_size()
        # 创建背景精灵
        background = cocos.sprite.Sprite('images/bg.jpg')
        background.position = d_width // 2, d_height // 2
        self.add(background)


#自定义菜单类
class main_menu(cocos.menu.Menu):
    def __init__(self):
        super(main_menu, self).__init__()

        # 也可以改变图片项的大小
        # 改变字体
        self.font_item['font_size'] = 66
        # 选中时
        self.font_item_selected['font_size'] = 66
        #改变颜色 rgba
        self.font_item['color'] = (255,255,255,25)
        # 选中时
        self.font_item_selected['color'] = (215,255,255,255)

        menu_start=cocos.menu.ImageMenuItem('images/start-up.png',self.menu_start_callback)
        menu_setting= cocos.menu.ImageMenuItem('images/setting-up.png', self.menu_setting_callback)
        help_setting = cocos.menu.ImageMenuItem('images/help-up.png', self.menu_help_callback)
        #创建菜单(添加项的列表,自定义布局位置)
        self.create_menu([menu_start,menu_setting,help_setting],
                         layout_strategy=cocos.menu.fixedPositionMenuLayout([(500,339),(500,220),(500,100)]),
                         selected_effect=cocos.menu.zoom_in(),
                         unselected_effect=cocos.menu.zoom_out())


    def menu_start_callback(self):
        pass
    def menu_help_callback(self):
        pass
    def menu_setting_callback(self):
        set_sence=setting_sence.create()

        donghua=RotoZoomTransition(set_sence,1.5)#  导包!!

        cocos.director.director.push(donghua)

if __name__=='__main__':
    #初始化导演
    cocos.director.director.init(width=640,height=480,caption="dog and cat")
    #将背景层  添加到场景
    bg=Game_BG()
    main_scence=cocos.scene.Scene(bg)
    #添加菜单
    mainmenu=main_menu()
    main_scence.add(mainmenu)
    #启动场景
    cocos.director.director.run(main_scence)
setting_sence.py
import cocos


#背景层
class Game_Setting(cocos.layer.Layer):
    def __init__(self):
        super(Game_Setting,self).__init__()
        d_width, d_height = cocos.director.director.get_window_size()
        # 创建背景精灵
        background = cocos.sprite.Sprite('images/bg.jpg')
        background.position = d_width // 2, d_height // 2
        self.add(background)


#自定义菜单类
class main_menu(cocos.menu.Menu):
    def __init__(self):
        super(main_menu, self).__init__()

        # 也可以改变图片项的大小
        # 改变字体
        self.font_item['font_size'] = 66
        # 选中时
        self.font_item_selected['font_size'] = 66
        #改变颜色 rgba
        self.font_item['color'] = (255,255,255,25)
        # 选中时
        self.font_item_selected['color'] = (215,255,255,255)

        ok = cocos.menu.ImageMenuItem('images/start-up.png', self.ok_callback)
        #创建菜单(添加项的列表,自定义布局位置)
        self.create_menu([ok],
                         layout_strategy=cocos.menu.fixedPositionMenuLayout([(560,130)]),
                         selected_effect=cocos.menu.zoom_in(),
                         unselected_effect=cocos.menu.zoom_out())


    def ok_callback(self):
        cocos.director.director.pop()

def create():
    #将背景层  添加到场景
    bg=Game_Setting()
    main_scence=cocos.scene.Scene(bg)
    #添加菜单
    mainmenu=main_menu()
    main_scence.add(mainmenu)
    return main_scence

动作

 

import cocos

hero = None  # 作为全局变量


class BG(cocos.layer.ColorLayer):  # 可设置颜色的层
    def __init__(self):
        global hero
        super(BG, self).__init__(255, 255, 255, 255)  # 白色的层
        hero = cocos.sprite.Sprite('images/hero.png')
        hero.position = 530, 320
        self.add(hero)


class my_menu(cocos.menu.Menu):
    def __init__(self):
        super(my_menu, self).__init__()

        self.font_item['font_size'] = 11
        self.font_item['color'] = (0, 0, 0, 255)
        self.font_item_selected['font_size'] = 20
        self.font_item_selected['color'] = (255, 74, 62, 255)

        item1 = cocos.menu.MenuItem('Hide', self.menu_callback1)
        item2 = cocos.menu.MenuItem('Show', self.menu_callback2)
        item3 = cocos.menu.MenuItem('ToggleVisibility', self.menu_callback3)
        item4 = cocos.menu.MenuItem('Place', self.menu_callback4)

        x = 120
        y = 360
        step = 60
        self.create_menu([item1, item2, item3, item4],
                         layout_strategy=cocos.menu.fixedPositionMenuLayout(
                             [(x, y),
                              (x, y - step),
                              (x, y - 2 * step),
                              (x, y - 3 * step)
                              ]))

    def menu_callback1(self):
        hero.do(cocos.actions.Hide())

    def menu_callback2(self):
        hero.do(cocos.actions.Show())

    def menu_callback3(self):
        hero.do(cocos.actions.ToggleVisibility())#交替的隐藏 出现

    def menu_callback4(self):
        hero.do(cocos.actions.Place((700,400)))#移动位置


if __name__ == '__main__':
    # 初始化导演
    cocos.director.director.init(width=1024, height=680, caption="动作")
    # 将背景层  添加到场景
    bg = BG()
    main_scence = cocos.scene.Scene(bg)
    # 添加菜单
    mainmenu = my_menu()
    main_scence.add(mainmenu)
    # 启动场景
    cocos.director.director.run(main_scence)

间隔动作:by相对移动   to绝对移动

import cocos
from cocos.menu import *

hero = None  # 作为全局变量


class BG(cocos.layer.ColorLayer):  # 可设置颜色的层
    def __init__(self):
        global hero
        super(BG, self).__init__(255, 255, 255, 255)  # 白色的层
        hero = cocos.sprite.Sprite('images/hero.png')
        hero.position = 530, 320
        self.add(hero)


class my_menu(cocos.menu.Menu):
    def __init__(self):
        super(my_menu, self).__init__()
        # 菜单项初始化设置
        self.font_item['font_size'] = 20
        self.font_item['color'] = (0, 0, 0, 255)
        self.font_item_selected['color'] = (0, 0, 0, 255)
        self.font_item_selected['font_size'] = 26

        item1 = MenuItem('MoveBy', self.menu_callback1)
        item2 = MenuItem('MoveTo', self.menu_callback2)
        item3 = MenuItem('JumpBy', self.menu_callback3)
        item4 = MenuItem('JumpTo', self.menu_callback4)
        item5 = MenuItem('ScaleBy', self.menu_callback5)
        item6 = MenuItem('ScaleTo', self.menu_callback6)
        item7 = MenuItem('RotateBy', self.menu_callback7)
        item8 = MenuItem('RotateTo', self.menu_callback8)
        item9 = MenuItem('FadeTo', self.menu_callback9)
        item10 = MenuItem('FadeIn', self.menu_callback10)
        item11 = MenuItem('FadeOut', self.menu_callback11)

        x = 120
        y = 560
        step = 45

        self.create_menu(
            [item1, item2, item3, item4, item5, item6, item7, item8, item9, item10, item11],
            layout_strategy=fixedPositionMenuLayout(
                [(x, y), (x, y - step), (x, y - 2 * step), (x, y - 3 * step), (x, y - 4 * step),
                 (x, y - 5 * step), (x, y - 6 * step), (x, y - 7 * step), (x, y - 8 * step),
                 (x, y - 9 * step), (x, y - 10 * step)]))

    def menu_callback1(self):
        hero.do(cocos.actions.MoveBy((100,100),duration=2))#位置 duration执行时间

    def menu_callback2(self):
        hero.do(cocos.actions.MoveTo((200,200),duration=2))

    def menu_callback3(self):
        hero.do(cocos.actions.JumpBy((100, 200), duration=2))  #跳

    def menu_callback4(self):
        hero.do(cocos.actions.JumpTo((200, 200), duration=2))
    def menu_callback5(self):
        hero.do(cocos.actions.ScaleBy(0.5,duration=2))  #缩放
    def menu_callback6(self):
        hero.do(cocos.actions.ScaleTo(2,duration=2))

    def menu_callback7(self):
        hero.do(cocos.actions.RotateBy(180,duration=2))#旋转角度
    def menu_callback8(self):
        hero.do(cocos.actions.RotateTo(20,duration=2))

    def menu_callback9(self):
        hero.do(cocos.actions.FadeTo(80,2))#80%透明 两秒钟
    def menu_callback10(self):
        hero.do(cocos.actions.FadeIn(2))  #渐入
    def menu_callback11(self):
        hero.do(cocos.actions.FadeOut(2))#淡出

if __name__ == '__main__':
    # 初始化导演
    cocos.director.director.init(width=1024, height=680, caption="动作")
    # 将背景层  添加到场景
    bg = BG()
    main_scence = cocos.scene.Scene(bg)
    # 添加菜单
    mainmenu = my_menu()
    main_scence.add(mainmenu)
    # 启动场景
    cocos.director.director.run(main_scence)

 

组合动作

粒子系统:

 

系统预定义的粒子系统

import cocos
from cocos.menu import *
from cocos.particle_systems import *
import time

lizi = None  # 作为全局变量


class GameLayer(cocos.layer.Layer):

    def __init__(self):
        super(GameLayer, self).__init__()
        # 创建初始的粒子系统
        lizi = Spiral() 
        lizi.position = 560, 320
        self.add(lizi, name='particle')





class my_menu(cocos.menu.Menu):


    def __init__(self):
        super(my_menu, self).__init__()
        # 菜单项初始化设置
        self.font_item['font_size'] = 20
        self.font_item_selected['font_size'] = 26

        item1 = MenuItem('Fireworks', self.menu_callback1)


        x = 120
        y = 560
        step = 45

        self.create_menu(
            [item1],
            layout_strategy=fixedPositionMenuLayout(
                [(x, y)]))

    def menu_callback1(self):
        bg.remove('particle' )  #使用name移除已有的粒子
        lizi=Fireworks()   #粒子模式设置
        lizi.total_particles=200 #设置属性
        lizi.speed=800  #设置属性
        lizi.position = 560, 320
        bg.add(lizi, name='particle')





if __name__ == '__main__':
    # 初始化导演
    cocos.director.director.init(width=1024, height=680, caption="动作")
    # 将背景层  添加到场景
    bg = GameLayer()
    main_scence = cocos.scene.Scene(bg)
    # 添加菜单
    mainmenu = my_menu()
    main_scence.add(mainmenu)
    # 启动场景
    cocos.director.director.run(main_scence)

 

打火机

# coding=utf-8
# Created by 智捷关东升
# 本书网站:www.zhijieketang.com/group/8
# 智捷课堂在线课堂:www.zhijieketang.com
# 智捷课堂微信公共号:zhijieketang
# 邮箱:eorient@sina.com
# 读者服务QQ群:628808216
# 【配套电子书】网址:
#       百度阅读:
#       https://yuedu.baidu.com/ebook/5823871e59fafab069dc5022aaea998fcc2240fc
# 代码文件:chapter21/21.8.4/ch21.8.4.py

from cocos.euclid import Point2
from cocos.sprite import *
from cocos.scene import *
from cocos.layer import *
from cocos.particle_systems import *
from cocos.director import *

# 自定义GameLayer层类
class GameLayer(Layer):

    def __init__(self):
        super(GameLayer, self).__init__()
        # 获得窗口的宽度和高度
        s_width, s_height = director.get_window_size()

        # 创建背景精灵
        background = Sprite('images/zippo.png')
        background.position = s_width // 2, s_height // 2
        # 添加背景精灵
        self.add(background, 0)

        ps = Fire()
        ps.gravity = Point2(45, 600) #x,y轴重力加速度  x正值为右边  y正值为上
        ps.radial_accel = 60
        ps.size = 220
        ps.size_var = 50
        ps.tangential_accel = 20
        ps.tangential_accel_var = 10
        ps.life = 0.99
        ps.life_var = 0.45
        ps.emission_rate = 200
        ps.position = 270, 580

        self.add(ps)


if __name__ == '__main__':
    # 初始化导演,设置窗口的高、宽、标题
    director.init(width=640, height=960, resizable=True, caption='粒子系统示例')

    # 创建主场景,并添加GameLayer对象到主场景
    main_scene = Scene(GameLayer())

    # 开始启动main_scene场景
    director.run(main_scene)

效果

音效

import cocos
from cocos.scenes.transitions import *
from cocos.audio.pygame import music
import setting_sence
#背景层
class Game_BG(cocos.layer.Layer):
    def __init__(self):
        super(Game_BG,self).__init__()
        d_width, d_height = cocos.director.director.get_window_size()
        # 创建背景精灵
        background = cocos.sprite.Sprite('images/bg.jpg')
        background.position = d_width // 2, d_height // 2
        self.add(background)



if __name__=='__main__':

    cocos.director.director.init(width=640,height=480,caption="dog and cat",audio_backend='sdl')#!!!!!指定背景音乐后台 sdl
    bg=Game_BG()
    main_scence=cocos.scene.Scene(bg)

    #播放背景音乐
    music.load('sound/Hop.mp3'.encode())#转为编码
    music.play(loops=-1)  #播放 循环次数
    music.set_volume(1)#声音大小

    cocos.director.director.run(main_scence)

 音效

import cocos
from cocos.scenes.transitions import *
from cocos.audio.pygame import music
from cocos.audio.effect import Effect

import setting_sence
#背景层
class Game_BG(cocos.layer.Layer):
    def __init__(self):
        super(Game_BG,self).__init__()
        d_width, d_height = cocos.director.director.get_window_size()
        # 创建背景精灵
        background = cocos.sprite.Sprite('images/bg.jpg')
        background.position = d_width // 2, d_height // 2
        self.add(background)


#自定义菜单类
class main_menu(cocos.menu.Menu):
    def __init__(self):
        super(main_menu, self).__init__()

        # 也可以改变图片项的大小
        # 改变字体
        self.font_item['font_size'] = 66
        # 选中时
        self.font_item_selected['font_size'] = 66
        #改变颜色 rgba
        self.font_item['color'] = (255,255,255,25)
        # 选中时
        self.font_item_selected['color'] = (215,255,255,255)

        menu_start=cocos.menu.ImageMenuItem('images/start-up.png',self.menu_start_callback)
        menu_setting= cocos.menu.ImageMenuItem('images/setting-up.png', self.menu_setting_callback)
        help_setting = cocos.menu.ImageMenuItem('images/help-up.png', self.menu_help_callback)
        #创建菜单(添加项的列表,自定义布局位置)
        self.create_menu([menu_start,menu_setting,help_setting],
                         layout_strategy=cocos.menu.fixedPositionMenuLayout([(500,339),(500,220),(500,100)]),
                         selected_effect=cocos.menu.zoom_in(),
                         unselected_effect=cocos.menu.zoom_out())


    def menu_start_callback(self):
        yinxiao=Effect('sound/Blip.wav') #音效
        yinxiao.play()


        pass
    def menu_help_callback(self):
        pass
    def menu_setting_callback(self):
        set_sence=setting_sence.create()

        donghua=RotoZoomTransition(set_sence,1.5)#  导包!!

        cocos.director.director.push(donghua)

if __name__=='__main__':
    #初始化导演
    cocos.director.director.init(width=640,height=480,caption="dog and cat",audio_backend='sdl')
    #将背景层  添加到场景
    bg=Game_BG()
    main_scence=cocos.scene.Scene(bg)
    #添加菜单
    mainmenu=main_menu()
    main_scence.add(mainmenu)

    # 播放背景音乐
    music.load('sound/Hop.mp3'.encode())  # 需要转为编码
    music.play(loops=-1)  # 播放 循环次数
    music.set_volume(1)  # 声音大小

    #启动场景
    cocos.director.director.run(main_scence)

 

 

 

 

 

 

 

 

 

 

展开阅读全文

没有更多推荐了,返回首页