Skip to content

cocos2d-python中文教程:1 Hello World #10

Open
@bieberg0n

Description

@bieberg0n
Owner

前言

相信有很多Python党像我一样,在多年的Python生涯中,编出了各种各样改善生活的小程序.突然有一天,我脑海中浮现了一个idea:为什么不用Python写一个游戏呢?

于是乎,我在不存在的网站Google中搜索Python用来写游戏的库,发现了一个知乎问答:为什么针对python的cocos2d教程那么少啊,还有关于cocos2d和pygame的一些疑问?这个回答阐述了比起pygame,用cocos2d-python写游戏的方便性.

但是,Google一搜索,pygame的中文教程一大把,cocos2d-python的中文教程基本为零.
我的心中突然涌现出使命感.我不下地狱,谁下地狱?所以,我作为一个英语四级都没过的人,打开了cocos2d-python英文文档,尽我所能憋出一个中文版,为像我这样的英语渣们谋福利.

(本教程使用Python3作为示范)


本章纯属cocos2d-python的展示,给大家复制代码跑起来爽一把.基础内容等第二章.
对应英文文档:Writing a cocos2d application

1 安装

安装直接用pip安装就很方便了.Linux下:

sudo pip3 install cocos2d

windows的话管理员权限运行cmd然后pip install cocos2d.

2 Hello World

本节内容,展示一段文字.
helloworld
完整代码:

import cocos

#自定义一个层
class HelloWorld(cocos.layer.Layer):
    def __init__(self):
        super( HelloWorld, self ).__init__()

        #新建文字标签用于显示Hello World
        label = cocos.text.Label('Hello, world',
                             #如果要显示中文,需要使用支持中文的字体,比如"微软雅黑"
                             font_name = 'Times New Roman',  
                             font_size=32,
                             #设置锚点为正中间
                             anchor_x='center', anchor_y='center')
        #设置文字标签在层的位置.由于锚点为正中间,即"用手捏"标签的正中间,放到(320,240)的位置
        label.position = 320,240
        #把文字标签添加到层
        self.add( label )


#"导演诞生",即建一个窗口,默认是640*480,不可调整大小
cocos.director.director.init()

#建一个"场景",场景里只有一个hello_layer层,层里已自带文字
main_scene = cocos.scene.Scene( HelloWorld() )
#"导演说Action",让场景工作
cocos.director.director.run(main_scene)

(英文文档不给出完整代码,所以我就自行辛苦调试出来了,带完整注释.)

3 Hello Actions

本节的主要内容是展现"旋转"和"放大缩小".
Hello Actions
完整代码:

import cocos
from cocos.actions import Repeat,Reverse,ScaleBy,RotateBy

#继承了带颜色属性的层类
class HelloWorld(cocos.layer.ColorLayer):
    def __init__(self):
        #层调成蓝色
        super(HelloWorld, self).__init__(64, 64, 224, 255)
        label = cocos.text.Label('Hello, World!',
                                 font_name='Times New Roman',
                                 font_size=32,
                                 anchor_x='center', anchor_y='center')
        label.position = 320,240
        self.add(label)

        #新建一个精灵,在这里是一个小人(英文文档没有给示范图片,所以这个icon.png请自行找个q版小人图片,放在代码同目录下)
        sprite = cocos.sprite.Sprite('icon.png')
        #精灵锚点默认在正中间,只设置位置就好
        sprite.position = 320,240
        #放大三倍,添加到层,z轴设为1,比层更靠前
        sprite.scale = 3
        self.add(sprite, z=1)

        #定义一个动作,即2秒内放大三倍
        scale = ScaleBy(3, duration=2)
        #标签的动作:重复执行放大三倍缩小三倍又放大三倍...Repeat即为重复动作,Reverse为相反动作
        label.do(Repeat(scale + Reverse(scale)))
        #精灵的动作:重复执行缩小三倍放大三倍又缩小三倍...
        sprite.do(Repeat(Reverse(scale) + scale))
        #层的动作:重复执行10秒内360度旋转
        self.do(RotateBy(360, duration=10))


cocos.director.director.init()
main_scene = cocos.scene.Scene( HelloWorld() )             
cocos.director.director.run(main_scene)

4 Handling Events

本节展示键盘鼠标事件.
Handling Events
完整代码:

import cocos
from cocos.director import director
import pyglet

class KeyDisplay(cocos.layer.Layer):

    is_event_handler = True

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

        self.text = cocos.text.Label('Keys: ', font_size=18, x=100, y=280)
        self.add(self.text)

        self.keys_pressed = set()

    def update_text(self):
        key_names = [pyglet.window.key.symbol_string(k) for k in self.keys_pressed]
        self.text.element.text = 'Keys: ' + ','.join(key_names)

    def on_key_press(self, key, modifiers):
        #按下按键自动触发本方法
        self.keys_pressed.add(key)
        self.update_text()

    def on_key_release(self, key, modifiers):
        #松开按键自动触发本方法
        self.keys_pressed.remove(key)
        self.update_text()


class MouseDisplay(cocos.layer.Layer):

    is_event_handler = True

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

        self.text = cocos.text.Label('Mouse @', font_size=18,
                                     x=100, y=240)
        self.add(self.text)

    def on_mouse_motion(self, x, y, dx, dy):
        #dx,dy为向量,表示鼠标移动方向
        self.text.element.text = 'Mouse @ {}, {}, {}, {}'.format(x, y, dx, dy)

    def on_mouse_drag(self, x, y, dx, dy, buttons, modifiers):
        self.text.element.text = 'Mouse @ {}, {}, {}, {}'.format(x, y,buttons, modifiers)

    def on_mouse_press(self, x, y, buttons, modifiers):
        #按下鼠标按键不仅更新鼠标位置,还改变标签的位置.这里使用director.get_virtual_coordinates(),用于保证即使窗口缩放过也能正确更新位置,如果直接用x,y会位置错乱,原因不明
        self.text.element.text = 'Mouse @ {}, {}, {}, {}'.format(x, y,buttons, modifiers)
        self.text.element.x, self.text.element.y = director.get_virtual_coordinates(x, y)


#这次创建的窗口带调整大小的功能
director.init(resizable=True)
main_scene = cocos.scene.Scene( KeyDisplay(), MouseDisplay() )
director.run(main_scene)

默认快捷键

一些默认的快捷键:
Ctrl+f:全屏
Ctrl+s:截图
Ctrl+p:暂停
Ctrl+w:开启/关闭以线框方式显示元素的模式
Ctrl+x:在左下角显示fps帧数
Ctrl+i:启动/关闭内嵌的Python解释器
英文文档:Default Handlers

总结

本章给了三种Hello World的姿势让各位先愉悦起来.下章开始放出一些基础姿势...
(我会努力搬运cocos2d-x版中文手册的链接过来,虽然里面的代码是c++,但各位只要对着中文手册,再阅读我放出的Python版代码就行啦哈哈哈)
(不定期更新)

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

      Development

      No branches or pull requests

        Participants

        @bieberg0n@donglinyin

        Issue actions

          cocos2d-python中文教程:1 Hello World · Issue #10 · bieberg0n/blog